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入门教程
Apr 03 Python
Python中类型检查的详细介绍
Feb 13 Python
解决在pycharm中显示额外的 figure 窗口问题
Jan 15 Python
解决在Python编辑器pycharm中程序run正常debug错误的问题
Jan 17 Python
对Pycharm创建py文件时自定义头部模板的方法详解
Feb 12 Python
Pyqt5如何让QMessageBox按钮显示中文示例代码
Apr 11 Python
python中树与树的表示知识点总结
Sep 14 Python
python:动态路由的Flask程序代码
Nov 22 Python
解析PyCharm Python运行权限问题
Jan 08 Python
Python中的整除和取模实例
Jun 03 Python
PyTorch中clone()、detach()及相关扩展详解
Dec 09 Python
python链表类中获取元素实例方法
Feb 23 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
一些常用的Javascript函数
2006/12/22 Javascript
javascript Base类 包含基本的方法
2009/07/22 Javascript
使用js实现按钮控制文本框加1减1应用于小时+分钟
2013/12/09 Javascript
微信小程序 animation API详解及实例代码
2016/10/08 Javascript
Vue数据驱动模拟实现4
2017/01/12 Javascript
详解基于vue-cli配置移动端自适应
2018/01/13 Javascript
vue实现自定义日期组件功能的实例代码
2018/11/06 Javascript
微信小程序云开发 搭建一个管理小程序
2019/05/17 Javascript
Webpack按需加载打包chunk命名的方法
2019/09/22 Javascript
JavaScript ECMA-262-3 深入解析(一):执行上下文实例分析
2020/04/25 Javascript
python实现异步回调机制代码分享
2014/01/10 Python
python提取字典key列表的方法
2015/07/11 Python
Django与遗留的数据库整合的方法指南
2015/07/24 Python
Python操作Access数据库基本步骤分析
2016/09/19 Python
如何优雅地改进Django中的模板碎片缓存详解
2018/07/04 Python
对python捕获ctrl+c手工中断程序的两种方法详解
2018/12/26 Python
Python 变量的创建过程详解
2019/09/02 Python
redis数据库及与python交互用法简单示例
2019/11/01 Python
python 中的[:-1]和[::-1]的具体使用
2020/02/13 Python
Ubuntu中配置TensorFlow使用环境的方法
2020/04/21 Python
详解window.open被浏览器拦截的解决方案
2019/07/18 HTML / CSS
抽象方法、抽象类怎样声明
2014/10/25 面试题
人力资源经理的岗位职责范本
2014/02/28 职场文书
软件毕业生个人鉴定
2014/03/03 职场文书
百日安全活动总结
2014/05/04 职场文书
市政工程技术专业自荐书
2014/07/06 职场文书
新党章的学习心得体会
2014/11/07 职场文书
2014年社区个人工作总结
2014/12/02 职场文书
单位租房协议书范本
2014/12/04 职场文书
2015年药店工作总结
2015/04/20 职场文书
道歉信范文
2015/05/12 职场文书
2016年党员承诺书范文
2016/03/24 职场文书
2016年幼儿园万圣节活动总结
2016/04/05 职场文书
Window server中安装Redis的超详细教程
2021/11/17 Redis
JavaScript流程控制(分支)
2021/12/06 Javascript
Java练习之潜艇小游戏的实现
2022/03/16 Java/Android