python-3.x - 如何使用 PythonPing 处理错误异常?
问题描述
我正在尝试 ping 计算机列表,但在最后一个计算机名称上不断收到套接字错误,该计算机名称不是有效的计算机。我该如何处理这个错误?
from pythonping import ping
import socket
list = ["usadandc1", "usadandc2", "usadandc3", "alsdkfasd"]
for host in list:
result = ping(host, count=1)
if result.success():
print(host ,'online')
else:
print(host, 'Offline')
这是输出:
usadandc1 online
usadandc2 online
usadandc3 online
Traceback (most recent call last):
File "C:\Temp\PythonPing.py", line 7, in <module>
result = ping(host, count=1)
File "C:\Users\usa\AppData\Roaming\Python\Python37\site-packages\pythonping\__init__.py", line 52, in ping
comm = executor.Communicator(target, provider, timeout, socket_options=options, verbose=verbose, output=out)
File "C:\Users\usa\AppData\Roaming\Python\Python37\site-packages\pythonping\executor.py", line 224, in __init__
self.socket = network.Socket(target, 'icmp', source=None, options=socket_options)
File "C:\Users\usa\AppData\Roaming\Python\Python37\site-packages\pythonping\network.py", line 21, in __init__
self.destination = socket.gethostbyname(destination)
socket.gaierror: [Errno 11001] getaddrinfo failed
解决方案
from pythonping import ping
import socket
list = ["google.com", "usadandc2", "usadandc3", "alsdkfasd"]
for host in list:
try:
ip = socket.gethostbyname(host)
result = ping(ip, count=1)
if result.success():
print(host, 'online')
except socket.error:
print(host, 'Offline')
推荐阅读
- sql - Postgres 递归查询和窗口函数从表中生成树
- google-chrome - Google 如何阻止 Chrome 在 Google Ads 等 Google 应用程序中自动填充表单?
- woocommerce - 如果 WoooCommerce 产品在购物车中,则在产品页面上显示带有购物车计数的消息
- python - 将字符串传递给 lambda 函数
- javascript - 如何使用 PHP 中的 AJAX 从 MYSQL 中获取数据
- airflow - 气流警告“将 1 个任务实例设置为 state=None,因为它们关联的 DagRun 未处于 RUNNING 状态”
- reactjs - 将数据从 app.js 传递到 ReactJs 中的组件
- python - Lektor CMS:无法让 lektor-tags 正常工作,在服务器上找不到请求的 URL
- java - 在 Dockerfile 的 ENTRYPOINT 上执行 java 命令无法识别给定的 ARG 值
- spring - 未定义命名查询有问题。我得到 java.lang.IllegalArgumentException: No query defined for that name