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程序与服务器连接的WSGI接口
Apr 29 Python
Django Admin 实现外键过滤的方法
Sep 29 Python
Python IDLE入门简介
Dec 08 Python
Python基础教程之利用期物处理并发
Mar 29 Python
Python 绘图库 Matplotlib 入门教程
Apr 19 Python
对Python3 解析html的几种操作方式小结
Feb 16 Python
使用Python正则表达式操作文本数据的方法
May 14 Python
Python中PyQt5/PySide2的按钮控件使用实例
Aug 17 Python
Python将列表中的元素转化为数字并排序的示例
Dec 25 Python
使用Keras加载含有自定义层或函数的模型操作
Jun 10 Python
Python-for循环的内部机制
Jun 12 Python
Python无损压缩图片的示例代码
Aug 06 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 删除记录同时删除图片文件的实现代码
2010/05/12 PHP
PHP中的错误处理、异常处理机制分析
2012/05/07 PHP
PHP写的求多项式导数的函数代码
2012/07/04 PHP
PHP register_shutdown_function函数的深入解析
2013/06/03 PHP
通过table标签,PHP输出EXCEL的实现方法
2013/07/24 PHP
PHP去掉json字符串中的反斜杠\及去掉双引号前的反斜杠
2015/09/30 PHP
PHP网站自动化配置的实现方法(必看)
2017/05/27 PHP
PHP实现的多维数组排序算法分析
2018/02/10 PHP
laravel 实现向公共模板中传值 (view composer)
2019/10/22 PHP
php array_map()函数实例用法
2021/03/03 PHP
《JavaScript高级程序设计》阅读笔记(三) ECMAScript中的引用类型
2012/02/27 Javascript
JavaScript的9种继承实现方式归纳
2015/05/18 Javascript
Jquery跨域获得Json的简单实例
2016/05/18 Javascript
探讨跨域请求资源的几种方式(总结)
2016/12/02 Javascript
JavaScript获取URL参数的方法之一
2017/03/24 Javascript
BACKBONE.JS 简单入门范例
2017/10/17 Javascript
Vue中在新窗口打开页面及Vue-router的使用
2018/06/13 Javascript
jQuery实现动画、消失、显现、渐出、渐入效果示例
2018/09/06 jQuery
JavaScript继承与聚合实例详解
2019/01/22 Javascript
react项目如何使用iconfont的方法步骤
2019/03/13 Javascript
使用 webpack 插件自动生成 vue 路由文件的方法
2019/08/20 Javascript
vue-cli3项目配置eslint代码规范的完整步骤
2020/09/10 Javascript
linux环境下安装pyramid和新建项目的步骤
2013/11/27 Python
python使用分治法实现求解最大值的方法
2015/05/12 Python
利用Python查看目录中的文件示例详解
2017/08/28 Python
Python中logging.NullHandler 的使用教程
2018/11/29 Python
详解Python中is和==的区别
2019/03/21 Python
python 叠加等边三角形的绘制的实现
2019/08/14 Python
python使用socket 先读取长度,在读取报文内容示例
2019/09/26 Python
Django后端按照日期查询的方法教程
2021/02/28 Python
土木工程专业大学毕业生求职信
2013/10/13 职场文书
法院反腐倡廉心得体会
2014/09/09 职场文书
县长“四风”对照检查材料思想汇报
2014/10/05 职场文书
保证金退回承诺函格式
2015/01/21 职场文书
大雁塔导游词
2015/02/04 职场文书
2016年班主任新年寄语
2015/08/18 职场文书