由于日常工作经常要回收开发商用完的服务器,之前是用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. import platform 
  9.  
  10. num_threads = 10 
  11. queue = Queue() 
  12.  
  13. def pinger(i,q): 
  14.     while True
  15.         ip = q.get() 
  16.         if platform.system() == "Linux"
  17.             cmd = "ping -c 1 %s" % ip 
  18.             outfile = "/dev/null" 
  19.         elif platform.system() == "Windows"
  20.             cmd = "ping -n 1 %s" % ip 
  21.             outfile = "ping.temp" 
  22.         ret = subprocess.call(cmd, shell=True, stdout=open(outfile,'w'), stderr=subprocess.STDOUT) 
  23.         if ret == 0
  24.             print "%s: is alive" % ip 
  25.         else
  26.             print "%s is down" % ip 
  27.         q.task_done() 
  28.  
  29. for i in range(num_threads): 
  30.     worker = Thread(target=pinger, args=(i, queue)) 
  31.     worker.setDaemon(True
  32.     worker.start() 
  33.      
  34.  
  35. host_file = open(r'hosts.txt','r'
  36. ips = [] 
  37. re_obj = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
  38. for line in host_file: 
  39.     for match in re_obj.findall(line): 
  40.         ips.append(match) 
  41. host_file.close() 
  42.  
  43.  
  44. for ip in ips: 
  45.     queue.put(ip) 
  46.      
  47. print "Main Thread Waiting" 
  48. queue.join() 
  49. print "Done" 
  50.  
  51. result = raw_input("Please press any key to exit"
  52. if result: 
  53.     sys.exit(0

小弟初学,请大家多多指点!