编写一个脚本`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)