由于日常工作经常要回收开发商用完的服务器,之前是用nmap检测开发商有没有关机的,感觉挺麻烦的,今天拿python写了一个脚本专门对付回收服务器的:
原理:把准备回收的机器写入hosts.txt文件里,python脚本读取hosts.txt文件的内容,匹配出里面的ip,然后通过ping测试服务器是否没关机
- #!/usr/bin/env python
- from threading import Thread
- import subprocess
- from Queue import Queue
- import re
- import sys
- import platform
- num_threads = 10
- queue = Queue()
- def pinger(i,q):
- while True:
- ip = q.get()
- if platform.system() == "Linux":
- cmd = "ping -c 1 %s" % ip
- outfile = "/dev/null"
- elif platform.system() == "Windows":
- cmd = "ping -n 1 %s" % ip
- outfile = "ping.temp"
- ret = subprocess.call(cmd, shell=True, stdout=open(outfile,'w'), stderr=subprocess.STDOUT)
- if ret == 0:
- print "%s: is alive" % ip
- else:
- print "%s is down" % ip
- q.task_done()
- for i in range(num_threads):
- worker = Thread(target=pinger, args=(i, queue))
- worker.setDaemon(True)
- worker.start()
- host_file = open(r'hosts.txt','r')
- ips = []
- re_obj = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
- for line in host_file:
- for match in re_obj.findall(line):
- ips.append(match)
- host_file.close()
- for ip in ips:
- queue.put(ip)
- print "Main Thread Waiting"
- queue.join()
- print "Done"
- result = raw_input("Please press any key to exit")
- if result:
- sys.exit(0)
小弟初学,请大家多多指点!