python 实现smb共享服务器的文件(夹)上传下载

python 实现smb共享服务器的文件上传下载

1.安装
pip install pysmb
2.使用
import os

from smb.SMBConnection import SMBConnection


class SMBClient:

    def __init__(self, username, password, ip, port=139, service_name=''):
        self.username = username
        self.password = password
        self.ip = ip
        self.port = port
        self.service_name = service_name
        self.conn = None

    def connect(self):
        """连接smb"""
        self.conn = SMBConnection(self.username, self.password, '', '', use_ntlm_v2=True)
        self.conn.connect(self.ip, self.port)

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

    def is_directory_exists(self, remote_directory):
        filelist = self.conn.listPath(self.service_name, os.path.dirname(remote_directory))
        for file in filelist:
            if file.isDirectory and file.filename == os.path.split(remote_directory)[-1]:
                return True
        return False

    def create_directory_recursive(self, remote_directory):
        """递归创建文件夹"""
        dirs = remote_directory.strip("/").split("/")
        current_dir = ""
        for directory in dirs:
            current_dir += "/" + directory
            if not self.is_directory_exists(current_dir):
                self.conn.createDirectory(self.service_name, current_dir)

    def upload_file(self, local_path, remote_path):
        """上传文件并创建文件夹"""
        self.create_directory_recursive(os.path.dirname(remote_path))
        with open(local_path, 'rb') as local_file:
            self.conn.storeFile(self.service_name, remote_path, local_file)

    def upload_directory(self, local_path, remote_path):
        """上传文件夹"""
        for root, dirs, files in os.walk(local_path):
            for file in files:
                local_path = os.path.join(root, file)
                temp = local_path.replace(local_path, '')
                remote_path = remote_path + temp.replace('\\', '/')
                self.upload_file(local_path, remote_path)

    def download_file(self, remote_path, local_path):
        """下载文件"""
        os.makedirs(os.path.dirname(local_path), exist_ok=True)
        with open(local_path, 'wb') as f:
            self.conn.retrieveFile(self.service_name, remote_path, f)

    def download_directory(self, remote_path, local_path):
        """递归下载文件夹"""
        for file in self.conn.listPath(self.service_name, remote_path):
            if file.filename.startswith('.'):
                continue
            else:
                if file.isDirectory:
                    local_dir = os.sep.join([local_path, file.filename])
                    os.makedirs(local_dir, exist_ok=True)
                    self.download_directory(os.path.join(remote_path, file.filename), local_dir)
                else:
                    local_file = os.sep.join([local_path, file.filename])
                    self.download_file(os.path.join(remote_path, file.filename), local_file)


if __name__ == '__main__':
    client = SMBClient('username', 'password', '192.168.1.3',service_name='xx部')
    client.connect()
    client.upload_file(
         remote_path='/xxx/logs/2023-07-28.zip',
         local_path='./xxx/logs/2023-07-28.zip'
     )
    client.download_directory(
        remote_path='/xxx/logs',
        local_path='./xxx/logs'
    )
    client.close()

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值