-1

I was in need of a script to perform certain actions remotely using python and paramiko. I performed sudo operations in remote machine using

'echo '+password+' | sudo -S '+'cmd_to_be_executed'

and tty issue was solved by setting the flag get_pty as true in paramiko. Now there is a remote machine which does not have sudo permission for that user, only way to switch to root is by using su command. So I tried

'echo '+password+' | su -c '+'cmd_to_be_executed'

but it throws tty issue. Now even if I, set pty flag as true in paramiko the same issue appears

standard in must be a tty

Is there any way to solve this ? Any help is much appreciated thanks!!!

1 Answers1

0

Yes. You can use a Python command script achieve this.

Use argparse to accept command line arguments, which will be your password.

Use subprocess.run to call your script. You may need to use the shell=True with subprocess. (Or use Pexpect instead of subprocess).

Try something like this:

import subprocess, argparse

#Set up the command line arguments

parser = argparse.ArgumentParser(description='Provide root password.')
parser.add_argument('--password', help='password help')

# Collect the arguments from the command line
args = parser.parse_args()

# Open a pipe to the command you want to run
p = subprocess.Popen(['su', '-c', !!your command here!!],stdout=subprocess.PIPE,stdin=subprocess.PIPE)

# Prepare the password and write it
pwd = args.password + '\n'
p.stdin.write(pwd)
p.communicate()[0]
p.stdin.close()
Alan
  • 2,914
  • 2
  • 14
  • 26
  • 1
    `popen()` cannot handle commands like `ssh`/`su` which read passwords from tty. that's why we have `expect`/`pexpect`. – pynexj Jun 03 '17 at 02:58
  • The same error persists moreover I should use ssh to connect to the remote machine at first – Arunagiriswaran Ezhilan Jun 03 '17 at 03:54
  • Yes, you would need to have the python script running on the remote machine after you ssh onto it (take a look at https://stackoverflow.com/questions/4180390/execute-remote-python-script-via-ssh) – Alan Jun 03 '17 at 14:16