net

本文介绍了一个Python脚本,用于定期检查预设主机列表的网络连通性和特定端口的开放状态。通过多线程并发执行ping命令及端口连接测试,该脚本能够高效地完成网络健康监测任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



import os,socket,time
import threading
def check_port(host,port):
    s = None
    for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error, msg:
            s = None
            print str(msg)
            continue
        try:
            s.settimeout(2)
            s.connect(sa)
        except socket.error, msg:
            print str(msg)
            s.close()
            s = None
            continue
        break
    if s is None:
        return 0
    s.close()
    return 1
def ping_server(ip):
    cmd = """
    ping  -c 50 %s|egrep "received|mdev" | sed "s,^,%s : ," >> %s/%s_ping.log
    """ % (ip,time.ctime(time.time()),logs_dir,ip)
    print cmd
    os.popen(cmd)
def check_network():
    check_ip_list = get_hosts()
    thread_pool = []
    for i in range(len(check_ip_list)):
        ip = check_ip_list[i]
        print ip
        th = threading.Thread(target=ping_server,args=(ip,) ) ;
        thread_pool.append(th)
    for i in range(len(check_ip_list)):
        thread_pool[i].deamon = True
        thread_pool[i].start()
def get_hosts():
        hosts_list = ["101.0.11.105","101.0.11.138","101.0.11.103"]
        return hosts_list
def get_hosts_ports():
        hosts_ports_list = ["101.0.11.105:2181","101.0.11.138:2181","101.0.11.103:2181"]
        return hosts_ports_list
def check_server_port():
    port_file = open("%s/check_port.log"%(logs_dir),'a')
    dt = time.ctime(time.time())
    checklist = get_hosts_ports()
    for checkitem in checklist:
        host, port = checkitem.split(':')
        if check_port(host, port):
            port_file.write('%s connect to %s  success\n'%(dt,checkitem))
        else:
            port_file.write('%s connect to %s  fail'%(dt,checkitem))
def check_health():
    while True:
        check_server_port()
        check_network()
        time.sleep(60)
if __name__ == '__main__':
    logs_dir = '/home/master/ruson/pinglogs'
    if not (os.path.exists(logs_dir)):
        os.makedirs(logs_dir)
    check_health()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值