首先需要的是一个纯文本的IP列表
127.0.0.1
10.2.2.1
10.2.2.3
保存成iplist.txt
然后创建
ipverify.sh
文件
#!/bin/bash
for i in `cat $1`
do
ping=`ping -c 1 $i | grep loss | awk '{print $6}' | awk -F "%" '{print $1}'`
if [ ! $ping -eq 0 ]; then
echo ping $i false
fi
done
调用 ./ipverify.sh iplist.txt
由于这是顺序执行的,连续ping几百个IP,返回全部会非常慢,下面是用python实现的多线程程序(因为,是判断的ping的输出,仅适用于linux环境)
#encoding:utf-8
from threading import Thread
import datetime
import os
import sys
class PING(Thread):
def __init__(self,ip):
Thread.__init__(self)
self.ip = ip
def run(self):
Curtime=datetime.datetime.now()
pingStr = 'ping -c2 %s '% self.ip
result = os.popen(pingStr).readlines()
resultStr = ''.join(result)
index = resultStr.index("received")
status = resultStr[index-2:index-1]
if status == 0:
print("%s 超时" % (self.ip))
elif status == '2':
print ("%s 可达" % (self.ip))
else:
print("%s 不可达" % (self.ip))
#多线程同时执行
def getIPs():
filepath = sys.argv[1]
print(filepath)
#filepath= "E://1.txt"
file = open(filepath)
b=[]
for line in file.readlines():
b.append( line.strip('\n'))
file.close()
return b
if __name__ == "__main__":
T_thread=[]
for i in getIPs():
t=PING(i)
T_thread.append(t)
for i in range(len(T_thread)):
T_thread[i].start()