Run a command with sudo after validating sudo access
(program: S, argv: I)
| 97 | |
| 98 | /// Run a command with sudo after validating sudo access |
| 99 | pub fn run_with_sudo<S, I, T>(program: S, argv: I) -> Result<()> |
| 100 | where |
| 101 | S: AsRef<OsStr>, |
| 102 | I: IntoIterator<Item = T>, |
| 103 | T: AsRef<OsStr>, |
| 104 | { |
| 105 | let mut builder = CommandBuilder::new(program); |
| 106 | builder.args(argv); |
| 107 | debug!("Running command with sudo: {}", builder.as_command_line()); |
| 108 | let mut cmd = wrap_with_sudo(builder)?.build(); |
| 109 | let output = cmd |
| 110 | .stdout(Stdio::piped()) |
| 111 | .output() |
| 112 | .map_err(|_| anyhow!("Failed to execute command with sudo: {cmd:?}"))?; |
| 113 | |
| 114 | if !output.status.success() { |
| 115 | info!("stdout: {}", String::from_utf8_lossy(&output.stdout)); |
| 116 | error!("stderr: {}", String::from_utf8_lossy(&output.stderr)); |
| 117 | bail!("Failed to execute command with sudo: {cmd:?}"); |
| 118 | } |
| 119 | |
| 120 | Ok(()) |
| 121 | } |
no test coverage detected