Bootstrap FreeKB - Python (Scripting) - SSH using paramiko
Python (Scripting) - SSH using paramiko

Updated:   |  Python (Scripting) articles

paramiko can be used to make an SSH connection onto a target system and to issue a command on the target system.

At the bare minimum, the following is all that should be needed to make an SSH connection if the SSH server accepts basic authentication (username, password).

#!/usr/bin/python
import paramiko

ssh = paramiko.SSHClient()
result = ssh.connect("<hostname or IP address of target system>", username="<username>",password="<password>")

print(result)
ssh.close()

 

Or like this, using an SSH key instead of a password, on a Linux system.

ssh.connect(server, username="john.doe", key_filename="/home/john.doe/.ssh/id_rsa.pub")

 

Or like this, using an SSH key instead of a password, on a Windows system.

ssh.connect(server, username="john.doe", key_filename=r"C:\Users\johndoe\.ssh\id_rsa")

 

If the SSH connection is successful, something like this should be printed.

<paramiko.client.SSHClient object at 0x7f1c69212f50>

 

Here is a more complete example which uses try / except / else to catch exceptions, ssh_exec to run a command after creating the SSH connection, and ssh.close to close the SSH connection.

#!/usr/bin/python3
import paramiko

def ssh_connect(server, user, pw):
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  try:
    ssh.connect(server, username=user, key_filename"/home/john.doe/.ssh/id_rsa.pub")
  except Exception as exception:
    return f"ssh.connect raised the following exception: {exception}"
  else:
    return ssh

def ssh_exec(ssh, command):
  try:
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
  except Exception as exception:
    return f"ssh.exec_command raised the following exception: {exception}"
  else:
    return ssh_stdout.read(), ssh_stderr.read(), ssh_stdout.channel.recv_exit_status()

ssh = ssh_connect("server1.example.com", "john.doe", "itsasecret")

stdout, stderr, return_code = ssh_exec(ssh, "the command you want to issue on the target system")
print(f"stdout      = {stdout}")
print(f"stderr      = {stderr}")
print(f"return code = {return_code}")
ssh.close()

 

Be aware that paramiko may append unwanted events to your log file. If you are using logging, you can set paramiko to only log events at a certain log level, such as WARNING.

logging.getLogger("paramiko").setLevel(logging.WARNING)

 

With Python 2, the output should be returned as a string, but with Python 3 the stdout and stderr is returned as bytes, so it's a good idea to include decode to convert bytes to string for Python 3.

def ssh_exec(ssh, command):
  try:
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
  except Exception as e:
    return f"ssh.exec_command raised the following exception: {exception}"
  else:
    return ssh_stdout.read().decode('utf-8'), ssh_stderr.read().decode('utf-8'), ssh_stdout.channel.recv_exit_status()

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter c1dbf0 in the box below so that we can be sure you are a human.