【问题标题】:Python ping loop script to run on windows, error在 Windows 上运行的 Python ping 循环脚本,错误
【发布时间】:2015-03-03 18:19:27
【问题描述】:

我正在尝试编写一个 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!")

【问题讨论】:

  • 您需要注意缩进。
  • 我知道,我试图直接从我的代码中复制它,但格式错误。

标签: python windows loops ping continuous


【解决方案1】:

首先,你的压痕全部搞砸了,请修复它。

第二,为什么每次使用-n 3 ping 3 次?如果前 2 次 ping 失败,但第三次返回正常,则仍算成功,仅供参考。

第三,您只是循环输入的 IP,而不是无限循环。我推荐这样的东西:

while True:

这将永远循环。您可以将循环放在该循环中以循环通过 IP。

第四,什么输出语句返回假?我没有看到那样的东西。此外,您的失败测试是完全错误的。如果 ping 超时,ping 可执行文件将返回返回码 1,但不会输出“失败”。 res 永远只会是 0 或 1,永远不会是字符串。

第五,在你更加努力之后,带着我给你的见解再次尝试写这个问题。

【讨论】:

  • 1.我知道,我试图直接从我的代码中复制它,但格式错误。 2. 我知道它只ping 3 次,我真的ping 1 或2 次没有问题,因为我希望无论如何都能让它连续ping,这样一个假阳性或假阴性就不会是世界末日。 3. 这是真的。我应该这样做,只是没有想到。 4. 谢谢。已修复:) 5. 我们不能相处融洽吗?
  • 我不是故意的 :)
【解决方案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)

【讨论】:

  • 您先生,是一位绅士和一位学者。谢谢。我做了一些修改,但您发布的内容确实很有帮助。我希望我可以为您的修改投票,但是我没有被允许投票的声誉。
  • 别担心,我不完全确定你想要什么,但逻辑应该是相似的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2019-09-11
  • 2016-03-10
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多