python - 仅输出有效
问题描述
我试图让这个 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))
解决方案
恕我直言,您不要分析 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"
推荐阅读
- go - Golang reverse a arbitrary slice
- java - 如何将 Ints 读取为数组并输出 MinMax
- javascript - ReferenceError: FormData is not defined at Object.
- scala - How Flink Kafka Producer set Semantic in Scala
- sql - How best to store an arbitrarily complex data structure in a relational DB?
- php - PHP中的条件间隔周期
- github - GitHub 无法识别 docs 文件夹中的 LICENSE.txt
- go - 匿名类型声明通过 "var" 与 ":=" 的工作方式不同
- javascript - 使用状态钩子时,useState() 如何为功能组件检索正确的状态对象和函数?
- javascript - 当页面加载不起作用时,Javascript/JQuery 会弹出警报