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使用rabbitmq实现网络爬虫示例
Feb 20 Python
Python中转换角度为弧度的radians()方法
May 18 Python
python编码总结(编码类型、格式、转码)
Jul 01 Python
Pandas中DataFrame的分组/分割/合并的实现
Jul 16 Python
由面试题加深对Django的认识理解
Jul 19 Python
Django中在xadmin中集成DjangoUeditor过程详解
Jul 24 Python
python tkinter canvas使用实例
Nov 04 Python
python代码如何实现余弦相似性计算
Feb 09 Python
python对文件的操作方法汇总
Feb 28 Python
Python几种常见算法汇总
Jun 02 Python
python3:excel操作之读取数据并返回字典 + 写入的案例
Sep 01 Python
python 办公自动化——基于pyqt5和openpyxl统计符合要求的名单
May 25 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
可快速识别放射性物质-国外大神教你diy一个开放式辐射探测器
2020/03/12 无线电
在PHP中使用与Perl兼容的正则表达式
2006/11/26 PHP
PHP 模拟登陆MSN并获得用户信息
2009/05/16 PHP
php统计文件大小,以GB、MB、KB、B输出
2011/05/29 PHP
控制PHP的输出:缓存并压缩动态页面
2013/06/11 PHP
解决PHP4.0 和 PHP5.0类构造函数的兼容问题
2013/08/01 PHP
ThinkPHP权限认证Auth实例详解
2014/07/22 PHP
SSO单点登录的PHP实现方法(Laravel框架)
2016/03/23 PHP
Yii 使用intervention/image拓展实现图像处理功能
2019/06/22 PHP
document.onreadystatechange事件的用法分析
2009/10/17 Javascript
javascript进行四舍五入方法汇总
2014/12/16 Javascript
使用javascript实现Iframe自适应高度
2014/12/24 Javascript
js使用post 方式打开新窗口
2015/02/26 Javascript
详解JavaScript中基于原型prototype的继承特性
2016/05/05 Javascript
js控制文本框禁止输入特殊字符详解
2017/04/07 Javascript
深入理解Commonjs规范及Node模块实现
2017/05/17 Javascript
ReactNative实现Toast的示例
2017/12/31 Javascript
js console.log打印对象时属性缺失的解决方法
2019/05/23 Javascript
JS中数组实现代码(倒序遍历数组,数组连接字符串)
2019/12/29 Javascript
详解Java中String JSONObject JSONArray List转换
2020/11/13 Javascript
VueCli生产环境打包部署跨域失败的解决
2020/11/13 Javascript
Python中的os.path路径模块中的操作方法总结
2016/07/07 Python
深入浅析Python获取对象信息的函数type()、isinstance()、dir()
2018/09/17 Python
python得到qq句柄,并显示在前台的方法
2018/10/14 Python
Python + selenium + requests实现12306全自动抢票及验证码破解加自动点击功能
2018/11/23 Python
Python魔法方法功能与用法简介
2019/04/04 Python
python实现祝福弹窗效果
2019/04/07 Python
python__name__原理及用法详解
2019/11/02 Python
2020最新pycharm汉化安装(python工程狮亲测有效)
2020/04/26 Python
CSS3属性使网站设计增强同时不消弱可用性
2009/08/29 HTML / CSS
俄罗斯三星品牌商店:Samsungstore
2020/04/05 全球购物
输入N,打印N*N矩阵
2012/02/20 面试题
复核员上岗演讲稿
2014/01/05 职场文书
节能标语大全
2014/06/21 职场文书
人与自然的观后感
2015/06/18 职场文书
解读Vue组件注册方式
2021/05/15 Vue.js