python第五次作业

编写一个脚本`test_ip.py`实现指定参数的远程主机网络探测
-----------------------------------------------------------------
> python test_ip.py 192.168.0.10 192.168.0.100
# 针对192.168.0.10~192.168.0.100范围内所有主机进行网络探测

import sys
import subprocess


def ping_ip(ip):
    try:
        param = '-n' if sys.platform.startswith('win') else '-c'
        command = ['ping', param, '1', ip]
        response = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        if response.returncode == 0:
            return True
        else:
            return False
    except Exception as e:
        print(f"Error pinging {ip}: {e}")
        return False


def main(start_ip, end_ip):
    start_parts = list(map(int, start_ip.split('.')))
    end_parts = list(map(int, end_ip.split('.')))

    for i in range(start_parts[3], end_parts[3] + 1):
        test_ip = f"{start_parts[0]}.{start_parts[1]}.{start_parts[2]}.{i}"
        if ping_ip(test_ip):
            print(f"{test_ip} is up.")
        else:
            print(f"{test_ip} is down.")


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python test_ip.py <start_ip> <end_ip>")
        sys.exit(1)

    start_ip = sys.argv[1]
    end_ip = sys.argv[2]

    main(start_ip, end_ip)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值