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

时间:2018-03-26 14:20:42

标签: python python-3.x smb

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

smb://ftpsrv/public/

我可以在那里被授权为匿名用户。在java中我可以简单地编写这样的代码

SmbFile root = new SmbFile(SMB_ROOT);

并且能够处理内部文件(这就是我需要的,一行!),但是我无法在python3中找到如何管理这个任务,有很多资源,但是我认为它们与我无关,因为它们经常适合python2和旧方法。有一些简单的方法,类似于上面的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()

我非常需要提供所有这些详细信息conn = SMBConnection(userID,password,client_machine_name,server_name,use_ntlm_v2 = True)

2 个答案:

答案 0 :(得分:2)

使用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()

我还没有准备好匿名的SMB共享,​​但是这段代码应该有效 urllib2是python 2包,在python 3中它被重命名为urllib并且有些东西被移动了。

答案 1 :(得分:1)

我想您是在要求Linux,但是为了完整起见,我将分享它在Windows上的工作原理。

在Windows上,Python的标准库函数似乎开箱即用地支持Samba访问:

import glob, os

with open(r'\\USER1-PC\Users\Public\test.txt', 'w') as f:
    f.write('hello')    # write a file on a distant Samba share

for f in glob.glob(r'\\USER1-PC\Users\**\*', recursive=True):
    print(f)   # glob works too
    if os.path.isfile(f):
        print(os.path.getmtime(f))  # we can get filesystem information