Mihael Waschl
Mihael Waschl

Reputation: 350

How can I enter a password in a sudo command powered by a subprocess?

I am trying to run this command sudo nmap -sP -n with python subprocess library, my goal is creating script when I run the command the script will read the password from a file and add it to the subprocess and execute the command. The problem is that I allways have to write password to execute the command.

I have tried this, but it did not work for me.

p = subprocess.Popen(["sudo", "nmap", "-sP", "-n", network], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(bytes("Mypassword", "utf-8"))

I found some solutions here Use subprocess to send a password, I tried all of them but it did not work for me. Any idea how can I solve the problem?

Upvotes: 0

Views: 994

Answers (1)

Alassane Ndiaye
Alassane Ndiaye

Reputation: 4767

The sudo man page specifies:

 -S, --stdin
             Write the prompt to the standard error and read the password from the stan‐
             dard input instead of using the terminal device.  The password must be fol‐
             lowed by a newline character.

Running the following code should fix your issue:

p = subprocess.Popen(["sudo", "-S", "cmd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("password\n")

Obviously, make sure you give the right password or this won't work. Also, don't forget to add \n at the end.

As an alternative, you can run nmap as an unprivileged user. This will allow you to use nmap --privileged ... which doesn't require a password. As specified in the link though, make sure you understand the security concerns to make sure it isn't an issue for your use case.

Upvotes: 1

Related Questions