使用smb协议python3访问服务器上的远程文件

Ale*_*lex 10 python smb python-3.x

我有一些文件的远程服务器。

smb://ftpsrv/public/
Run Code Online (Sandbox Code Playgroud)

我可以作为匿名用户在那里获得授权。在 java 中,我可以简单地编写以下代码:

SmbFile root = new SmbFile(SMB_ROOT);

并获得处理内部文件的能力(这是我所需要的,一行!),但我找不到如何在 Python 3 中管理此任务,有很多资源,但我认为它们不是与我相关,因为它们经常针对 Python 2 和旧的其他方法量身定制。有没有一些简单的方法,类似于上面的Java代码?或者,例如,如果我想访问文件夹中的文件fgg.txt, 有人可以提供真正可行的解决方案smb://ftpsrv/public/。真的有一个方便的库来解决这个问题吗?

以现场为例:

import tempfile
from smb.SMBConnection import SMBConnection

# There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip
# client_machine_name can be an arbitary ASCII string
# server_name should match the remote machine name, or else the connection will be rejected
conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
assert conn.connect(server_ip, 139)

file_obj = tempfile.NamedTemporaryFile()
file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', file_obj)

# Retrieved file contents are inside file_obj
# Do what you need with the file_obj and then close it
# Note that the file obj is positioned at the end-of-file,
# so you might need to perform a file_obj.seek() if you need
# to read from the beginning
file_obj.close()
Run Code Online (Sandbox Code Playgroud)

我是否真的需要提供所有这些细节:conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)

小智 13

在 Python 3 中使用 urllib 和 pysmb 打开文件的简单示例

import urllib
from smb.SMBHandler import SMBHandler
opener = urllib.request.build_opener(SMBHandler)
fh = opener.open('smb://host/share/file.txt')
data = fh.read()
fh.close()
Run Code Online (Sandbox Code Playgroud)

我还没有准备好用于测试的匿名 SMB 共享,但是此代码应该可以工作。
urllib2 是 python 2 包,在 python 3 中它被重命名为 urllib 并且一些东西被移动了。

  • 我收到此错误,无论是 IP 还是主机名。`urllib.error.URLError: <urlopen 错误 SMB 错误: 主机名未回复其计算机名称>` (2认同)
  • @TanghongWan 你解决了吗? (2认同)