【pysmb】smb远程共享下载文件的工具类

发布时间 2023-12-07 15:47:10作者: 詩
from smb.SMBConnection import *


class SMBClient:
    """
    SMBClient类,用于连接smb服务器,获取文件
    
	:ip,
	:port(445 or 139),
	:username: 用户名.
	:password: 
    """
    def __init__(self, ip, port, username, password):
        self.ip = ip
        self.port = port
        self.username = username
        self.password = password
        self.conn = SMBConnection(username, password, 'client_name', 'server_name', use_ntlm_v2=True,is_direct_tcp=True)
        self.conn.connect(ip, port)

    def list_shares(self):
        """列出smb共享文件夹名称
        """
        shares = self.conn.listShares()
        return [share.name for share in shares]

    def get_file(self, share_name, remote_file_path, local_file_path):
        """从smb服务器获取文件并下载到本地
        
        :share_name: 远程文件所在共享文件夹名称,即list_shares()返回的列表中的元素。

        :remote_file_path: 远程文件路径,例如:/Project/test.txt。

        :local_file_path: 本地保存的文件名称路径,例如:test.txt。

        :return null
        """
        with open(local_file_path, 'wb') as fp:
            self.conn.retrieveFile(share_name, remote_file_path, fp)

    def close(self):
        self.conn.close()
    
    def __del__(self):
        self.close()

if __name__ == '__main__':
    smb_client = SMBClient("127.0.0.1", 445, "", "")
    print(smb_client.list_shares())
    
    # smb_client.get_file("ffcs", "/Project/test.txt", "test.txt")