Platform-Independent SFTP with Python
Secure file transfer (SFTP) is essential for secure data exchange, but finding Python libraries that support it can be a challenge. When hard-coding user credentials and remote locations is not an option, exploring alternative solutions is crucial.
Paramiko is a popular Python library for SFTP. Its syntax is relatively straightforward, as demonstrated below:
<code class="python">import paramiko host = "THEHOST.com" port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" username = "THEUSERNAME" transport.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print('Upload done.')</code>
This code uploads a file to a remote SFTP server using hard-coded host, port, username, and password. However, it is important to note that hard-coding credentials is not considered best practice and should be avoided whenever possible.
Twisted is another option for SFTP in Python. It is a more complex library but offers a broader range of features. Here is an example of how to use Twisted for SFTP:
<code class="python">from twisted.conch.ssh import userauth, connection, channel, sftp password = "THEPASSWORD" username = "THEUSERNAME" transport = connection.SSHClientFactory().buildProtocol('localhost', None) transport.requestService(userauth.SSHUserAuthClientPassword(username, password)) sftp = channel.SSHChannel(transport) sftp.request_sftp() import sys path = './THETARGETDIRECTORY/' + sys.argv[1] localpath = sys.argv[1] sftp.sendFile(localpath, path) sftp.close() transport.loseConnection() print('Upload done.')</code>
Both Paramiko and Twisted can facilitate platform-independent SFTP connections in Python. Paramiko is simpler to use, while Twisted offers more advanced features. The choice between the two depends on the specific requirements of the project.
The above is the detailed content of Which Python Libraries Provide Platform-Independent SFTP Support?. For more information, please follow other related articles on the PHP Chinese website!