帮运维的朋友写的简单脚本工具,最终结果输出到当前目录的result.txt中。
需要创建服务端列表文件server_list.json,否则会报错:

server_list.json文件内容:

{"servers":[
    "baidu.com",
    "taobao.com",
    "qq.com",
    "$192.168.0.1:3",
    "$192.168.1.10:13"
]}

其中$192.168.1.10:13表示从192.168.1.10检测到192.168.1.13

脚本如下:

#!/usr/bin/python
# encoding=utf-8
import json
import os
import subprocess

global_ok  = []
global_err = []
global_server_dict = {}

def pingServerCall(server):
    fnull = open(os.devnull, 'w')
    result = subprocess.call('ping '+server+' -c 2', shell = True, stdout = fnull, stderr = fnull)
    if result:
        print 'check [server]:%s\t\t \033[1;31m err \033[0m...' % server
        global_err.append(server)
    else:
        print 'check [server]:%s\t\t \033[1;32mok \033[0m...' % server
        global_ok.append(server)
    fnull.close()


if __name__=='__main__':
    with open("server_list.json",'r') as load_f:
        global_server_dict = json.load(load_f)
    if global_server_dict:
        for serv in global_server_dict["servers"]:
            if serv[0] == '$':
                serv_p = serv.split(':')
                serv_p[0] = serv_p[0][1:]
                serv_l = serv_p[0].split('.')
                serv_str_l = serv_l[:len(serv_l)-1]
                for i in xrange(int(serv_l[len(serv_l)-1]),int(serv_p[1])+1):
                    pingServerCall('.'.join(serv_str_l)+'.'+str(i))
            else:
                pingServerCall(serv)
    with open("result.txt",'w') as result_f:
        result_f.writelines("---------- SUCCESS ----------\n")
        for serv in global_ok:
            result_f.write(serv+"\n")
        result_f.writelines("\n---------- ERROR ----------\n")
        for serv in global_err:
            result_f.write(serv+"\n")