Connecting with SSH servers with paramiko and pysftp

Connecting with SSH servers with paramiko and pysftp

An SSH server, also known as an Secure Shell server, is a program that allows users to log into a computer remotely and execute commands as if they were sitting at the computer’s console. SSH is a secure protocol that encrypts all traffic between the client and the server, making it difficult for attackers to intercept and eavesdrop on communications.

Benefits of Using an SSH Server:

Key Components of an SSH Server:

Establishing an SSH Connection:

  1. Client Initiation: The SSH client initiates the connection by sending a request to the SSH server on port 22.
  2. Server Authentication: The SSH server presents its public key to the client, allowing the client to verify the server’s identity.
  3. Client Authentication: The client authenticates itself to the server using its private key and optionally a username and password.
  4. Secure Channel Establishment: Upon successful authentication, a secure channel is established, encrypting all data exchanged between the client and server.

Common SSH Commands:

SSH is a powerful and versatile tool for secure remote access and system administration. Its ability to encrypt all traffic and provide strong authentication mechanisms makes it an essential tool for anyone who needs to manage or access computers remotely.

Installing an SSH server on Linux

is a straightforward process that involves installing the necessary packages and configuring the SSH daemon. Here’s a step-by-step guide on how to install an SSH server on various Linux distributions:

On Ubuntu and Debian:

  1. Update the package manager:
Bash
sudo apt-get update
  1. Install the OpenSSH server package:
Bash
sudo apt-get install openssh-server
  1. Enable and start the SSH service:
Bash
sudo systemctl enable ssh
sudo systemctl start ssh

On CentOS and Red Hat Enterprise Linux (RHEL):

  1. Update the package manager:
Bash
sudo yum update
  1. Install the OpenSSH server package:
Bash
sudo yum install openssh-server
  1. Enable and start the SSH service:
Bash
sudo systemctl enable sshd
sudo systemctl start sshd

On Fedora:

  1. Update the package manager:
Bash
sudo dnf update
  1. Install the OpenSSH server package:
Bash
sudo dnf install openssh-server
  1. Enable and start the SSH service:
Bash
sudo systemctl enable sshd
sudo systemctl start sshd

After completing these steps, the SSH server should be up and running on your Linux system. You can verify this by connecting to the server using an SSH client.

Additional Configuration:

Once the SSH server is installed, you may want to configure it further to enhance security and customize its behavior. Some common configuration options include:

Bash
sudo nano /etc/ssh/sshd_config
Bash
sudo nano /etc/ssh/sshd_config
Bash
ssh-keygen
Bash
sudo nano /etc/ssh/sshd_config

Remember to restart the SSH service after making any configuration changes for them to take effect.

Paramiko and pysftp are two Python modules that provide tools for interacting with SSH and SFTP servers, respectively.

Paramiko

Paramiko is a low-level SSH library that allows you to establish connections to SSH servers, execute commands, transfer files, and manage SFTP sessions. It provides a comprehensive set of functions and classes for handling various aspects of SSH communication, including:

pysftp

pysftp is a higher-level wrapper around Paramiko that provides a more user-friendly interface for working with SFTP servers. It simplifies file transfer operations, directory manipulation, and remote filesystem management, making it easier to perform common SFTP tasks.

Key Features of pysftp:

Comparing Paramiko and pysftp:

FeatureParamikopysftp
Level of abstractionLow-levelHigh-level
SSH capabilitiesComprehensive SSH functionality, including command execution and tunnelingSFTP-focused, with simplified file transfer operations
Ease of useMore complex and requires deeper understanding of SSH protocolsSimpler and more user-friendly for SFTP-related tasks
Control over SSH detailsProvides granular control over SSH connection parameters and interactionsOffers a more abstract interface for SFTP operations

Choosing the Right Module:

The choice between Paramiko and pysftp depends on your specific requirements:

If you need both SSH and SFTP functionality, consider using Paramiko for SSH-related tasks and pysftp for SFTP operations.

SSH Connection Script with Paramiko

This Python script establishes an SSH connection using the paramiko library. The script connects to an SSH server with the specified hostname, username, and password.

1. Importing the Required Modules:

Python
import paramiko
import socket

The script imports the paramiko module for SSH operations and the socket module for handling socket-related exceptions.

2. SSH Connection Function:

Python
def establish_ssh_connection(host, username, password):
    try:
        # Create an SSH client instance
        ssh_client = paramiko.SSHClient()

        # Set up logging for debugging (optional)
        paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)

        # Load system host keys
        ssh_client.load_system_host_keys()

        # Automatically add server key to known_hosts file
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the SSH server
        response = ssh_client.connect(host, port=22, username=username, password=password)
        print('Connected to host on port 22:', response)

        # Get transport and security options
        transport = ssh_client.get_transport()
        security_options = transport.get_security_options()
        print('Key exchange algorithms:', security_options.kex)
        print('Ciphers:', security_options.ciphers)

    except paramiko.BadAuthenticationType as exception:
        print("BadAuthenticationException:", exception)
    except paramiko.SSHException as sshException:
        print("SSHException:", sshException)
    except socket.error as socketError:
        print("SocketError:", socketError)
    finally:
        print("Closing connection")
        # Close the SSH connection
        ssh_client.close()
        print("Connection closed")

The establish_ssh_connection function attempts to establish an SSH connection to the specified host using the provided username and password. It prints information about the connection and security options.

3. Main Function:

Python
if __name__ == '__main__':
    # Set parameters for SSH connection
    host = 'localhost'
    username = 'username'
    password = 'password'

    # Call the SSH connection function
    establish_ssh_connection(host, username, password)

The script calls the establish_ssh_connection function with the specified parameters for the SSH connection.

Python
import paramiko
import socket

#put data about your ssh server
host = 'localhost'
username = 'username'
password = 'password'

try:
    ssh_client = paramiko.SSHClient()
    #shows debug info
    paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
    #The following lines add the server key automatically to the know_hosts file
    ssh_client.load_system_host_keys()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    response = ssh_client.connect(host, port = 22, username = username, password = password)
    print('connected with host on port 22',response)
    transport = ssh_client.get_transport()
    security_options = transport.get_security_options()
    print(security_options.kex)
    print(security_options.ciphers)
except paramiko.BadAuthenticationType as exception:
    print("BadAuthenticationException:",exception)
except paramiko.SSHException as sshException:
    print("SSHException:",sshException)
except socket.error as  socketError:
    print("socketError:",socketError)
finally:
    print("closing connection")
    ssh_client.close()
    print("closed")

Note:

SSH Command Execution Script with Paramiko

This Python script uses the paramiko library to execute a command on a remote SSH server. The script prompts the user for the target hostname, port, username, password, and command to be executed on the remote server.

1. Importing the Required Modules:

Python
#!/usr/bin/env python3

import getpass
import paramiko

2. SSH Command Execution Function:

Python
HOSTNAME = 'localhost'
PORT = 22

def run_ssh_cmd(username, password, command, hostname=HOSTNAME, port=PORT):
    try:
        # Create an SSH client instance
        ssh_client = paramiko.SSHClient()

        # Automatically add server key to known_hosts file
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Load system host keys
        ssh_client.load_system_host_keys()

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

        # Execute the specified command on the remote server
        stdin, stdout, stderr = ssh_client.exec_command(command)

        # Print the output of the command
        for line in stdout.read().splitlines():
            print(line.decode())

    except paramiko.AuthenticationException as auth_exception:
        print("Authentication failed:", auth_exception)
    except paramiko.SSHException as ssh_exception:
        print("SSHException:", ssh_exception)
    except Exception as exception:
        print("An error occurred:", exception)
    finally:
        # Close the SSH connection
        ssh_client.close()

3. Main Function:

Python
if __name__ == '__main__':
    # Get user input for SSH connection details
    hostname = input("Enter the target hostname: ")
    port = input("Enter the target port (default is 22): ")
    username = input("Enter username: ")
    password = getpass.getpass(prompt="Enter password: ")
    command = input("Enter command: ")

    # Run the SSH command execution function
    run_ssh_cmd(username, password, command, hostname, port)
Python
#!/usr/bin/env python3

import getpass
import paramiko

HOSTNAME = 'localhost'
PORT = 22

def run_ssh_cmd(username, password, command, hostname=HOSTNAME,port=PORT):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.load_system_host_keys()
    ssh_client.connect(hostname, port, username, password)
    stdin, stdout, stderr = ssh_client.exec_command(command)
    #print(stdout.read())
    stdin.close()
    for line in stdout.read().splitlines():
        print(line.decode())

if __name__ == '__main__':
    hostname = input("Enter the target hostname: ")
    port = input("Enter the target port: ")
    username = input("Enter username: ")
    password = getpass.getpass(prompt="Enter password: ")
    command = input("Enter command: ")
    run_ssh_cmd(username, password, command)

Note:

SSH Command Execution Script with Paramiko

This Python script uses the paramiko library to execute a command on a remote SSH server. The script prompts the user for the target hostname, port, username, password, and command to be executed on the remote server.

1. Importing the Required Modules:

Python
#!/usr/bin/env python3

import paramiko
import getpass

2. SSH Command Execution Function:

Python
def run_ssh_command(hostname, user, passwd, command):
    try:
        # Create a transport object
        transport = paramiko.Transport((hostname, 22))

        # Start the SSH connection
        transport.start_client()

        # Authenticate with a username and password
        transport.auth_password(username=user, password=passwd)

        # Check if the authentication was successful
        if transport.is_authenticated():
            print("Connected to", hostname)

            # Open an SSH channel
            channel = transport.open_session()

            # Execute the specified command on the remote server
            channel.exec_command(command)

            # Receive the response from the command
            response = channel.recv(1024)

            # Print the command and its response
            print(f'Command: {command} (User: {user}) --> {response.decode()}')

    except paramiko.AuthenticationException as auth_exception:
        print("Authentication failed:", auth_exception)
    except paramiko.SSHException as ssh_exception:
        print("SSHException:", ssh_exception)
    except Exception as e:
        print("An error occurred:", e)
    finally:
        # Close the SSH connection
        transport.close()

3. Main Function:

Python
if __name__ == '__main__':
    # Get user input for SSH connection details
    hostname = input("Enter the target hostname: ")
    username = input("Enter username: ")
    password = getpass.getpass(prompt="Enter password: ")
    command = input("Enter command: ")

    # Run the SSH command execution function
    run_ssh_command(hostname, username, password, command)
Python
#!/usr/bin/env python3

import paramiko
import getpass

def run_ssh_command(hostname, user, passwd, command):
    transport = paramiko.Transport(hostname)
    try:
        transport.start_client()
    except Exception as e:
        print(e)
    
    try:
        transport.auth_password(username=user,password=passwd)
    except Exception as e:
        print(e)
        
    if transport.is_authenticated():
        print(transport.getpeername())
        channel = transport.open_session()
        channel.exec_command(command)
        response = channel.recv(1024)
        print('Command %r(%r)-->%s' % (command,user,response))

if __name__ == '__main__':
    hostname = input("Enter the target hostname: ")
    port = input("Enter the target port: ")
    username = input("Enter username: ")
    password = getpass.getpass(prompt="Enter password: ")
    command = input("Enter command: ")
    run_ssh_command(hostname,username, password, command)

Note:

Exit mobile version