import paramiko
import os
class Linux():
def __init__(self, ip, username, password, timeout=30):
self.ip = ip
self.username = username
self.password = password
self.timeout = timeout
self.try_times = 3
self.filename = []
def get_all_files_in_local_dir(self, local_dir):
for home, dirs, files in os.walk(local_dir):
for file in files:
filepath = os.path.join(home, file)
self.filename.append(filepath)
def sftp_put_dir(self, local_dir, remote_dir):
t = self.sftp_connect()
sftp = paramiko.SFTPClient.from_transport(t)
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip, port=22, username=self.username, password=self.password)
try:
if remote_dir[-1] == '/':
remote_dir = remote_dir[0:-1]
for x in self.filename:
filename = os.path.split(x)[-1]
remote_file_dir = os.path.split(x)[0].replace(local_dir, remote_dir)
remote_path = remote_file_dir.replace("\\", "/")
stdin, stdout, stderr = ssh.exec_command('find ' + remote_path)
result = stdout.read().decode('utf-8')
if len(result) == 0 :
print('目录 %s 不存在,创建目录' % remote_path)
ssh.exec_command('mkdir -p ' + remote_path)
# ssh.exec_command('chmod 777 -R ' + remote_path)
print('%s 创建成功' % remote_path)
else:
print('目录 %s 已存在' % remote_path)
remote_filename = remote_path + '/' + filename
print(remote_filename)
print ("Put文件%s传输中..." % (filename))
sftp.put(x, remote_filename)
#ssh.close()
except Exception as e:
print(e)
def sftp_connect(self):
t = paramiko.Transport(sock=(self.ip, 22))
t.connect(username=self.username, password=self.password)
return t
if __name__ == "__main__":
local_dir = r'E:\数据共享'
remote_dir = r'/mnt/xvdb/数据共享'
host = Linux('172.16.91.5', 'root', 'abcd@1234')
host.get_all_files_in_local_dir(local_dir)
host.sftp_put_dir(local_dir, remote_dir)
上面这一段代码是将windows服务器上的文件备份到Linux服务器上,注意注释标红的那一行:
如果没有这一行,将会报错:[Errno 2] No such file
如果有这一行,将不会报错,说明引起这个问题的原因之一是文件夹权限。