使用Python编写Ping监测程序

Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;

如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;

本文将介绍如何使用Python编写Ping监测程序

首先,需要导入os、sys、time和subprocess模块。其中os和sys模块用于处理文件路径,time模块用于获取当前时间,subprocess模块用于运行Ping命令

c 复制代码
import os
import sys
import time
import subprocess

接着,需要设置监测的IP地址和Log文件存储路径

c 复制代码
cur_path = os.path.join(os.path.expanduser('~'), 'Desktop')
hostname = '192.168.10.1'  # IP address

log_path = cur_path + "\\%s_ping_log.txt" % hostname

接着定义一个名为pyping的函数,用于运行Ping命令并返回Ping结果。该函数使用subprocess模块运行ping命令并捕获命令输出。然后,提取Ping结果中的有用信息,并将当前时间添加到结果中。最后,该函数返回一个Ping结果字符串

c 复制代码
def pyping(ipaddress):
    cur_time = time.strftime('%Y_%m_%d-%H:%M:%S', time.localtime(time.time()))
    proc = subprocess.Popen(
        ['ping', '-n', '1', ipaddress],
        stdout=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    ping_ret = '%s, PC:%s' % (cur_time, stdout.decode("gbk").split("\n")[2])
    print(ping_ret)
    return ping_ret

接着使用一个无限循环来执行Ping监测,在每次循环中,调用pyping函数来运行Ping命令并获取结果,将结果写入Log文件,并使用time模块延迟一秒钟;

c 复制代码
with open(log_path, "a") as logfile:
    try:
        while True:
            ret_ping = pyping(hostname)
            logfile.write(ret_ping + '\r\n')
            logfile.flush()
            time.sleep(1)
    except KeyboardInterrupt:
        print("程序已停止")

最后,将以上三部分代码段组合在一起即可编写一个Ping监测程序;

c 复制代码
# 导入必要的模块
```c
import os  # 操作系统模块
import sys  # 系统模块
import time  # 时间模块
import subprocess  # 子进程模块

# 获取当前用户桌面路径
cur_path = os.path.join(os.path.expanduser('~'), 'Desktop')
# IP地址
hostname = '192.168.10.1'
# 日志文件路径
log_path = cur_path + "\\%s_ping_log.txt" % hostname

# 定义函数,输入IP地址,返回ping测试结果
def pyping(ipaddress):
    # 获取当前时间
    cur_time = time.strftime('%Y_%m_%d-%H:%M:%S', time.localtime(time.time()))
    # 执行ping指令并获取结果
    proc = subprocess.Popen(
        ['ping', '-n', '1', ipaddress],
        stdout=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    # 解析结果并返回字符串
    ping_ret = '%s, PC:%s' % (cur_time, stdout.decode("gbk").split("\n")[2])
    print(ping_ret)
    return ping_ret

# 打开日志文件并开始循环ping测试
with open(log_path, "a") as logfile:
    try:
        while True:
            # 进行ping测试
            ret_ping = pyping(hostname)
            # 将结果写入日志文件
            logfile.write(ret_ping + '\r\n')
            logfile.flush()
            # 等待1秒
            time.sleep(1)
    except KeyboardInterrupt:
        print("程序已停止")
相关推荐
damoluomu4 天前
挑 PHP CMS 之前,先学会看它的协议
php
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时4 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊4 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1234 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero074 天前
Jev 与 Laya
python·语言模型