Perform commands with Python over ssh



I need to run some commands on a remote computer. Manually, I will log in with ssh and run the command. How would you automate this in Python? You need for example to log in to the remote computer with a (known) password, so I can't just use cmd = ssh user @ remotehost, and then use the paramiko module for authentication and automation on the server side.


Very simple example:


ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(server, username=username, password=password)

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)



If you are using ssh keys, do:

k = paramiko.RSAKey.from_private_key_file(keyfilename)

k = paramiko.DSSKey.from_private_key_file(keyfilename)

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


Or


commands.getstatusoutput("ssh machine 1 'your script'")


www.paramiko.org


Paramiko is a Python (2.7, 3.4+) implementation of the SSHv2 protocol [1], and provides both client and server functions. Although Paramiko uses Python C extensions for low-level encryption (Cryptography), it itself is a pure Python interface around the concept of SSH networking.



pip install paramiko


Script example


import paramiko

import scenarios



def play_scenario(scenario):

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(scenario["host"], username=scenario["username"], password=scenario["password"])

print('==========================================')

print(scenario["host"] + " " + scenario["label"])

print('------------------------------------------')

for cmd in scenario["cmds"]:

print(cmd)

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)

print(ssh_stdout.read())

print(ssh_stderr.read())


for scenario in scenarios.items:

play_scenario(scenario)


from datetime import datetime



today = datetime.today()

this_month_folder = str(today.year) + "/" + str(today.month) + "/"


Example scenario


# Scenarios

vindazo_ = {"label":"Belgie Web and Database all in one", "host":"vindazo.com", "username":"", "password": "", "cmds": ["find /mnt/backupbox/database/ -iname '*in_progress*'", "ps aux |grep pg_dump", "ps aux |grep python", "du -h /media/sdd/backups/database/", "du -h /mnt/backupbox/database/", "du -h /mnt/backupbox/daily/www/vindazo_be/media/files/" + this_month_folder, ]}



du -h /media/sdd/backups/database/

du -h /mnt/backupbox/database/

ls -al /mnt/backupbox/daily/www/vindazo_be/media/files/2021/5/









Trouble shuting paramiko does not automatically add unknown hosts

paramiko/client.py", line 809, in missing_host_key


ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())





Comments