吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1338|回复: 17
收起左侧

[Python 原创] 使用Python监控网络连接状态并自动启动和关闭软件

[复制链接]
Skynet520 发表于 2025-7-22 10:57
通过 Python 编写一个网络连接状态监测程序,以 Synology Drive软件为例

通过如下代码实现来演示如何监控网络连接状态并自动启动和关闭相关软件
[Python] 纯文本查看 复制代码
import subprocess
import os
import time


def is_connected():
    # ping一个内网地址
    internal_ip = '10.10.10.11'
    internal_ping = subprocess.call(['ping', '-n', '1', '-w', '500', internal_ip], stdout=subprocess.PIPE)
    if internal_ping == 0:
        # 内网连接正常,检查软件是否已经关闭
        drive_process = "cloud-drive-ui.exe"
        try:
            output = subprocess.check_output(["tasklist", "/FI", f"IMAGENAME eq {drive_process}"])
            if drive_process in str(output):
                # 软件正在运行,需要关闭
                os.system("taskkill /f /im cloud-drive-ui.exe")
            return True
        except subprocess.CalledProcessError:
            # 异常处理
            pass

    # ping一个公共网址
    external_ip = 'www.baidu.com'
    external_ping = subprocess.call(['ping', '-n', '1', '-w', '500', external_ip], stdout=subprocess.PIPE)
    if external_ping == 0:
        # 外网连接正常,检查软件是否已经启动
        drive_process = "cloud-drive-ui.exe"
        try:
            output = subprocess.check_output(["tasklist", "/FI", f"IMAGENAME eq {drive_process}"])
            if drive_process in str(output):
                # 软件已经启动,不需要重复运行
                return True
            else:
                # 软件没有启动,需要运行
                drive_path = r"C:\Program Files (x86)\Synology\SynologyDrive\bin\launcher.exe"
                os.startfile(drive_path)
                return True
        except subprocess.CalledProcessError:
            # 异常处理
            pass

    return False

# 持续运行程序
while True:
    if not is_connected():
        # 如果网络连接中断,关闭 Synology Drive 软件
        pass

    # 等待一段时间后再次检查网络连接状态
    time.sleep(10)
    ```

免费评分

参与人数 3吾爱币 +9 热心值 +2 收起 理由
xlln + 1 + 1 我很赞同!
zx111111 + 1 热心回复!
hrh123 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

麻木不忍 发表于 2025-8-3 23:07
你好,如果我想监测测设备网页能否正常登录打开,如何能修改代码,设备市web管理的,跟路由器、交换机类似
aqbrdfewx 发表于 2025-7-22 11:59
sichenzi 发表于 2025-7-22 12:14
Wangsir89 发表于 2025-7-22 13:12
厉害厉害 学习了
congcongzhidao 发表于 2025-7-22 14:32
持续后台运行占内存吧
onetwo888 发表于 2025-7-22 15:10
学习学习,感谢!!
zxc123655 发表于 2025-7-22 16:02
来观摩观摩,学习一下
guyongjingbin 发表于 2025-7-22 17:28
学习,进步。
wls07121991 发表于 2025-7-22 18:19
感谢  分享  不错
thefresher 发表于 2025-7-22 20:28
观摩学习一下
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-2-20 14:12

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表