백엔드 개발 파이썬 튜토리얼 python实现探测socket和web服务示例

python实现探测socket和web服务示例

Jun 06, 2016 am 11:29 AM
socket 웹 서비스

操作系统:linux
软件环境:Python 2.7.3

用法:

代码如下:


$ ./MonSocket.py
# This is check the URI or Socket of the script  #
Usage:
      ./MonSocket.py -d URL; This is Http protocol
      ./MonSocket.py -s socket IP or domain; This is Socket protocol
      ./MonSocket.py -p port; This is Socket port
      ./MonSocket.py -n ; Total number of requests
      ./MonSocket.py -c ; Number of concurrent requests
      ./MonSocket.py -t ; Timeout time(s),socket default is 1s,http default is 5s
For exampale: ./MonSocket.py -d www.weibo.com/index.php -n 200 -c 10 -t 2
For exampale: ./MonSocket.py -s 10.210.214.249 -p 80 -n 200 -c 50 -t 3

代码:

代码如下:


#!/usr/bin/env python
# encoding: utf-8

#
# Write by 飞奔的蜗牛-Bob

import os,sys
import getopt,re
import socket,threading,urllib2

def usage():
        print '# This is check the URI or Socket of the script  #'
        print 'Usage:'
        print "      %s -d URL; This is Http protocol" %sys.argv[0]
 print "      %s -s socket IP or domain; This is Socket protocol" %sys.argv[0]
 print "      %s -p port; This is Socket port" %sys.argv[0]
 print "      %s -n ; Total number of requests" %sys.argv[0]
 print "      %s -c ; Number of concurrent requests" %sys.argv[0]
 print "      %s -t ; Timeout time(s),socket default is 1s,http default is 5s" %sys.argv[0]
        print "For exampale: %s -d www.weibo.com/index.php -n 200 -c 10 -t 2" %sys.argv[0]
 print "For exampale: %s -s 10.210.214.249 -p 80 -n 200 -c 50 -t 3" %sys.argv[0]

def Detect_url(url,sign):
 if timeout:
  time = int(timeout)
 else:
  time = 5
 urllib2.socket.setdefaulttimeout(time)
 request = urllib2.Request('http://%s' %(url))
 try:
  ret = urllib2.urlopen(request)
 except urllib2.URLError,e:
  if hasattr(e,"reason"):
   port_timeout.append('1')
  elif hasattr(e,"code"):
   if re.findall('^3\d*','%s' %e.code):
    port_normal.append('1')
   if re.findall('^404\d*','%s' %e.code):
    port_404.append('1')
                        if re.findall('^403\d*','%s' %e.code):
                                port_403.append('1')
                        if re.findall('^500\d*','%s' %e.code):
                                port_500.append('1')
   if re.findall('^502\d*','%s' %e.code):
    port_502.append('1')
                        if re.findall('^503\d*','%s' %e.code):
                                port_503.append('1')
  else:  
   port_other.append('1')
 else:
                port_normal.append('1')

def Detect_socket(server,port):
 sign = 0
        if timeout:
                time = int(timeout)
        else:
                time = 1

 socket.setdefaulttimeout(time)
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 try:
  ret = s.connect((server, int(port)))
 except socket.error, e:
  if re.findall('^timed\ out*','%s' %e):
   socket_timeout.append('1')
   sign = 1
  else:
   print '%s' %e
   sys.exit(2)
 else:
  socket_normal.append('1')
  sign = 1
 if sign == 0:
  s.close()

def print_out():
 if url_mod:
  print 'URL:'
         print 'timeout:[%s]' %len(port_timeout)
         print 'normal:[%s]' %len(port_normal)
         print '\033[;31mError_403:[%s]\tError_404:[%s]\033[0m' %(len(port_403),len(port_404))
         print '\033[;31mError_500:[%s]\tError_502:[%s]\tError_503:[%s]\033[0m' %(len(port_500),len(port_502),len(port_503))
  print '\033[;31mError_other:[%s]\033[0m' %len(port_other)

 if sock_mod:
  print 'Socket:'
         print 'timeout:[%s]' %len(socket_timeout)
          print 'normal:[%s]' %len(socket_normal)
    

def main():
 if sock_mod:
  dest_arg1 = sock_mod
  dest_arg2 = dport
  dest_function = Detect_socket  
 elif url_mod:
  dest_arg1 = url_mod
  dest_arg2 = ''
  dest_function = Detect_url
 else:
  sys.exit()

 total = int(dcount)
 concurrent = int(dconcurrent)
        n = 0
        sign = 0
 lastnu = total%concurrent


        while 1:

                threads = []
                if n + concurrent > total:
                        nloops = range(n,total)
                        sign = 1
                else:
                        nloops = range(n,n+concurrent)

                for i in nloops:
                        t = threading.Thread(target=dest_function,args=(dest_arg1,dest_arg2))
                        threads.append(t)
                if sign == 1:
                        th_nu = lastnu
                else:
                        th_nu = concurrent

                for i in range(th_nu):
                        threads[i].start()

                for i in range(th_nu):
                        threads[i].join()

                n = n + concurrent

                if sign == 1:
                        break

 print_out()


if __name__=='__main__':
 try:
  opts,args=getopt.getopt(sys.argv[1:],"hd:s:p:n:c:t:")
 except getopt.GetoptError:
  usage()
  sys.exit(2)

 port_timeout = []
 port_normal = []
 port_403= []
 port_404 = []
 port_500 = []
 port_502 = []
 port_503 = []
 port_other = []
 socket_normal = []
 socket_timeout = []
 dcount = 0
 url_mod = ''
 sock_mod = ''
 dport = ''
 dconcurrent = 0
 timeout = 0

 if opts:
  for opt,arg in opts:
   if opt == '-h':
    usage()
    sys.exit()
   if opt == '-d':
    url_mod = arg
   if opt == '-s':
    sock_mod = arg
   if opt == '-p':
    dport = arg
   if opt == '-n':
    dcount = arg
   if opt == '-c':
    dconcurrent = arg
   if opt == '-t':
    timeout = arg
  if url_mod and dcount and dconcurrent:
   main()
  elif sock_mod and dport and dcount and dconcurrent:
   main()
  else:
   usage()

        else:
  usage()
  sys.exit()

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP+Socket 시리즈의 IO 다중화 및 웹서버 구현 PHP+Socket 시리즈의 IO 다중화 및 웹서버 구현 Feb 02, 2023 pm 01:43 PM

이 기사에서는 주로 IO 멀티플렉싱을 소개하는 php+socket과 php+socket이 웹 서버를 구현하는 방법에 대한 관련 지식을 제공합니다. 관심 있는 친구들은 아래를 살펴보시면 모두에게 도움이 되길 바랍니다.

PHP와 SOAP를 사용하여 웹 서비스 호출 및 개발을 구현하는 방법 PHP와 SOAP를 사용하여 웹 서비스 호출 및 개발을 구현하는 방법 Jun 25, 2023 am 09:59 AM

웹 개발 분야에서 웹 서비스는 다양한 애플리케이션이 서로 통신하여 보다 복잡하고 강력한 시스템을 구축할 수 있도록 하는 매우 중요한 기술입니다. 이 기사에서는 PHP와 SOAP를 사용하여 웹 서비스 호출 및 개발을 구현하는 방법을 심층적으로 살펴보겠습니다. SOAP(SimpleObjectAccessProtocol)는 서로 다른 애플리케이션 간의 정보 교환에 사용되는 XML 기반 프로토콜입니다. SOAP는 중요한 웹 서비스 표준입니다.

Python의 소켓 및 소켓 서버를 사용하는 방법 Python의 소켓 및 소켓 서버를 사용하는 방법 May 28, 2023 pm 08:10 PM

1. TCP 프로토콜 기반 소켓 프로그래밍 1. 소켓 워크플로는 서버 측에서 시작됩니다. 서버는 먼저 소켓을 초기화한 다음 포트에 바인드하고 포트를 수신하며 차단을 위해 승인을 호출하고 클라이언트가 연결될 때까지 기다립니다. 이때 클라이언트가 Socket을 초기화한 후 서버에 연결(connect)하면, 연결에 성공하면 클라이언트와 서버 간의 연결이 성립된다. 클라이언트는 데이터 요청을 보내고, 서버는 요청을 받아 요청을 처리한 후 클라이언트에 응답 데이터를 보내고, 클라이언트는 데이터를 읽고 마지막으로 연결을 종료합니다. 이를 구현하려면 다음 Python 코드를 사용하세요. : importso

Spring Boot+Vue를 사용하여 소켓 알림 푸시를 구현하는 방법 Spring Boot+Vue를 사용하여 소켓 알림 푸시를 구현하는 방법 May 27, 2023 am 08:47 AM

SpringBoot 측의 첫 번째 단계는 종속성을 도입하는 것입니다. 먼저 WebSocket에 필요한 종속성과 com.alibabafastjson1.2.73org.springframework.bootspring-boot-starter-websocket 출력 형식을 처리하기 위한 종속성을 도입해야 합니다. 두 번째 단계는 WebSocket 구성 클래스 importorg를 생성하는 것입니다. springframework.context.annotation.Bean;importorg.springframework.context.annotation.Config

PHP 소켓에 연결할 수 없는 경우 수행할 작업 PHP 소켓에 연결할 수 없는 경우 수행할 작업 Nov 09, 2022 am 10:34 AM

PHP 소켓을 연결할 수 없는 문제에 대한 해결책: 1. PHP에서 소켓 확장이 활성화되어 있는지 확인하십시오. 2. php.ini 파일을 열고 "php_sockets.dll"이 로드되었는지 확인하십시오. 3. "php_sockets.dll"의 주석을 제거하십시오. ".

PHP와 Socket을 이용한 실시간 파일 전송 기술 연구 PHP와 Socket을 이용한 실시간 파일 전송 기술 연구 Jun 28, 2023 am 09:11 AM

인터넷이 발전하면서 파일 전송은 사람들의 일상 업무와 오락에 없어서는 안 될 부분이 되었습니다. 그러나 이메일 첨부나 파일 공유 웹사이트와 같은 기존 파일 전송 방법에는 특정 제한이 있으며 실시간 및 보안 요구 사항을 충족할 수 없습니다. 따라서 실시간 파일 전송을 달성하기 위해 PHP 및 소켓 기술을 사용하는 것이 새로운 솔루션이 되었습니다. 이 기사에서는 실시간 파일 전송을 달성하기 위해 PHP 및 소켓 기술을 사용하는 기술 원리, 장점 및 응용 시나리오를 소개하고 구체적인 사례를 통해 이 기술의 구현 방법을 보여줍니다. 기술

C#의 일반적인 네트워크 통신 및 보안 문제와 솔루션 C#의 일반적인 네트워크 통신 및 보안 문제와 솔루션 Oct 09, 2023 pm 09:21 PM

C#의 일반적인 네트워크 통신 및 보안 문제와 해결 방법 오늘날 인터넷 시대에 네트워크 통신은 소프트웨어 개발에 없어서는 안 될 부분이 되었습니다. C#에서는 일반적으로 데이터 전송 보안, 네트워크 연결 안정성 등과 같은 일부 네트워크 통신 문제가 발생합니다. 이 문서에서는 C#의 일반적인 네트워크 통신 및 보안 문제에 대해 자세히 설명하고 해당 솔루션과 코드 예제를 제공합니다. 1. 네트워크 통신 문제 네트워크 연결 중단: 네트워크 통신 과정에서 네트워크 연결이 중단될 수 있으며, 이로 인해

PHP+Socket 시리즈는 클라이언트와 서버 간의 데이터 전송을 구현합니다. PHP+Socket 시리즈는 클라이언트와 서버 간의 데이터 전송을 구현합니다. Feb 02, 2023 am 11:35 AM

이 기사에서는 php+socket에 대한 관련 지식을 제공합니다. 주로 소켓이 무엇인지 소개합니다. php+socket은 클라이언트-서버 데이터 전송을 어떻게 실현합니까? 관심 있는 친구들은 아래를 살펴보시면 모두에게 도움이 되길 바랍니다.

See all articles