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

from smb.SMBConnection import *


class SMBClient:
    """
    SMBClient类,用于连接smb服务器,获取文件
    
	:ip,
	:port(445 or 139),
	:username: 用户名.
	:password: 密码.
    :host: smb服务器名称、电脑名称.
    """
    def __init__(self, ip, port, username, password, host):
        self.ip = ip
        self.port = port
        self.username = username
        self.password = password
        self.host = host
        self.conn = SMBConnection(username, password, 'client_name', host, 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, "", "", "LAPTOP-AEG82LV")
    print(smb_client.list_shares())
    
    # smb_client.get_file("ffcs", "/Project/test.txt", "test.txt")
posted @     阅读(371)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示