pub fn run_command_as_user(
cmd: &str,
cmd_args: &[&str],
cmd_input: Option<&[u8]>,
env_list: &[&str],
envs: Option<HashMap<String, String>>,
user: &str,
) -> Result<CommandOutput, Error>Expand description
Runs command with command_args and optional command_input as user.
Uses runuser to run the command as the specific user.
An env_list can be passed in to pass on a specific set of environment variables to the
environment of the user when calling command.
An optional HashMap of envs can be passed in to provide specific overrides of environment
variables passed in to the environment of the user when calling command.
§Note
Running as another user is a privileged action which requires calling this function as root.
§Errors
Returns an error if
- runuser cannot be found,
commandcannot be found,commandcannot be run in background,command_inputis provided, but stdin cannot be attached or written to,commandcannot be executed,- or a UTF-8 error occurred while converting stdout or stderr of the command to string.
§Examples
use std::collections::HashMap;
use change_user_run::run_command_as_user;
// Run `whoami` as the user `test`.
run_command_as_user("whoami", &[], None, &[], None, "test");
// Run `example` as the user `test`, pass in environment variables relevant for `cargo-llvm-cov`.
// Here, we assume that `example` has been compiled with required coverage instrumentation.
let env_list = [
"LLVM_PROFILE_FILE",
"CARGO_LLVM_COV",
"CARGO_LLVM_COV_SHOW_ENV",
"CARGO_LLVM_COV_TARGET_DIR",
"RUSTFLAGS",
"RUSTDOCFLAGS",
];
let mut envs: HashMap<String, String> = HashMap::new();
// Note: This instructs relevant .profraw data to be written to /tmp.
envs.insert(
"LLVM_PROFILE_FILE".to_string(),
"/tmp/project-%p-%16m.profraw".to_string(),
);
run_command_as_user("example", &["--help"], None, &env_list, Some(envs), "test");