Search code examples
pythonlinuxwindowspython-3.xpysftp

transferring files with pysftp.get_r between linux and windows


I want to recursively download files from a Linux server into a Windows desktop. I'm using the following code:

import pysftp
import sys

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

with pysftp.Connection(host="192.168.1.1", username="user", password="secret", cnopts=cnopts) as sftp:
    sftp.get_r ('test_sftp', 'C:\\Users\\user\\Desktop\\my_dir\\', preserve_mtime=False)
    sftp.close()

I have the encoutered the following error (while recursively copying the files):

Traceback (most recent call last):
  File "blah.py", line 12, in <module>
    sftp.get_r ('teste_sftp', 'C:\\Users\\user\\Desktop\\my_dir\\', preserve_mtime=False)
  File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\pysftp\__init__.py", line 311, in get_r
    preserve_mtime=preserve_mtime)
  File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\pysftp\__init__.py", line 249, in get
    self._sftp.get(remotepath, localpath, callback=callback)
  File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\paramiko\sftp_client.py", line 720, in get
    with open(localpath, 'wb') as fl:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\Desktop\\my_dir\\test_sftp/n1/M51'

I understand that pysftp is trying to recreate the folder structure from the source into the destination folder, but it isn't sensible to the fact that it is working on a Windows machine and that the slashes should be backslashes.

How to work around it?


Solution

  • Currently, pysftp doesn't have support for such feature.

    I would recommend Python's default FTP library, which is already in the standard library (batteries included). There you can call retrbinary() giving the desired folder.