Is pysftp really context-aware?

474 views Asked by At

I'm using the pysftp module to implement a function to put some files onto an FTP site. Following the suggestion in the cookbook for version 0.29, I opened the connection in a with statement:

with psyftp.Connection(host=SERVER, port=PORT, username=USER, password=PASS) as ftp:

(I know using all caps for parameter names is not ideal python style. Please don't judge.) Running this results in:

AttributeError: __exit__

Research on StackOverflow says this happens because the with statement requires an object that has __enter__ and __exit__ methods. You get this error when you use with on an object that doesn't include them, i.e., not a context manager.

Is pysftp not really a context manager, despite its claim, or is there something more subtle going on? I can program my routine without relying on the "with" statement, I'm just wondering what the deal is here.

1

There are 1 answers

0
Fabian On

Contextmanager is working on the current version:

import pysftp
with pysftp.Connection(self.server_ip, username=self.username, password=self.password) as sftp:
    for attr in sftp.listdir_attr(remotepath=remote_path):
        print(attr.filename, attr.st_size, sftp.isdir(remote_path + "/" + attr.filename))

Note: PYSFPT != FTP, if you like to connect to a FTP server please use ftplib

from ftplib import FTP
with FTP("ftp1.at.proftpd.org") as ftp:
    #do your stuff here

SFTP = SSH File Transfer Protocol, FTP = File Transfer Protocol

FTPS (also known as FTPES, FTP-SSL, and FTP Secure) is an extension to the commonly used File Transfer Protocol (FTP) that adds support for the Transport Layer Security (TLS) and, formerly, the Secure Sockets Layer (SSL, which is now prohibited by RFC7568) cryptographic protocols.

FTPS should not be confused with the SSH File Transfer Protocol (SFTP), a secure file transfer subsystem for the Secure Shell (SSH) protocol with which it is not compatible. It is also different from FTP over SSH, which is the practice of tunneling FTP through an SSH connection. - FTPS Wikipedia