How to run commands over ssh with Python?

Sometimes, we want to run commands over ssh with Python.

in this articl,e we’ll look at how to run commands over ssh with Python.

How to run commands over ssh with Python?

To run commands over ssh with Python, we can use the Paramiko library.

To install it, we run

pip install paramiko

Then we can use it by writing

import paramiko

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)

to create an ssh client with

ssh = paramiko.SSHClient()

Then we call ssh.connect to connect to the server with the username and password.

And then we call exec_command to run the command we want.

If we use ssh keys, we write

import paramiko

k = paramiko.RSAKey.from_private_key_file(keyfilename)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, pkey=k)

to load the private key file with

paramiko.RSAKey.from_private_key_file(keyfilename)

Then we make the connection with connect.

Conclusion

To run commands over ssh with Python, we can use the Paramiko library.