How to execute a root command on linux

Hello I know about
std::process::Command
but how to execute a root command and pass the password again to the command?
Thank you in advance :slight_smile:

Basically sudo is your command and the program you want to run is passed as an argument. You then probably have to pass the passwort to stdin. But I'm not sure if this is working.

Thank you so much @trembel :slight_smile:
Do you know a tutorial of how to do "passing to stdin"?

No, sorry. But I think its a terrible idea. You should run your program with the correct rights or give it the setuid and/or setgid bit

It's for a personal project on my Linux machine to simplify some forgettable commands and to learn Rust in the process.
I want the app to manage the workflow like the real command.
I am not going to store the password anywhere I am going to ask the user to enter it ans pass it to the command.

Maybe this helps you: https://stackoverflow.com/questions/21615188/how-to-send-input-to-a-program-through-stdin-in-rust

Thanks :slight_smile: I'll check this.

You'll typically write your program like normal and then when the user runs it from the command line they'll use sudo my-awesome-program to make sure it runs with the correct permissions.

I'd suggest avoiding invoking sudo from std::process::Command because then you need to provide a way of entering the password, and sudo uses tricks to make sure that password comes from the user's terminal without letting your program see it.

1 Like

If you really want to run your program with sudo, then you need to have the spawned command inherit from the parent's standard input.

This is the case by default when using .status() to run (and wait for) the command, but it is not the case for some of the other ways of spawning the command:

fn main ()
{
    assert!(
        ::std::process::Command::new("sudo")
            .arg("/usr/bin/id")
            .status()
            .unwrap()
            .success()
    );
}
  • asciicast
1 Like