ipscanner python3(模块ipaddress)。结果列表 - 所有主机脱机

时间:2015-06-24 19:40:44

标签: python-3.x

有一个代码可以扫描指定的地址范围:

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...")

结果工作 - 子网中的所有主机都处于脱机状态

我哪里错了?

1 个答案:

答案 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选项。