阅读量:3
在Python中,你可以使用subprocess模块来执行ping命令
import subprocess
import time
def ping(host, interval):
while True:
try:
# 在Windows系统中,使用"-n"参数,而在Linux和macOS系统中,使用"-c"参数
command = ["ping", "-c", "1", host] if platform.system().lower() != "windows" else ["ping", "-n", "1", host]
output = subprocess.check_output(command, stderr=subprocess.STDOUT, universal_newlines=True)
print(f"{host} is up: {output.strip()}")
except subprocess.CalledProcessError as e:
print(f"{host} is down: {e.output.strip()}")
time.sleep(interval)
if __name__ == "__main__":
host = input("Enter the host to ping: ")
interval = float(input("Enter the interval in seconds: "))
ping(host, interval)
这个脚本定义了一个名为ping的函数,它接受一个主机名和一个时间间隔(以秒为单位)。函数会无限循环地执行ping命令,并在每次执行后等待指定的时间间隔。如果主机在线,它将输出ping成功的信息;如果主机离线,它将输出ping失败的信息。
请注意,这个脚本需要在具有相应权限的环境中运行,以便能够执行ping命令。在某些操作系统中,你可能需要以管理员身份运行脚本。
以上就是关于“在Python里如何定时执行ping命令”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm