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 ip正则式
May 07 Python
Python的Django框架中自定义模版标签的示例
Jul 20 Python
浅谈python中set使用
Jun 30 Python
基于python进行桶排序与基数排序的总结
May 29 Python
python reverse反转部分数组的实例
Dec 13 Python
详解Python基础random模块随机数的生成
Mar 23 Python
搞定这套Python爬虫面试题(面试会so easy)
Apr 03 Python
python3中datetime库,time库以及pandas中的时间函数区别与详解
Apr 16 Python
tensorflow模型的save与restore,及checkpoint中读取变量方式
May 26 Python
python代码区分大小写吗
Jun 17 Python
Windows下PyCharm配置Anaconda环境(超详细教程)
Jul 31 Python
python神经网络编程之手写数字识别
May 08 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读MYSQL中文乱码的解决方法
2006/12/17 PHP
php模拟socket一次连接,多次发送数据的实现代码
2011/07/26 PHP
php中Smarty模板初体验
2011/08/08 PHP
setcookie中Cannot modify header information-headers already sent by错误的解决方法详解
2013/05/08 PHP
PHP 错误处理机制
2015/07/06 PHP
Thinkphp5+uploadify实现的文件上传功能示例
2018/05/26 PHP
微信公众平台开发教程①获取用户Openid及个人信息图文详解
2019/04/10 PHP
IE8下关于querySelectorAll()的问题
2010/05/13 Javascript
扩展jquery实现客户端表格的分页、排序功能代码
2011/03/16 Javascript
使用js实现一个可编辑的select下拉列表
2014/02/20 Javascript
node.js入门实例helloworld详解
2015/12/23 Javascript
三分钟带你玩转jQuery.noConflict()
2016/02/15 Javascript
js基于cookie方式记住返回页面用法示例
2016/05/27 Javascript
jQuery实现鼠标滚动图片延迟加载效果附源码下载
2016/06/28 Javascript
微信小程序 仿猫眼实现实例代码
2017/03/14 Javascript
Bootstrap模态框(Modal)实现过渡效果
2017/03/17 Javascript
利用JS做网页特效_大图轮播(实例讲解)
2017/08/09 Javascript
详谈Vue.js框架下main.js,App.vue,page/index.vue之间的区别
2020/08/12 Javascript
[01:02:34]TFT vs VGJ.T Supermajor 败者组 BO3 第二场 6.5
2018/06/06 DOTA
[原创]教女朋友学Python(一)运行环境搭建
2017/11/29 Python
python开发之anaconda以及win7下安装gensim的方法
2019/07/05 Python
Python寻找路径和查找文件路径的示例
2019/07/10 Python
Flask框架路由和视图用法实例分析
2019/11/07 Python
Python计算公交发车时间的完整代码
2020/02/12 Python
pandas和spark dataframe互相转换实例详解
2020/02/18 Python
Python中bisect的用法及示例详解
2020/07/20 Python
css3旋转木马_动力节点Java学院整理
2017/07/12 HTML / CSS
Ann Taylor官方网站:美国最大的女性产品制造商之一
2016/09/14 全球购物
LTD Commodities:礼品,独特发现,家居装饰,家用器皿
2017/08/11 全球购物
为什么使用接口?
2014/08/13 面试题
2014年最新学习全国两会精神心得
2014/03/17 职场文书
公关活动策划方案
2014/05/25 职场文书
优秀教师先进材料
2014/12/16 职场文书
2015年高校保卫处工作总结
2015/07/23 职场文书
python基础之停用词过滤详解
2021/04/21 Python
pytorch 预训练模型读取修改相关参数的填坑问题
2021/06/05 Python