How to Connect to SFTP/SSH Using Python?

Estimated read time 2 min read

To connect to an SFTP/SSH server using Python, you can utilize the paramiko library, which provides an implementation of the SSHv2 protocol and allows you to establish secure connections. Here’s an example of how you can connect to an SFTP server using Python:

import paramiko

def connect_to_sftp(hostname, port, username, password):
    # Create an SSH client
    client = paramiko.SSHClient()

        # Connect to the SSH server
        client.connect(hostname, port, username, password)

        # Open an SFTP session
        sftp = client.open_sftp()

        # Perform SFTP operations
        # Example: list files in the current directory
        files = sftp.listdir()

        for file in files:

        # Close the SFTP session

        # Close the SSH client

# Usage: replace the following variables with your actual SFTP server credentials
hostname = 'your_sftp_hostname'
port = 22  # default SSH port is 22
username = 'your_username'
password = 'your_password'

connect_to_sftp(hostname, port, username, password)

In this example, we create a function called connect_to_sftp that takes the hostname, port, username, and password as arguments. Inside the function, we create an SSH client using paramiko.SSHClient() and set the AutoAddPolicy() to automatically add the server’s host key to the local known_hosts file.

We establish a connection to the SSH server using the connect() method, passing the hostname, port, username, and password. Then, we open an SFTP session using client.open_sftp(), and you can perform various SFTP operations using the sftp object. In this example, we list the files in the current directory using sftp.listdir().

Finally, we close the SFTP session with sftp.close() and the SSH client with client.close().

Please make sure to install the paramiko library before running this code. You can install it using pip:

pip install paramiko

Note: It is highly recommended to use SSH key-based authentication instead of passwords for improved security.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply