在python中将文件从SMB服务器复制到本地驱动器(Linux / Windows)

时间:2013-12-06 10:51:15

标签: python

我正在使用smb模块使用以下代码段连接到smb服务器

import tempfile
from smb.SMBConnection import SMBConnection
from nmb.NetBIOS import NetBIOS

conn = SMBConnection('salead', 'repo@2k12', '192.168.14.1', 'SERVER', use_ntlm_v2 = True)
assert conn.connect('192.168.1.41', 139)
if conn:
    print "successfull",conn
else:
    print "failed to connect"

我无法弄清楚当我使用linux机器时,我可以做些什么来将文件从smb复制到我的本地驱动器。

如果有人能帮助我,那对我来说将是一个很大的帮助。

提前谢谢

2 个答案:

答案 0 :(得分:3)

根据some documentationSMBConnection.retrieveFile()是您要搜索的功能。

示例:

# UNTESTED
conn = SMBConnection('salead',
                     'repo@2k12',
                     '192.168.14.1',
                     'SERVER',
                     use_ntlm_v2 = True)
assert conn.connect('192.168.1.41', 139)
with open('local_file', 'wb') as fp:
    conn.retrieveFile('share', '/path/to/remote_file', fp)

文档:http://pysmb.readthedocs.io/en/latest/api/smb_SMBConnection.html

示例(日文):http://symfoware.blog68.fc2.com/blog-entry-999.html

答案 1 :(得分:2)

@Rob上面引用的文档应该可以帮助您。这是一个使用抽象类的想法:

> pip install pysmb
import subprocess

from smb import SMBConnection


class SMBClient:
    def __init__(self, ip, username, password, servername, share_name):
        self._ip = ip
        self._username = username
        self._password = password
        self._port = 445
        self._share_name = share_name
        self._servername = servername
        self._server = ''

    def _connect(self):
        """ Connect and authenticate to the SMB share. """
        self._server = SMBConnection(username=self._username,
                                    password=self._password,
                                    my_name=self._get_localhost(),
                                    remote_name=self._servername,
                                    use_ntlm_v2=True)
        self._server.connect(self._ip, port=self._port)

    def _download(self, files: list):
        """ Download files from the remote share. """
        for file in files:
            with open(file, 'wb') as file_obj:
                self._server.retrieveFile(service_name=self._share_name,
                                          path=file,
                                          file_obj=file_obj)

    def _get_localhost(self):
        self._host = subprocess.Popen(['hostname'],stdout=subprocess.PIPE).communicate()[0].strip()

然后,您所需要做的就是:

filename = [the file you want to download]
smb_client = SMBClient(ip='192.168.14.1', username='salead', password='repo@2k12', servername='SERVER', share_name='SHARE_NAME')
smb_client._connect()
response = smb_client._download(filename)

主要文档:https://pysmb.readthedocs.io/en/latest/index.html SMBConnection文档:https://pysmb.readthedocs.io/en/latest/api/smb_SMBConnection.html