When I login via putty, I give my username and password and login. After logging in, I use the below command to switch to a different user group:
sudo su - test_user
I enter the password when promted and the user changes to test_user.
Now I am trying to achieve the same using python Paramiko. But I am not able to do it. Below is the code that I have tried:
import paramiko
hostname = 'host'
port = '22'
username = 'bs'
password = '*****'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_system_host_keys()
ssh.connect(hostname=hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command('sudo su - test_user')
stdin.write('*****\n')
stdin.flush()
print(f"STDOUT: {stdout.read().decode('utf8')}")
print(f"STDERR: {stderr.read().decode('utf8')}")
ssh.close()
The error I get is:
STDERR: sudo: no tty present and no askpass program specified
I have also tried the below but I still could not switch user:
stdin, stdout, stderr = ssh.exec_command('sudo su - test_user', get_pty = True) -> the code keeps running and does not end until manually stopped.
stdin, stdout, stderr = ssh.exec_command('sudo -S test_user')
Error:
STDERR: [sudo] password for bs: sudo: test_user: command not found
stdin, stdout, stderr = ssh.exec_command('sudo -S chown -R test_user:test_user /tmp/test.txt')
Error:
STDERR: [sudo] password for bs: