Running commands with paramiko

Now that we are connected to the remote host with paramiko, we can run commands on the remote host using this connection. To connect, we can simply call the connect() method, along with the target hostname and the SSH login credentials. To run any command on the target host, we need to invoke the exec_command() method by passing the command as its argument:

ssh_client.connect(hostname, port, username, password)
stdin, stdout, stderr = ssh_client.exec_command(cmd)
for line in stdout.readlines():
print(line.strip())
ssh.close()

The following code listing shows how to do an SSH login to a target host and then run the command the user introduced in the prompt. You can find the following code in the ssh_execute_command.py file:

#!/usr/bin/env python3

import getpass
import paramiko

HOSTNAME = 'ssh_server'
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)

if __name__ == '__main__':
username = input("Enter username: ")
password = getpass.getpass(prompt="Enter password: ")
command = input("Enter command: ")
run_ssh_cmd(username, password, command)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset