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

Python中使用不同凭据获取远程文件修改时间并实现5分钟超时告警

实现方案

以下两种方案均适配Windows环境的SMB共享路径(即你代码中\\Server1\格式的路径),同时补充了5分钟超时判断的逻辑:

方案1:调用系统net use命令(无第三方依赖)

通过调用Windows内置的net use命令完成身份认证,不需要额外安装依赖,适合快速实现场景:

import os
import time
import subprocess

# 配置参数
remote_path = r'\\Server1\Users.txt'
share_root = r'\\Server1'
username = r'你的域名\用户名' # 无域环境直接写用户名即可
password = '你的密码'
alert_threshold = 5 * 60 # 超时阈值,单位为秒

try:
    # 先删除已存在的同地址共享连接,避免冲突
    subprocess.run(
        ['net', 'use', share_root, '/delete', '/y'],
        capture_output=True,
        check=False
    )
    # 使用指定凭据建立共享连接
    auth_result = subprocess.run(
        ['net', 'use', share_root, '/user:' + username, password],
        capture_output=True,
        check=True,
        text=True
    )
    if auth_result.returncode != 0:
        print(f"认证失败:{auth_result.stderr}")
        exit()
    
    # 计算时间差判断是否需要告警
    mtime = os.path.getmtime(remote_path)
    current_time = time.time()
    diff = current_time - mtime
    if diff > alert_threshold:
        print("alert")
    else:
        print(f"文件正常,最后修改时间:{time.ctime(mtime)},距当前{round(diff)}秒")

except FileNotFoundError:
    print("no file")
except subprocess.CalledProcessError as e:
    print(f"认证失败,错误信息:{e.stderr}")
finally:
    # 用完断开连接,避免本地残留凭据
    subprocess.run(
        ['net', 'use', share_root, '/delete', '/y'],
        capture_output=True,
        check=False
    )

方案2:使用pywin32调用Windows API(更稳定,适合生产环境)

直接调用Windows系统API完成共享连接,比调用cmd命令可控性更高,出错排查更方便:

  1. 先安装依赖:pip install pywin32
  2. 实现代码:
import os
import time
import win32wnet
import win32netcon

# 配置参数
remote_path = r'\\Server1\Users.txt'
share_root = r'\\Server1'
username = r'你的域名\用户名'
password = '你的密码'
alert_threshold = 5 * 60

try:
    # 配置网络资源参数
    net_resource = {
        'lpRemoteName': share_root,
        'dwType': win32netcon.RESOURCETYPE_DISK,
    }
    # 用指定凭据建立连接
    win32wnet.WNetAddConnection2(net_resource, password, username, 0)
    
    # 时间差判断逻辑
    mtime = os.path.getmtime(remote_path)
    diff = time.time() - mtime
    if diff > alert_threshold:
        print("alert")
    else:
        print(f"文件正常,最后修改时间:{time.ctime(mtime)},距当前{round(diff)}秒")

except FileNotFoundError:
    print("no file")
except win32wnet.error as e:
    print(f"认证或连接失败,错误代码:{e.winerror}, 信息:{e.strerror}")
finally:
    # 清理连接
    try:
        win32wnet.WNetCancelConnection2(share_root, 0, 1)
    except:
        pass

注意事项

  • 不要在代码中硬编码用户名密码,生产环境建议通过环境变量、加密配置文件等方式读取敏感信息
  • 如果是Linux环境访问SMB共享,可替换为smbclient命令或者pysmb库实现带凭据的访问,逻辑和上述方案一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:06:03