Python脚本在Windows运行正常,Linux下获取Windows服务器文件修改时间报错
问题根因
你遇到的报错本质有两点:
- Linux系统原生不识别Windows的UNC路径格式(即你代码中使用的
\\Server1\tools\...格式) os.path系列API只能访问Linux本地已挂载的文件路径,你未将Windows的SMB共享目录挂载到Linux本地,系统自然找不到对应文件
解决步骤
第一步:安装SMB挂载工具
CentOS/RHEL系列执行命令:yum install cifs-utils -y
Debian/Ubuntu系列执行命令:apt install cifs-utils -y第二步:创建本地挂载目录
mkdir -p /mnt/win_tools_share第三步:挂载Windows共享目录
执行挂载命令,注意将Windows UNC路径的反斜杠全部替换为正斜杠:mount -t cifs //Server1/tools /mnt/win_tools_share -o username=Windows共享账号,password=Windows共享密码,vers=2.0
参数说明:vers为SMB协议版本,Windows Server 2016/Win10及以上系统可填3.0,更低版本填2.0即可第四步:修改Python脚本路径
修改后的完整代码如下:
import os import datetime as dt # 路径替换为挂载后的本地路径 server = '/mnt/win_tools_share/folder/capture.JPG' modify = dt.datetime.fromtimestamp(os.path.getmtime(server)) if dt.datetime.now() - modify > dt.timedelta(minutes=5): print("old") else: print("new")
补充说明
如果需要开机自动挂载共享目录,可在/etc/fstab文件末尾添加如下内容://Server1/tools /mnt/win_tools_share cifs username=Windows共享账号,password=Windows共享密码,vers=2.0 0 0
需保证Linux与Windows服务器的139、445端口互通,且共享账号拥有对应文件的读取权限,避免挂载后依然无法访问。
内容的提问来源于stack exchange,提问作者Hayrullah
相关产品推荐
相关产品推荐

