可以运行简单的ping扫描程序,但也会出错

时间:2019-03-06 06:36:03

标签: python python-3.x

我正在尝试使用python 3.x创建一个简单的ping扫描程序,如下所示

import subprocess

subnet = "ping -c 1 10.1.1."

for i in range(250, 251):
    subprocess.call(["ping -c1 10.1.1." + str(i)], shell=True)

它可以给出正确的结果;但是,还会返回一些错误。我可以知道是否与我的代码有关吗?

结果:

PING 10.1.1.250 (10.1.1.250) 56(84) bytes of data.
64 bytes from 10.1.1.250: icmp_seq=1 ttl=128 time=1.72 ms

--- 10.1.1.250 ping statistics ---

1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 1.723/1.723/1.723/0.000 ms
PING 10.1.1.251 (10.1.1.251) 56(84) bytes of data.
64 bytes from 10.1.1.251: icmp_seq=1 ttl=128 time=1.88 ms

--- 10.1.1.251 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 1.884/1.884/1.884/0.000 ms
PING 10.1.1.252 (10.1.1.252) 56(84) bytes of data.
64 bytes from 10.1.1.252: icmp_seq=1 ttl=128 time=1.100 ms

Traceback (most recent call last):
  File "test2.py", line 6, in <module>
    subprocess.call(["ping -c1 10.1.1." + str(i)], shell=True)
  File "/usr/lib/python3.7/subprocess.py", line 325, in call
    return p.wait(timeout=timeout)
  File "/usr/lib/python3.7/subprocess.py", line 990, in wait
    return self._wait(timeout=timeout)
  File "/usr/lib/python3.7/subprocess.py", line 1624, in _wait
    (pid, sts) = self._try_wait(0)
  File "/usr/lib/python3.7/subprocess.py", line 1582, in _try_wait
    (pid, sts) = os.waitpid(self.pid, wait_flags)

谢谢。

1 个答案:

答案 0 :(得分:1)

您应该处理KeyboardInterrupt

import subprocess

netaddress = "10.1.1.{}"
limit = (10,255)
for i in range(*limit):
    try:
        subprocess.call(["ping", "-c1", netaddress.format(i)])
    except KeyboardInterrupt as interrupt:
        print("Skipping....")
        # or `break` if you want to exit