使用python代码将windows服务器传输数据到Linux服务器出现的问题

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

如果有这一行,将不会报错,说明引起这个问题的原因之一是文件夹权限。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值