'login as different user to run commands using paramiko

import paramiko
import time
hostname = "myserver.com"
username = input ('Enter Username:' )
password = input ('Enter Password:' )
command = "'sudo -u anotheruser -i'; 'whoami'"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect (hostname,
             port=22,username=username,
             password=password,
             look_for_keys=False,
             allow_agent=False)
stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
print ('Command Sent:')
stdin.write("mysudopassoword\n")
print ("Password Sent")
stdin.flush()
time.sleep(2)
print(f'STDOUT:{stdout.read().decode("utf8")}')
print(f'STDERR:{stderr.read().decode("utf8")}')

if stderr.channel.recv_exit_status() != 0:
    print (f"Following error occured:{stderr.readlines()}")
else:
    print ("All good")
stdin.close()
stdout.close()
stderr.close()
ssh.close

I am trying to run the commands on remote server logging as a different user. The above code points password sent but it hangs in there forever.



Solution 1:[1]

The issue is that exec_command creates a new channel everytime you use it. Instead we can invoke_shell which will return a channel object.

import paramiko
import time

host = "myserver.com"
username = "user"
password = "pass"
port = "22"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)

commands = ['sudo su - abc', 'mkdir foo']

channel = ssh.invoke_shell()

time.sleep(1) 
channel.recv(9999)
channel.send("\n")
time.sleep(1)

for command in commands:
    channel.send(command + "\n")
    while not channel.recv_ready(): 
        time.sleep(0.1)
    time.sleep(0.1) 
    output = channel.recv(9999) 
    print(output.decode('utf-8'))
    time.sleep(0.1)
channel.close()
  • You can pass a list of commands as shown above
  • Reference

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikhileshwar Nanduri