阅读量:4
在Python中,你可以使用subprocess模块来执行ping命令
import subprocess
def ping(host, timeout=2):
try:
# 在Windows系统中,使用'-n'参数,而在Linux和macOS系统中,使用'-c'参数
command = ['ping', '-c', '1', host] if platform.system().lower() != 'windows' else ['ping', '-n', '1', host]
# 使用subprocess.run()执行ping命令,并捕获输出结果
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=timeout)
# 检查返回码是否为0(表示成功)
if result.returncode == 0:
print(f"{host} is reachable.")
else:
print(f"{host} is not reachable.")
except subprocess.TimeoutExpired:
print(f"{host} did not respond within the timeout period.")
except Exception as e:
print(f"An error occurred: {e}")
# 用法示例:
ping("example.com")
请注意,这个示例仅适用于Unix-like系统(Linux、macOS)。如果你正在使用Windows系统,你需要将command数组中的['ping', '-c', '1', host]更改为['ping', '-n', '1', host]。
以上就是关于“python怎么执行ping命令”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm