为了账号安全,请及时绑定邮箱和手机立即绑定

多线程。如何正确同时ping多个IP?

多线程。如何正确同时ping多个IP?

jeck猫 2021-06-07 08:23:33
我想制作可以 ping 远程 IP 的控制台程序。我使用多线程同时 ping 多个 IP。当所有IP都可达时,一切看起来都不错,但是当一个IP不可达时,其他线程必须等待很长时间,直到错误的ping完成(我故意选择了一个无法ping通的IP),由于join方法,它会等到所有线程结束。当我刚刚删除 join 方法时,我的 PC 崩溃了。我做了以下工作来解决这个问题(创建了无限 ping 函数,因此由于内部的无限方法而无法结束 thead)并在代码中保留 joinmethod,它工作正常,但有没有更好的选择?我想该解决方案在资源消耗或任何其他方面可能存在一些缺点。我的工作代码,我对此表示怀疑:下面的方法b在 t100 时间间隔内对(IP)执行一次 ping 操作def do_ping(b,t100):    a=os.system(f"ping -n 1 {b}")    h=good_time(time.localtime(),1)    with open(f"noob_{h}_{b}.txt",mode="a") as f:        t=good_time(time.localtime(),0)        if(a==int(0)):             f.write(f"The remote destination {b} is reachable, everyting is enter code hereOKAY. {t} \n")        elif(a==int(1)):            f.write(f"Ping {b} failed! {t} \n")             time.sleep(int(t100))无限 ping 一个 IP 地址:def ping1(b,t100):     while(True):             IP_Op.do_ping(b,t100)主程序:while(True):    treadsN=[]    for i in b:b 是一个 IP 列表(整个程序还将结果写入文件,如果 ping 长时间失败,将来会发送电子邮件treadsN.append(threading.Thread(target=IP_Op.ping1, args=(i,3)))     for i in treadsN:          i.start()      for i in treadsN:           i.join()
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

您不需要线程来执行多个进程 - 只需使用subprocess.Popen- 它不会像 那样阻塞os.system,因此您可以多次运行它并且它们都将并行运行。


如果b是一个包含所有 ip 的列表:


import subprocess


while True:

    result = []

    for ip in b:

        p = subprocess.Popen(['ping', '-n', '1', ip]) # runs ping in background

        result.append(p) # store the Popen object for later result retrieval

这将ping在后台运行多个进程!现在你只需要解析结果:


    try_again = []

    for ip, p in zip(b, result):

        if p.wait() == 0:

            print(ip, 'is ok!')

        else:

            print(ip, 'failed!')

            try_again.append(ip)

然后,您可以根据需要重复失败的那些:


    if not try_again:

        break

    time.sleep(100)

    b = try_again


查看完整回答
反对 回复 2021-06-09
  • 1 回答
  • 0 关注
  • 306 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号