首页 > 解决方案 > Python Paramiko 通过 SSH 将多个文件下载到窗口客户端

问题描述

我想将linux服务器下的多个文件下载到我的窗口客户端,我在桌面下有很多文件

test_file1_20200601_0001.csv test_file1_20200601_0002.csv test_file1_20200601_0003.csv test_file1_20200601_0004.csv test_file1_20200601_0004.csv 。. test_file1_20200601_0400.csv

这是我的代码

dt_today  = datetime.strftime(datetime.now() - timedelta(0), '%Y%m%d')
dt_yesday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')

Destination = os.path.join(os.sep,str(Path.home()),'Template and Raw','Raw')
ssh = paramiko.SSHClient()
ssh.connect('192.168.1.1', username="server1", password="server1@123")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sftp = ssh.open_sftp()

for filename in sftp.listdir('/home/server1/Desktop/test/'+ dt_yesday):
    if fnmatch.fnmatch(filename, 'test_file1_'+dt_yesday+'*.csv'):
        sftp.get(filename, Destination)
sftp.close()

我得到了这个错误

PermissionError: [Errno 13] Permission denied: 'C:\Users\YouKnowWho\Template and Raw\Raw'

我可以知道我该如何解决这个问题

标签: python

解决方案


Paramiko 源显示 get 方法打开localpath以进行写入。您将一个文件夹传递给.get.

    def get(self, remotepath, localpath, callback=None):
        """
        Copy a remote file (``remotepath``) from the SFTP server to the local
        host as ``localpath``.  Any exception raised by operations will be
        passed through.  This method is primarily provided as a convenience.

        :param str remotepath: the remote file to copy
        :param str localpath: the destination path on the local host
        :param callable callback:
            optional callback function (form: ``func(int, int)``) that accepts
            the bytes transferred so far and the total bytes to be transferred

        .. versionadded:: 1.4
        .. versionchanged:: 1.7.4
            Added the ``callback`` param
        """
        with open(localpath, "wb") as fl:
            size = self.getfo(remotepath, fl, callback)
        s = os.stat(localpath)
        if s.st_size != size:
            raise IOError(
                "size mismatch in get!  {} != {}".format(s.st_size, size)
            )


推荐阅读