2

I have written a small program that uses the os module extensively especially os.walk, os.remove etc. For example,

def dump_folder(source, destination):
    """
    """
    # uses os.walk, shutil.move

def encrypt_folder(folder, recipient):
    """
    """
    # uses os.walk, os.remove

Now, I would like to extend this program to support SFTP folders.

Do I need to mount the folders locally to make os.* work? For example, in Windows, I could use win32net and do something like:

try:
    win32wnet.WNetAddConnection2(...drive, remote...)                                
except:
    pass

If I am going to use a tool like paramiko, can I make it work with the same code without worrying about the details which os.walk, os.remove, shutil.move provides? If I can't, then I will have to rewrite the program quite a bit which is not something I want.

PS: The goal of this question is to find out how to use the same code to work with remote folders. Tools like paramiko deals with implementation details (like where is the file etc) so we will have to re-write the program . The idea of mounting remote file locally and ability to use os is really nice and powerful.

Nishant
  • 20,354
  • 18
  • 69
  • 101
  • 4
    Possible duplicate of [SFTP in Python? (platform independent)](https://stackoverflow.com/questions/432385/sftp-in-python-platform-independent) – Peter Wood Jun 11 '18 at 10:22
  • @Peter Wood, I think it is not a complete duplicate as I am not asking about `paramiko` per se. I would like to use the same code for remote access! That is the goal. – Nishant Jun 11 '18 at 10:52

2 Answers2

3

I'm sorry to disappoint you, but the situation is indeed exactly as you describe in your question:

Yes, you do need to mount your remote directory if you want to use os.walk, os.remove, shutil.move, etc.

If you use a specialized SFTP library such as paramiko (or calling ssh/sftp via the subprocess module), you'll have to implement the functionaliy of os.walk on your own.

By the way, if you decide to implement your own os.walk on top of paramiko, you might want to contribute that function back to paramiko, as it may be helpful for other users of that library, too.

vog
  • 23,517
  • 11
  • 59
  • 75
1

As the @vog's answer says already, you cannot use os.* functions for SFTP, unless you mount a remote filesystem to a local one.


The only other way is to use some Python SFTP client library.

There's pysftp library, which is a more Pytonish wrapper around Paramiko library. And pysftp has walktree method:

walktree(remotepath, fcallback, dcallback, ucallback, recurse=True)
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992