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