![](/img/trans.png)
[英]Python compare two lists of IPs and return the lowest to 0 IP entry in list?
[英]Writing a Python script to ping a list of IP addresses and return whether the host is UP or DOWN and it's just printing my IPs
我編寫了腳本來 ping 列表中的 IP 地址列表。 但是,當我運行腳本時,它只會打印我所有的 IP 地址,但實際上並沒有根據我的判斷來 ping 它們。
誰能告訴我我錯過了什么,我將不勝感激。
#!/usr/bin/env python3
import os
ip_list = ['8.8.8.8'
'8.8.4.4'
'1.1.1.1'
'4.4.4.4']
for ip in ip_list:
response = os.popen(f"ping {ip}").read()
if "Received = 4" in response:
print(f"UP {ip} Ping Successful, Host is UP!")
else:
print(f"DOWN {ip} Ping Unsuccessful, Host is DOWN.")
我按如下方式重新編寫了代碼,但它仍然不喜歡我正在做的事情。 我在 macOS 上的 bash shell 中運行。
#!/usr/bin/env python3
import subprocess
ip_list = ['8.8.8.8', '8.8.4.4', '1.1.1.1']
for ip in ip_list:
p = subprocess.run(['ping '+ip])
p.wait()
if p.poll():
print (ip+" is down")
else:
print (ip+" is up")
我從該代碼中得到的輸出在這里:
matt$ python3 Python_Ping_Public3.py
Traceback (most recent call last):
File "/Users/matt/Desktop/Python_Ping_Public3.py", line 7, in <module>
p = subprocess.run(['ping '+ip])
File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 505, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/local/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1821, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ping 8.8.8.8'
考慮一下:
letters = ['A'
'B'
'C']
print(letters)
這會打印ABC
,因為這三個文字之間沒有逗號。
這更有意義:
letters = ['A',
'B',
'C']
print(letters)
空格在 Python 中是有意義的,但行尾不能代替列表分隔符,它仍然是,
。
這更清楚:
#!/usr/bin/env python3
import os
ip_list = ['8.8.8.8', '8.8.4.4', '1.1.1.1', '4.4.4.4']
for ip in ip_list:
response = os.popen(f"ping {ip}").read()
if "Received = 4" in response:
print(f"UP {ip} Ping Successful, Host is UP!")
else:
print(f"DOWN {ip} Ping Unsuccessful, Host is DOWN.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.