Reputation: 46899
I would like to ensure my executable is run with root
permissions under Linux. i came up with this:
use std::env;
use std::process::exit;
fn main() {
match env::var("USER") {
Err(e) => {
println!("Something went wrong: {:?}", e);
exit(2);
}
Ok(name) => {
if name != "root" {
println!("Must be root...");
exit(1);
}
}
}
println!("ok!");
}
Is there a more concise / idiomatic way to do this? How could I have access to the effective user id (EUID)?
Upvotes: 1
Views: 3686
Reputation: 46899
What I've found (and what is used in libcryptsetup-rs
) is this:
use nix::unistd::Uid;
fn main() {
if !Uid::effective().is_root() {
panic!("You must run this executable with root permissions");
}
}
Whether to panic!
, println!
, or exit
is up to the programmer to decide.
Upvotes: 5