Search code examples
commandsudoparamiko

Sending a command in Paramiko as sudo


How can I run a command in a linux box through Paramiko as a sudo user and send the sudo password alomg with it, then get the output? I tried the following code but since it did not return the output ( I tried testing ls -l /root) I am not sure if it’s working or not.

stdin, stdout, stderr =         ssh.exec_command("sudo ls -l")
stdin.write('sudo_password\n')
stdin.flush()
Output = stdout.read.splitlines()

A second question is that My understanding is that we cannot ”sudo -s” in the first command and then run the next commands as root while we have used a non-root command to start the session with at first, right? (Imagine there is no root password on the box)

What is a functional piece of code to send a command as sudo, then provide the password and get the output?

What is a functional code to do the same thing for multiple commands? Can we send the password once and then use the it for the rest of the commands?


Solution

  • thanks to everyone taking their time and posting their answers. there is a straightforward answer to this question and here it is:

    command = 'echo "sudo-password" | sudo <the-command-to-run-as-sudo>'
    stdin, stdout, stderr = SESSION.exec_command(command)
    stdout = stdout.read().decode()
    

    example command:

    command = 'echo "123456" | sudo ls-l /root'
    stdin, stdout, stderr = SESSION.exec_command(command)
    stdout = stdout.read().decode()