Here’s an example of how you can use Python to SSH into a remote server and run commands.
import paramiko
# create an SSH client object
ssh = paramiko.SSHClient()
# automatically add the remote server's SSH key
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# connect to the remote server
ssh.connect(hostname='hostname', username='username', password='password')
# run a command on the remote server
stdin, stdout, stderr = ssh.exec_command('ls')
# print the output of the command
print(stdout.read().decode())
# close the SSH connection
ssh.close()
This code uses the paramiko
library to handle the SSH connection. The paramiko.SSHClient
object is created to handle the connection, and the set_missing_host_key_policy
method is used to automatically add the remote server’s SSH key to the client’s known_hosts
file. The connect
method is used to connect to the remote server, and the exec_command
method is used to run a command on the remote server. The output of the command is printed using the stdout.read().decode()
method. Finally, the close
method is used to close the SSH connection.