由于日常工作经常要回收开发商用完的服务器,之前是用nmap检测开发商有没有关机的,感觉挺麻烦的,今天拿python写了一个脚本专门对付回收服务器的:

原理:把准备回收的机器写入hosts.txt文件里,python脚本读取hosts.txt文件的内容,匹配出里面的ip,然后通过ping测试服务器是否没关机

 
  
  1. #!/usr/bin/env python 
  2.  
  3. from threading import Thread 
  4. import subprocess 
  5. from Queue import Queue 
  6. import re 
  7. import sys 
  8.  
  9. num_threads = 10 
  10. queue = Queue() 
  11.  
  12. def pinger(i,q): 
  13.     while True
  14.         ip = q.get() 
  15.         ret = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=open(r'ping.temp','w'), stderr=subprocess.STDOUT) 
  16.         if ret == 0
  17.             print "%s: is alive" % ip 
  18.         else
  19.             print "%s is down" % ip 
  20.         q.task_done() 
  21.  
  22. for i in range(num_threads): 
  23.     worker = Thread(target=pinger, args=(i, queue)) 
  24.     worker.setDaemon(True
  25.     worker.start() 
  26.      
  27.  
  28. host_file = open(r'hosts.txt','r'
  29. ips = [] 
  30. re_obj = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
  31. for line in host_file: 
  32.     for match in re_obj.findall(line): 
  33.         ips.append(match) 
  34. host_file.close() 
  35.  
  36.  
  37. for ip in ips: 
  38.     queue.put(ip) 
  39.      
  40. print "Main Thread Waiting" 
  41. queue.join() 
  42. print "Done" 
  43.  
  44. result = raw_input("Please press any key to exit"
  45. if result: 
  46.     sys.exit(0

效果图如下:

适合自己的需求,高手就路过吧~