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:

  • Secure remote access: SSH provides a secure way to access a computer remotely without the risk of unauthorized access or data breaches.
  • Administrative control: SSH allows administrators to manage and maintain remote servers from anywhere with an internet connection.
  • File transfer capabilities: SSH can be used to transfer files securely between computers, enabling efficient file management and collaboration.
  • Port forwarding: SSH can be used to forward ports, allowing users to access services running on the remote server through a different port.
  • Tunnel creation: SSH can be used to create secure tunnels, enabling secure communication between two otherwise unsecure networks.

Key Components of an SSH Server:

  • SSH Daemon (sshd): The software that listens for incoming SSH connections and manages the authentication process.
  • SSH Client: The software that users install on their local computers to connect to the SSH server.
  • SSH Protocol: The set of rules and specifications that govern the communication between the SSH client and 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 [username]@[server_address]: Connect to the SSH server specified by the address.
  • ls: List the contents of the current directory.
  • cd [directory]: Change the current directory.
  • pwd: Print the current working directory.
  • mkdir [directory]: Create a new directory.
  • rmdir [directory]: Remove an empty directory.
  • rm [filename]: Remove a file.
  • cat [filename]: Display the contents of a file.
  • cp [source_file] [destination_file]: Copy a file.
  • mv [source_file] [destination_file]: Move or rename a file.
  • scp [local_file] [remote_user]@[remote_address]:[remote_file]: Copy a file from the local machine to the remote server.
  • scp [remote_user]@[remote_address]:[remote_file] [local_file]: Copy a file from the remote server to the local machine.

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:

  • Changing the default SSH port (22) to a different port:
Bash
sudo nano /etc/ssh/sshd_config
  • Disabling root login over SSH:
Bash
sudo nano /etc/ssh/sshd_config
  • Setting up SSH key-based authentication for passwordless login:
Bash
ssh-keygen
  • Restricting SSH access to specific IP addresses or subnets:
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:

  • SSH connections and authentication: Establish secure connections to SSH servers, handle authentication methods like password or key-based authentication, and manage session parameters.
  • SSH command execution: Execute commands on remote SSH servers, capture output and error streams, and interact with remote processes.
  • SFTP file transfers: Initiate SFTP sessions, upload and download files, manage file permissions, and navigate the remote filesystem.
  • SSH tunneling: Create secure tunnels between local and remote ports, enabling secure communication over otherwise unsecure networks.

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:

  • Simplified file transfers: Upload, download, rename, and delete files using simpler functions and methods.
  • Directory management: Create, navigate, and remove directories on the remote SFTP server.
  • Error handling: Convenient error handling mechanisms to deal with SFTP-related errors.

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:

  • For low-level SSH interactions and granular control over SSH protocols, use Paramiko.
  • For simplified SFTP file transfers and directory management, use pysftp.

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:

  • Ensure that the provided SSH server allows password-based authentication.
  • Always follow security best practices when dealing with authentication credentials. Using keys instead of passwords is recommended for increased security.

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:

  • The script prompts the user for input, including sensitive information like the password. Ensure to handle such information securely.
  • This script is for educational purposes and may need adjustments for production use. Consider using key-based authentication for increased security in a production environment.

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:

  • The script prompts the user for input, including sensitive information like the password. Ensure to handle such information securely.
  • This script is for educational purposes and may need adjustments for production use. Consider using key-based authentication for increased security in a production environment.
Total
0
Shares

Leave a Reply

Previous Post
Building an anonymous FTP scanner with python

Building an anonymous FTP scanner with python

Next Post
Using Paramiko to brute-force SSH user credentials

Using Paramiko to brute-force SSH user credentials

Related Posts