Python 3:通过 UNC 路径访问 Linux 下的 Windows 共享



首先,让我们确保Windows共享是可访问的:

$ sudo mkdir /mnt/test

让我们尝试挂载,但它失败了:

$ sudo mount -t cifs //192.168.0.10/work /mnt/test
mount: wrong fs type, bad option, bad superblock on //192.168.0.10/work,
missing codepage or helper program, or other error
(for several filesystems (e.g. nfs, cifs) you might
need a /sbin/mount.<type> helper program)
In some cases useful info is found in syslog - try
dmesg | tail or so.

但是,如果提供虚拟用户/通行证(即准确指向"用户名"和"PASSWD"(,则挂载成功:

$ sudo mount -t cifs -o username=USERNAME,password=PASSWD //192.168.0.10/work /mnt/test
$ ls /mnt/test/*.txt
/mnt/test/1.txt
$ umount test

现在让我们试试python:

$ python -V
Python 3.5.2+
$ python
>>> import os
>>> os.listdir(r'//192.168.0.10/work')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '//192.168.0.10/work'

我正在尝试四个斜杠,反斜杠,组合它,有或没有r,unicode转义(bytes(path, "utf-8").decode("unicode_escape")(,所有这些都失败了No such file or directory.这种失败的可能是用户/通行证,但我无法想象如何将其添加到 UNC。

附言。我也尝试pysmb库,没有用户/通行证就可以正常工作。但是如果可能的话,我不想使用额外的库。

您必须在 Linux 上挂载 UNC 路径。 操作系统无法理解两个反斜杠,除非在挂载路径时。 因此,要使它自动完成,只需编写一些 Python 代码来调用必要的 Linux 命令来完成挂载任务,然后像往常一样引用文件路径。

从 Python 运行 Linux "ls" 命令的示例。

import os
os.system('ls')

现在遵循这两种方法之一。

https://unix.stackexchange.com/questions/18925/how-to-mount-a-device-in-linux

https://www.putorius.net/mount-windows-share-linux.html

最新更新