Lancer une commande sur une serveur distant avec ssh et pexpect de python


Exemple de code sur comment créer un tunnel ssh et lancer des commandes sur une serveur distant en utilisant pexpect de python:

import pexpect

host = "toto@machine_b.fr"

child = pexpect.spawn('ssh toto@machine_b.fr')

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

child.expect("password:")
child.sendline('my_password')
child.expect ('[#\$] ')

print('----- command 1 ------')

child.sendline('ls -l')
child.expect ('[#\$] ')
print(child.before)

print('----- command 2 ------')

child.sendline('pwd')
child.expect ('[#\$] ')

print(child.before)

child.close()

Note: voir cet article pour convertir des octets (bytes) en chaîne de caractères (string) sous python.

Références