How can `Rust`'s Command automatically answer the asking password?

I want to invoke some commands, which require the caller to input a password, such as sudo or git pull, these commands will prompt users to input the username and password. I tried to use Rust's Command to implement the functionality, which can automatically input this information, however, the code doesn't work.

use std::{process::{Command,Stdio}, io::Write};
fn main(){
	let mut child =Command::new("sh").stdin(Stdio::piped()).arg("-c").arg("sudo -i").spawn().unwrap();
	child.stdin.as_mut().unwrap().write(b"123456").unwrap();
	let w = child.wait_with_output().unwrap();
	println!("{w:?}");
}

Running this code will observe the terminal line will prompt the user to type a password, and the code child.stdin.as_mut().unwrap().write(b"123456").unwrap(); that would automatically input the password to respond the asking does not work.

How can I make the code work as expected?

The sudo command goes to great lengths to make sure the password prompt goes to the original terminal (and therefore, the user) rather than some intermediate program.

I've found the best strategy is to not invoke sudo from your program, directly. Instead, write your program assuming you have super user access and rely on the user running it with sudo.

That said, running things this way does increase your attack surface, so there's always a security/convenience tradeoff.

4 Likes

Don't do this. git already has the ability to cache credentials.

1 Like

I just show you a similar scene that requires us to input a password in the terminal line. The general requirement is when we invoke the third-part program by Command and that program requires us to input a password in the terminal line, in this case, I want to make the calling program automatically answer the asking input.

I think the function does not only limit to git but also in other scenes that requires the user to input password in the command line.

Use the -S option of sudo:

-S, --stdin
Write the prompt to the standard error and read the
password from the standard input instead of using the
terminal device.

https://man7.org/linux/man-pages/man8/sudo.8.html

This is btw not related to rust at all, you can reproduce your problem in bash.

1 Like

You can also use the script --log-out /dev/null utility to make a recorded terminal session, so when sudo fetches the terminal it lands on script.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.