Python 练习1--通过多线程来ping 地址列表
#Time: 2020/03/05
#Author: Xiaohong
#运行环境: OS: Win7 64位 专业版Pack1
# Python: 3.7
功能:利用多线程,来ping 文件中的地址列表
主程序如下:重点在第14 行、第28 行
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import threading
import os
import platform
global unreachip,reachip,platOS
unreachip=list() #保存无法ping通的ip list
reachip=list() #保存可以ping通的ip list
#根据不同的OS,调用不同的命令语句
def is_reacheable(ip):
if platOS=='Windows':
backinfo = subprocess.os.system('ping -n 1 -w 1 %s >nul' % ip) # 实现pingIP地址的功能,-n1指发送报文一次,-w1指等待1毫秒
else:
backinfo = subprocess.call('ping -c 1 -w 1 %s >nul' % ip) # 实现pingIP地址的功能,-c1指发送报文一次,-w1指等待1毫秒
if backinfo: #返回值非0,代表无法pingt通
unreachip.append(ip)
else: #返回值为0,代表pingt通
reachip.append(ip)
def main():
with open('ip.txt') as f: #从文本中取出ip地址
lines = f.readlines()
threads = []
for line in lines:
#启用线程,来调用
thr = threading.Thread(target=is_reacheable, args=(line.strip(),))
thr.start()
threads.append(thr)
for thr in threads:
thr.join()
if __name__ == '__main__':
if platform.system()=='Linux':
platOS='Linux'
else:
platOS = 'Windows'
main()
print(platOS)
print('UnreachIP:')
print(unreachip)
print('Reachip:')
print(reachip)
输出如下: