做运维,常常要通过ping来检测一堆主机是否在线,于是分享个小脚本,分别写了shell和python的,方便大家使用。
Shell版本
#!/bin/bash host_list='host_list.txt' ping_log='ping_log.txt' ping_count_success=0 ping_count_fail=0 ping_max_count=1 grep -Ev '^#' ${host_list} | ( while read -r ip_addr do echo -n "Ping ${ip_addr}..." ping -c ${ping_max_count} ${ip_addr} 2>&1 ret_val=$? if [ ${ret_val} -ne 0 ] then echo -e "${ip_addr}\tDOWN" >> ${ping_log} let ping_count_fail+=1 continue fi echo -e "${ip_addr}\tUP" >> ${ping_log} let ping_count_success+=1 done echo -e "Ping success:\t${ping_count_success}\nPing fail:\t${ping_count_fail}\n" >> $ping_log )
Python版本
import os,sys import subprocess,cmd ping_log = open('ping_log.txt','w+') ping_count_success,ping_count_fail = 0,0 def ping_host(): global ping_count_success,ping_count_fail f = open("host_list.txt","r") lines = f.readlines() for line in lines: line=line.strip('\n') ret = subprocess.call("ping -c 1 -w 1 %s" % line,shell=True,stdout=subprocess.PIPE) if ret == 0: str = '%s\tUP' % line ping_log.write(str+'\n') ping_count_success += 1 elif ret == 1: str = '%s\tDOWN' % line ping_log.write(str+'\n') ping_count_fail += 1 f.close() ping_host() ping_log.write('Ping success:\t'+str(ping_count_success)+'\n'+'Ping fail:\t'+str(ping_count_fail)+'\n') ping_log.close()
注意
- 在Windows下,使用“ping -n”而不是“ping -c”
- 待ping的主机列表host_list.txt和脚本在同一目录
10.10.200.251 10.10.200.252 10.10.200.1 baidu.com 10.10.200.8 10.10.200.254 olzl.net
原创文章禁止转载:技术学堂 » 批量ping主机的脚本(shell版&python版)