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

问题描述 投票:0回答:1

我试图用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)

谢谢。

python python-3.x
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.