首页 > 解决方案 > 仅输出有效

问题描述

我试图让这个 IP 扫描器只显示它 ping 的活动 IP,任何帮助都很棒。谢谢你。

# Script to ping all IP addresses in a /24 subnet
import os

network = input ("Enter IP Network to scan: ")
print(network)

# Iterate over all usable IPs in this subnet
for host in range (1, 254):
 print("Pinging " + network + "." + str(host))
 os.system("ping -c 2 " + network + "." + str(host))

标签: pythonpython-3.x

解决方案


恕我直言,您不要分析 ping 命令的输出,而是分析其退出代码。根据手册页

 The ping utility exits with one of the following values:
 0       At least one response was heard from the specified host.
 2       The transmission was successful but no responses were received.
 any other value An error occurred. 

所以代码可能是这样的。

import os

network = input ("Enter IP Network to scan: ")
print(network)

for host in range (1, 254):
   print("Pinging " + network + "." + str(host))
   h = network + "." + str(host)
   res = os.system("ping -q -c 2 " + h)
   if res == 1 or res == 2: 
       print("host " + h + "is active"

推荐阅读