Pycharm 连接smb服务器

Pycharm实现smb共享服务器的文件连接下载

1.添加pysmb

添加pysbm

2.使用

Python 2.7

import os

from smb.SMBConnection import SMBConnection


class SMBClient:

    def __init__(self, username, password, ip, port=445, 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] and file.getsize(f) > 1024:
                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 download_file(self, remote_path, local_path):
        """下载文件"""
        if os.path.exists(local_path):#判断文件是否存在
            print(local_path+"本地已存在")
        else:
            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:#如果是目录则跳过
                    continue
                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__':
#比如访问共享:\\ip\remotepath
    client = SMBClient('username', 'password', '192.168.1.3',service_name='remotepath')
    client.connect()
    client.download_directory(
        remote_path='',
        local_path='E:/test/'
    )
    client.close()


引用:
https://blog.csdn.net/qq_45444679/article/details/132046859
https://www.cnblogs.com/monsino/p/14104911.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值