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()