Thursday, September 22, 2016

Simple open_sftp() context manager for sftp read and writing of files

I had to do some reading/writing of files from an SFTP source/destination and ended up putting together a simple context manager for being able to do this so that it follows the same general interface as open() for local files. Usage is as simple as
from open_sftp import open_sftp

path = "sftp://user:p@ssw0rd@test.com/path/to/file.txt"

# Read a file
with open_sftp(path) as f:
    s = f.read() 
print s

# Write to a file
with open_sftp(path, mode='w') as f:
    f.write("Some content.") 
It's as simple as that. The full code can be found as a gist on GitHub. Note: This assumes that the directory already exists, but one could modify this trivially to create the path automatically by adding the details from this StackOverflow thread.