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


Posted in Python onMarch 28, 2014

操作系统: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()
Python 相关文章推荐
Python的词法分析与语法分析
May 18 Python
Python的ORM框架SQLObject入门实例
Apr 28 Python
详解Python的Django框架中的模版相关知识
Jul 15 Python
python 调用c语言函数的方法
Sep 29 Python
浅谈pytorch和Numpy的区别以及相互转换方法
Jul 26 Python
CentOS 7 安装python3.7.1的方法及注意事项
Nov 01 Python
python多进程并发demo实例解析
Dec 13 Python
基于spring boot 日志(logback)报错的解决方式
Feb 20 Python
django-csrf使用和禁用方式
Mar 13 Python
python实现猜单词游戏
May 22 Python
python实现人工蜂群算法
Sep 18 Python
pandas时间序列之pd.to_datetime()的实现
Jun 16 Python
python实现目录树生成示例
Mar 28 #Python
python改变日志(logging)存放位置的示例
Mar 27 #Python
使用python删除nginx缓存文件示例(python文件操作)
Mar 26 #Python
python实现ip查询示例
Mar 26 #Python
python fabric实现远程操作和部署示例
Mar 25 #Python
python基础教程之数字处理(math)模块详解
Mar 25 #Python
python操作摄像头截图实现远程监控的例子
Mar 25 #Python
You might like
PHP初学入门
2006/11/19 PHP
Optimizer与Debugger兼容性问题的解决方法
2008/12/01 PHP
php中选择什么接口(mysql、mysqli)访问mysql
2013/02/06 PHP
PHP 如何利用phpexcel导入数据库
2013/08/24 PHP
php 邮件发送问题解决
2014/03/22 PHP
PHP内存缓存功能memcached示例
2016/10/19 PHP
PHP解决中文乱码
2017/04/28 PHP
PHP的RSA加密解密方法以及开发接口使用
2018/02/11 PHP
静态的动态续篇之来点XML
2006/08/15 Javascript
JavaScript的面向对象(二)
2006/11/09 Javascript
从零开始学习jQuery (十) jQueryUI常用功能实战
2011/02/23 Javascript
使用jquery获取网页中图片高度的两种方法
2013/09/26 Javascript
5分钟理解JavaScript中this用法分享
2013/11/09 Javascript
jq实现酷炫的鼠标经过图片翻滚效果
2014/03/12 Javascript
jQuery超精致图片轮播幻灯片特效代码分享
2015/09/10 Javascript
js事件处理程序跨浏览器解决方案
2016/03/27 Javascript
vue项目中使用百度地图的方法
2018/06/08 Javascript
vue实现点击出现操作弹出框的示例
2020/11/05 Javascript
python发送arp欺骗攻击代码分析
2014/01/16 Python
python中的__init__ 、__new__、__call__小结
2014/04/25 Python
Python实现partial改变方法默认参数
2014/08/18 Python
python刷投票的脚本实现代码
2014/11/08 Python
Python实现的桶排序算法示例
2017/11/29 Python
Python 实现数据结构中的的栈队列
2019/05/16 Python
Python socket非阻塞模块应用示例
2019/09/12 Python
CSS3制作炫酷的自定义发光文字
2016/03/28 HTML / CSS
详解Canvas 实现炫丽的粒子运动效果(粒子生成文字)
2018/02/01 HTML / CSS
关于canvas绘制模糊问题的解决方法
2019/09/24 HTML / CSS
祖国在我心中演讲稿600字
2014/05/04 职场文书
2014教师个人自我评价范文
2014/09/13 职场文书
2014年最新离婚协议书范本
2014/10/11 职场文书
2014年网管工作总结
2014/12/11 职场文书
优秀党员推荐材料
2014/12/18 职场文书
2015年乡镇安全生产工作总结
2015/05/19 职场文书
简单聊聊TypeScript只读修饰符
2022/04/06 Javascript
volatile保证可见性及重排序方法
2022/08/05 Java/Android