SSH in Python, paramiko

I saw other discussions but found nothing useful

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.0.13', username='aa', password='aa')
stdin, stdout, stderr = ssh.exec_command("sudo reboot")
stdin.write('aa\n')
stdin.flush()
data = stdout.read() + stderr.read()
print(data)
ssh.close()

This code should sort of execute 'sudo reboot' and send the password 'aa' accordingly so that sudo would execute, but this doesn't happen, why? The code itself is executed without errors

UPD: I checked, it connects and "logs in"

Author: Terrorka, 2019-10-28

2 answers

Probably because a terminal is required to enter the password, and you didn't provide any terminal. Try ssh. exec_command (..., get_pty=True) andreymal

 0
Author: Terrorka, 2019-10-28 18:26:54

Try the following code:

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(...)

channel = сlient.get_transport().open_session()
channel.get_pty()
channel.settimeout(5)
channel.exec_command('sudo reboot')
channel.send(password+'\n')
print channel.recv(1024)

channel.close()
client.close()
 0
Author: DarkFox777, 2020-11-01 18:48:17