'How to send prompt input to std::process::Command in rust?
I'm writing a cli tool for 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 is create the users and set user's password.
Normally with bash this will be like this
passwd $user
and this needs get the password as promt input
New password:
I'm trying make something like this
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 resolve something similar but the implementation is a little different since it is a version of the standard library from some time ago, but it is a good base
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Will |