有一个代码可以扫描指定的地址范围:
import os, ipaddress
position_start=input('Start hostname: ')
position_end=input('End hostname: ')
hostname_start = ipaddress.IPv4Address(position_start)
hostname_end = ipaddress.IPv4Address(position_end)
while hostname_start <= hostname_end:
hostname_response = os.system("ping -c 1 -w 2" + str(hostname_start)+ "> /dev/null 2>&1")
if hostname_response == 0:
print (hostname_start, ' is up!\n')
else:
print (hostname_start, ' is down!\n')
hostname_start += 1
input("\nPress the enter key to exit...")
结果工作 - 子网中的所有主机都处于脱机状态
我哪里错了?
答案 0 :(得分:0)
您的主要问题是格式化字符串。 "ping -c 1 -w 2"
最后没有空格,应用程序找不到IP地址。这是工作示例
import os
import ipaddress
position_start = input('Start hostname: ')
position_end = input('End hostname: ')
hostname_start = ipaddress.IPv4Address(position_start)
hostname_end = ipaddress.IPv4Address(position_end)
while hostname_start <= hostname_end:
hostname_response = os.system("ping -c 1 -w 2 {0} > /dev/null 2>&1".format(hostname_start))
if hostname_response == 0:
print(hostname_start, ' is up!\n')
else:
print(hostname_start, ' is down!\n')
hostname_start += 1
input("\nPress the enter key to exit...")
请注意,此示例仅适用于Linux,因为* BSD和OS X不支持-w
ping选项。