Python检测服务器是否ping通的2种方法:
1、第一种比较挫,就是用ping,python调用shell,这个适用于较少的服务器数量,几百台已经很慢了(当然是说python同步的方法,要是nodejs异步方式还是很快的,但是nodejs CPU计算不行,所以尝试了下只能200台左右的服务器可以同时ping,再多的话程序也会崩掉)
shell脚本再简单不过了,ping.sh如下:
#!/bin/bash
PING=`ping -c 3 $1 | grep '0 received' | wc -l`
echo $PING
其实很简单,ping 3个包,只要ping通,上述返回的结果就不是0。$1是传入的第一个参数,即IP
思路很简单的,从数据库读出IP 列表,然后调用上述脚本:
#检查ip能否ping通
#0:正常,1:ping不通
def check_ip_ping():
? ? record = get_ip() #从数据库中读取的IP列表
? ? for i in range(0,len(record)):
? ? ? ? p = subprocess.Popen([r'./ping.sh',record[i]],stdout=subprocess.PIPE)
? ? ? result = p.stdout.read()
? ? ? ? Status = 0
? ? ? ? if result =='1\n':
? ? ? ? ? ? Status = 1
? ? ? ? ? ? #print i,record[i],'----ping failed----'
? ? ? ? else:
? ? ? ? ? ? ping_ok.append(record[i])
? ? ? ? ? ? #print i,record[i],'----ping success----'
? ? ? ? mysql('update ip_connect set Status=%d where IP="%s"'%(Status,record[i]))
还有一种方式与这个差不多,不过没有返回值,直接打印出结果,即用系统命令os.system(cmd)
2、比这种快很多,适合服务器数量较大时使用,fping命令,它是对一个文件的批量ping,瞬间完成的,如果ping不通,那就较慢,日常ping不通的毕竟是少数,所以这个非常适用。来感受一下,它ping的结果,新建一个文件iplist,里面是IP列表,fping结果如下:

其实结果就两个 is alive / is unrreachable ,其它的中间检测时它自己输出的不用理会。
fping.sh :
#!/bin/bash
rm -f result.txt
cat ipmi_ping.txt | fping > result.txt
思路也很简单,将IP列表读取来写进一个iplist文件,然后再对这个文件fping(调用fping.sh)批量执行的结果写进result文件:
def check_online_ip():
? ? ip = mysql('select * from ip_check')
? ? #将IP写进一个文件
? ? if os.path.exists('iplist.txt'):
? ? ? ? os.remove('iplist.txt')
? ? iplist= 'iplist.txt'
? ? for i in range(0,len(ip)):
? ? ? ? with open(iplist, 'a') as f:
? ? ? ? ? ? f.write(ip[i][0]+'\n')
? ? #对文件中的IP进行fping
? ? p = subprocess.Popen(r'./fping.sh',stdout=subprocess.PIPE)
? ? p.stdout.read()
? ? #读result.txt文件,将IP is unreachable的行提取更新mysql状态为1
? ? result = open('result.txt','r')
? ? content = result.read().split('\n')
? ? for i in range(0,len(content)-1):
? ? ? ? tmp = content[i]
? ? ? ? ip = tmp[:tmp.index('is')-1]
? ? ? ? Status = 0
? ? ? ? if 'unreachable' in tmp:
? ? ? ? ? ? Status = 1
? ? ? ? #print i,ip
? ? ? ? mysql('update? ip_check set Status=%d where IP="%s"'%(Status,ip))
? ? print 'check all ipconnectness over!'
将这个搞成计划任务,每天跑几遍,还是挺赞的。 呵呵。。
--------------------------------------分割线 --------------------------------------