Pycharm 连接smb服务器
Pycharm实现smb共享服务器的文件连接下载
1.添加pysmb
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