Creating a SSH client using Paramiko


First, we import the necessary libraries: paramiko for SSH connections, time for measuring execution time, and getpass for securely inputting the password.

Next, we define a class called ssh to represent an SSH connection. Inside this class, we have three methods:

a. The __init__ method is the constructor that initializes the ssh object. It takes in the host address, port number, username, and password as parameters. Inside this method, we store the provided values in the object's attributes (self.host, self.port, self.user, self.password), and then we call the connect method to establish the SSH connection.

b. The connect method is responsible for establishing the SSH connection. It creates an SSH client object using paramiko.SSHClient(), sets the host key policy to automatically add the host key to known_hosts, and then connects to the SSH server using the provided credentials (self.client.connect(...)). If the connection is successful, it calls the commands method to start executing commands on the server.

c. The commands method handles the execution of commands on the SSH server. It runs in a loop, prompting the user for commands to execute (cmd = input(...)), until the user enters "exit" to break out of the loop. If the user enters "users", it executes the command "cat /etc/passwd" on the server and displays the output. Otherwise, it executes the entered command on the server and displays the output. The loop can also be interrupted by pressing Ctrl+C. After the loop ends, it closes the SSH connection. Point to note here, you can create any amount of statements for commands you may wish to run with a simple alias as shown with the 'users' calling 'cat /etc/passwd'.

We define a main function that serves as the entry point of the program. Inside this function, we prompt the user for the host address, port number, username, and password using the input function. The getpass.getpass function is used for securely inputting the password without displaying it on the screen. Then, we create an instance of the ssh class, passing the provided information as arguments, which establishes the SSH connection.

Finally, we check if the script is being executed as the main script (__name__ == '__main__'). If it is, we record the starting time using time.time(), call the main function to start the SSH connection process, and then record the ending time. Finally, we display the execution time by calculating the difference between the starting and ending times. Point to note, the timing segment is not necessary, it is a personal preference.

Complete Code


import paramiko  # Importing the paramiko library for SSH connection
import time  # Importing the time library for measuring execution time
import getpass  # Importing the getpass library for securely inputting the password

class ssh:
    def __init__(self, host, port, username, password):
        self.host = host  # Store the host address
        self.port = port  # Store the port number
        self.user = username  # Store the username
        self.password = password  # Store the password
        self.connect()  # Establish an SSH connection upon object initialization
    
    def connect(self):
        try:
            self.client = paramiko.SSHClient()  # Create an SSH client object
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # Automatically add the host key to known_hosts
            self.client.connect(port=self.port, username=self.user, hostname=self.host, password=self.password)  # Connect to the SSH server
            self.commands()  # Start executing commands after successful connection
        except Exception as err:
            print("Error connecting: " + str(err))  # Display an error message if connection fails
        finally:
            pass
    
    def commands(self):
        try:
            while True:
                try:
                    cmd = input("Connection to " + self.host + ": ")  # Prompt for user input
                    if cmd == "exit":
                        break  # Break the loop if the user enters "exit"
                    elif cmd == "users":
                        self.stdin, self.stdout, self.stderr = self.client.exec_command("cat /etc/passwd")  # Execute the command on the SSH server
                        print("\n" + self.stdout.read().decode())  # Display the command output
                    else:
                        self.stdin, self.stdout, self.stderr = self.client.exec_command(cmd)  # Execute the command on the SSH server
                        print("\n" + self.stdout.read().decode())  # Display the command output
                except KeyboardInterrupt:
                    break  # Break the loop if the user interrupts with Ctrl+C
            self.client.close()  # Close the SSH connection
        except Exception as err:
            print("Error: " + str(err))  # Display an error message if an exception occurs

def main():
    host = input("Host: ")  # Prompt for the host address
    port = input("Port: ")  # Prompt for the port number
    username = input("Username: ")  # Prompt for the username
    password = getpass.getpass(prompt='Password: ')  # Prompt for the password without displaying it
    conn = ssh(host=host, port=port, username=username, password=password)  # Create an SSH object and establish connection
    
if __name__ == '__main__':
    start = time.time()  # Record the starting time
    main()  # Call the main function
    end = time.time()  # Record the ending time
    print("Time taken: {:.6f} seconds".format(end - start))  # Display the execution time

Enquiries

[email protected]

Copyright © 2023 - slash-root.com