Search code examples
pythonsshsudoparamiko

Execute a Command on a Remote Server That Requires Sudo with password input - Paramiko


I am trying to execute a sudo command on a remote machine using python-paramiko, (Python 2.7.9 on linux2) Below is the code. when I execute the code it's giving different output each time, whereas its working fine when I run the same code in python>>> cmdline

import paramiko
import sys
import time
def send_string_and_wait(command, wait_time, should_print):
   shell.send(command)
   time.sleep(wait_time)
   receive_buffer = shell.recv(1024)
   if should_print:
     return  receive_buffer

dbname='test'
cl='testdb'
host='testhost'
owner='uname'
passwd='p'


client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(str(host), username=str(owner),  password=str(passwd), port=22)
shell = client.invoke_shell()
send_string_and_wait("sudo su - oracle\n", 1, True)
send_string_and_wait(str(passwd) + "\n", 1, True)
a=send_string_and_wait("sh Validation_Final.sh" + str(' ') +  str(dbname) + str(' ') + str(cl) + "\n", 0, True)
print a
client.close() 

sample output

Any advise and suggestions will be greatly appreciated, Thank you!


Solution

  • A few years ago I have had similar issues, and it turns out that there might be a few reasons for that.

    One possible option is that the call waits to get a shell prompt in order to return. However, in the case of a command that requires sudo, the behavior might change: In some cases, it will require you to enter the password first. In other cases (e.g., if you have just used sudo and it was not timed out yet), it will not require the password again. This inconsistency might cause problems.

    Take a look here - using -k might solve your problem.

    In order to solve that, you have to define (if possible) that sudo will always require a password, thus make it consistent.

    Another issue that might raise is the definition of the shell prompt (some shells use >, others use $); the same might be true for the sudo - it might print Password:, which contains no shell prompt and might not be recognized by the remote-command agent, and it might print something else, e.g. password.