Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send prompt input to std::process::Command in rust?

I'm writing a cli-tool to automate the archlinux installation, that is based on toml config files.

Currently i have this problem: Once the base system is installed and configured, the next topic is creating the users and set their passwords.

Like this:

passwd $user

And this needs to get the password as prompt input

New password:

I'm trying make something like this with rust:

use std::process::Command;

struct User {
    ....
    username: String
    pwd: String
}

...

fn set_pwd(self) -> Result<()> {
    Command::new("chroot")
        .arg("/mnt")
        .arg("passwd")
        .arg(self.username)
        .spawn()
}
...

The problem is that I don't understand, how to pass the password as prompt input to the bash process.

Update:

This question https://stackoverflow.coam/questions/21615188/how-to-send-input-to-a-program-through-stdin-in-rust is something similar, but the implementation is a little different. Because it is a version of the standard library from some time ago.

like image 708
al3x Avatar asked Jun 11 '26 19:06

al3x


1 Answers

finally i based on this question How to send input to a program through stdin in Rust

finally the method look like this...

    fn set_pwd(self) -> Result<()> {
        match Command::new("chroot")
            .stdin(Stdio::piped())
            .arg("/mnt")
            .arg("passwd")
            .arg(self.username)
            .spawn()
        {
            Ok(mut child) => {
                let pwd = format!("{}\n{}", self.pwd, self.pwd);
                child.stdin.as_ref().unwrap().write(pwd.as_bytes()).unwrap();
                child.wait().unwrap();
                Ok(())
            }
            Err(_e) => Err(()),
        }
    }

the difference with the other question, is that instead of using a BuffWriter and the write! macro, the std::process::ChildStdin implements the std::io::Write trait and provides a write method.

like image 195
al3x Avatar answered Jun 14 '26 09:06

al3x



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!