Python多线程ping检测机器存活(windows版)

简介:

由于日常工作经常要回收开发商用完的服务器,之前是用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

效果图如下:

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

本文转自运维笔记博客51CTO博客,原文链接http://blog.51cto.com/lihuipeng/924890如需转载请自行联系原作者


lihuipeng

相关文章
|
5月前
|
数据管理 Linux iOS开发
Splunk Enterprise 9.4.5 (macOS, Linux, Windows) - 机器数据管理和分析
Splunk Enterprise 9.4.5 (macOS, Linux, Windows) - 机器数据管理和分析
182 0
|
C++ Python Windows
在Visual Studio中使用Python(Windows)
在Visual Studio中使用Python(Windows)
165 2
|
12月前
|
数据管理 Linux iOS开发
Splunk Enterprise 9.4.1 (macOS, Linux, Windows) 发布 - 机器数据管理和分析
Splunk Enterprise 9.4.1 (macOS, Linux, Windows) 发布 - 机器数据管理和分析
314 0
Splunk Enterprise 9.4.1 (macOS, Linux, Windows) 发布 - 机器数据管理和分析
|
Windows Python
python获取windows机子上运行的程序名称
python获取windows机子上运行的程序名称
|
Python Windows
python之windows脚本启动bat
python之windows脚本启动bat
|
测试技术 Python
|
运维 网络安全 虚拟化
Windows系统镜像检测修复建议
Windows系统镜像检测修复建议
08-02-19>pe_xscan 增加Windows启动模式和对SuperHidden值检测和报告
08-02-19>pe_xscan 增加Windows启动模式和对SuperHidden值检测和报告
Python 在 Windows 环境下的文件路径问题
在 Python 程序中,我们经常需要对文件进行操作。在 Windows 下,文件目录路径使用反斜杠“\”来分隔。然而,在 Python 代码中,反斜杠“\”是转义符,例如“\n”表示换行符、“\t”表示制表符。这样,如果继续使用“\”表示文件路径,就会产生歧义。
|
Python Windows
在 Windows 平台下打包 Python 多进程代码为 exe 文件的问题及解决方案
在使用 Python 进行多进程编程时,在 Windows 平台下可能会出现将代码打包为 exe 文件后无法正常运行的问题。这个问题主要是由于在 Windows 下创建新的进程需要复制父进程的内存空间,而 Python 多进程机制需要先完成父进程的初始化阶段后才能启动子进程,所以在这个过程中可能会出现错误。此外,由于没有显式导入 Python 解释器,也会导致 Python 解释器无法正常工作。为了解决这个问题,我们可以使用函数。
717 5

推荐镜像

更多