在windows上运行的Python ping循环脚本,

2024-06-02 13:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个python脚本,在这个脚本中输入几个ip并连续ping它们,然后输出一个结果。我想让它循环通过ips,只是继续,直到停止,但我不能让它发生。此外,输出if语句始终返回false。建议/帮助?在

    import os
    import subprocess

    print ("PingKeep will run a Ping request every 5 seconds on a round of          IP's until told to stop (using ctrl+c)." ) 
    ips=[]
    n=int(input("How many IP's are we checking: "))
    for i in range(1,n+1):
    x=str(input("Enter IP number "+str(i)+": "))
    ips.append(x)
   for ping in range(0,n):
  ipd=ips[ping]
res = subprocess.call(['ping', '-n', '3', ipd])
if ipd in str(res):
    print ("ping to", ipd, "OK")
elif "failure" in str(res):
    print ("ping to", ipd, "recieved no responce")
else:
    print ("ping to", ipd, "failed!")

Tags: toinimportip脚本forinputif
2条回答

不确定代码结束时您想做什么,但如果您在ping失败时捕获CalleddProcessError,您将知道ping失败的时间,不完全确定您希望如何结束程序,这样我就留给您:

from subprocess import check_call, CalledProcessError,PIPE

print("PingKeep will run a Ping request every 5 seconds on a round of          IP's until told to stop (using ctrl+c).")
import time
n = int(input("How many IP's are we checking: "))
ips = [input("Enter IP number {}: ".format(i)) for i in range(1, n + 1)]

while True:
    for ip in ips:
        try:
            out = check_call(['ping', '-n', '3', ip],stdout=PIPE)
        except CalledProcessError as e:
            # non zero return code will bring us here
            print("Ping to {} unsuccessful".format(ip))
            continue
        # if we are here ping was successful
        print("Ping to {} ok".format(ip))
    time.sleep(5)

首先,你的压痕都弄错了,请修一下。在

第二,为什么每次运行使用-n 3ping 3次?如果前两次ping失败,而第三次ping返回良好,则仍算作成功,仅供参考。在

第三,你只是在输入的IP中循环,而不是无限循环。我建议这样做:

while True:

那将永远循环。你可以把你的循环放在这个循环里,通过IP循环。在

第四,什么输出语句返回false?我没看到这样的事。而且,你的失败测试是完全错误的。如果ping超时,ping可执行文件将返回一个返回代码1,但不会有任何输出“failure”。res将永远是0或1,而不是字符串。在

第五,在你努力了之后,用我给你的见解再写一次这个问题。在

相关问题 更多 >