scanner.py脚本分享,检测端口 检测ping机器存活

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import thread
import logging
import string
import os
import sys
import time
from multiprocessing import Queue
from IPy import IP
import socket
socket.setdefaulttimeout(2)
q = Queue()
portlist=[3306,3307]
ip = IP('10.0.0.0/16')
#print(ip.len())
for x in ip:
   q.put(x)
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logfile = 'scanner.log'
fh = logging.FileHandler(logfile, mode='w')
logger.addHandler(fh)

def scanner( threadName):
   while not q.empty():
       nowip=q.get().strNormal(0)
       for port in portlist:
             try:
               client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
               client.connect((nowip,port))
               client.close()
        # print(nowip,"ok")
               logger.info(nowip+":"+str(port))
             except Exception as err:
                print nowip+":"+str(port)+" pass"
                continue
def ping( threadName):
    while not q.empty():
       nowip=q.get().strNormal(0)
       cmd="/usr/bin/ping -c 1 -w 1 "+nowip
       if(os.system(cmd)>0):
          print nowip+" ping error"
          logger.info(nowip+" ping error")
       else:
         print nowip+"ping ok"
              
       

def main():
   if(len(sys.argv)<2 or (sys.argv[1]<>"scanner" and sys.argv[1]<>"ping")):
      print "参数缺失,请输入scanner或者ping"
      os._exit(1)
   for i in range(1200):
     try:
       if sys.argv[1]=="scanner":
           thread.start_new_thread(scanner, ("Thread"+str(i), ) )
       else:
           thread.start_new_thread(ping, ("Thread"+str(i), ) )
     except:
       print ("Error: start thread") 
if __name__ == '__main__':   
   main()
   #time.sleep(5)

 

你可能感兴趣的:(python)