You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python脚本检测网络共享响应时间

网络共享响应时间检测优化方案

一、为现有逻辑添加超时处理

Python标准文件I/O操作不支持直接设置超时,我们可以通过线程封装检测逻辑,配合超时等待实现超时控制:

import os
import time
import threading

def execute_share_test():
    file_name = f"\\\\fileserver_name\\share_name$\\TestFile-{time.time()}.txt"
    try:
        with open(file_name, 'a') as f:
            f.write('hello')
        if os.path.isfile(file_name):
            time.sleep(1)
            os.remove(file_name)
        return True
    except Exception as e:
        print(f"操作异常: {e}")
        return False

# 设置超时阈值(单位:秒)
timeout = 5
test_thread = threading.Thread(target=execute_share_test)
test_thread.start()
test_thread.join(timeout)

if test_thread.is_alive():
    print(f"网络共享响应超时(超过{timeout}秒)")
    # 注意:线程无法强制终止,若需避免临时文件残留,可考虑使用守护线程或提前生成唯一文件名
else:
    print("检测完成")

二、更高效的网络共享检测方法

1. 先Ping服务器再检测共享

先通过Ping确认服务器网络可达,再执行共享操作,减少无效的I/O等待:

import subprocess
import os
import time

def ping_server(server_name, timeout=3):
    # 适配Windows和Linux的Ping命令参数
    count_param = '-n' if os.name == 'nt' else '-c'
    timeout_param = '-w' if os.name == 'nt' else '-W'
    try:
        result = subprocess.run(
            ['ping', count_param, '1', timeout_param, str(timeout), server_name],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=timeout + 1
        )
        return result.returncode == 0
    except subprocess.TimeoutExpired:
        return False

def test_share():
    server = "fileserver_name"
    share_path = f"\\\\{server}\\share_name$"
    
    if not ping_server(server):
        print("服务器网络不可达")
        return
    
    file_name = f"{share_path}\\TestFile-{time.time()}.txt"
    try:
        with open(file_name, 'a') as f:
            f.write('hello')
        if os.path.isfile(file_name):
            os.remove(file_name)
        print("共享响应正常")
    except Exception as e:
        print(f"共享访问失败: {e}")

test_share()

2. 轻量检测共享目录可用性

相比创建文件,直接检测共享目录的可访问性更轻量,适合快速检测:

import os
import threading

def check_share_access():
    share_path = "\\\\fileserver_name\\share_name$"
    try:
        # 用listdir代替exists,避免权限问题导致的误判
        os.listdir(share_path)
        return True
    except Exception as e:
        print(f"共享检测异常: {e}")
        return False

timeout = 5
check_thread = threading.Thread(target=check_share_access)
check_thread.start()
check_thread.join(timeout)

if check_thread.is_alive():
    print(f"共享检测超时(超过{timeout}秒)")
else:
    if check_thread._result:
        print("共享可正常访问")

方法对比

  • 创建文件测试:模拟真实读写场景,结果准确但开销较大
  • Ping+目录检测:先排除网络问题,再验证共享,平衡速度与准确性
  • 直接目录检测:最快的检测方式,适合高频巡检场景

内容的提问来源于stack exchange,提问作者Nari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:50:24