PrivilegedCommand

Struct PrivilegedCommand 

Source
pub struct PrivilegedCommand { /* private fields */ }
Expand description

Builder for executing a program with elevated privileges.

§Example

use privesc::Command;

let output = Command::new("/usr/bin/cat")
    .arg("/etc/shadow")
    .run()?;

§Platform Behavior

  • macOS: Uses osascript with AppleScript for GUI, sudo for CLI.
  • Linux: Uses pkexec for GUI, sudo for CLI.
  • Windows: Uses ShellExecuteExW with “runas” verb (UAC). Output capture is not available.

Implementations§

Source§

impl PrivilegedCommand

Source

pub fn new(program: impl Into<String>) -> Self

Creates a new Command for the given program.

§Arguments
  • program - The path to the program to execute with elevated privileges.
Examples found in repository?
examples/basic.rs (line 4)
3fn main() {
4    let output = PrivilegedCommand::new("cat")
5        .arg("/etc/shadow")
6        .gui(true)
7        .prompt("Administrator privileges required to read the test file")
8        .run()
9        .unwrap();
10
11    println!("Exit status: {}", output.status);
12
13    match output.stdout_str() {
14        Some(stdout) => println!("Out: {stdout}"),
15        None => println!("Out: <not available on this platform>"),
16    }
17
18    match output.stderr_str() {
19        Some(stderr) => println!("Err: {stderr}"),
20        None => println!("Err: <not available on this platform>"),
21    }
22}
More examples
Hide additional examples
examples/spawn.rs (line 7)
5fn main() {
6    // Spawn a privileged process without blocking
7    let mut child = PrivilegedCommand::new("sleep").arg("2").spawn().unwrap();
8
9    if let Some(id) = child.id() {
10        println!("Spawned process with ID: {id}");
11    }
12
13    // Do some work while the process runs
14    println!("Doing other work while process runs...");
15
16    sleep(Duration::from_secs(1));
17
18    // Check if the process has finished (non-blocking)
19    match child.try_wait().unwrap() {
20        Some(status) => println!("Process already finished with: {status}"),
21        None => println!("Process still running..."),
22    }
23
24    // Wait for the process to complete
25    println!("Waiting for process to finish...");
26    let output = child.wait().unwrap();
27
28    println!("Exit status: {}", output.status);
29}
Source

pub fn arg(self, arg: impl Into<String>) -> Self

Adds a single argument to pass to the program.

Examples found in repository?
examples/basic.rs (line 5)
3fn main() {
4    let output = PrivilegedCommand::new("cat")
5        .arg("/etc/shadow")
6        .gui(true)
7        .prompt("Administrator privileges required to read the test file")
8        .run()
9        .unwrap();
10
11    println!("Exit status: {}", output.status);
12
13    match output.stdout_str() {
14        Some(stdout) => println!("Out: {stdout}"),
15        None => println!("Out: <not available on this platform>"),
16    }
17
18    match output.stderr_str() {
19        Some(stderr) => println!("Err: {stderr}"),
20        None => println!("Err: <not available on this platform>"),
21    }
22}
More examples
Hide additional examples
examples/spawn.rs (line 7)
5fn main() {
6    // Spawn a privileged process without blocking
7    let mut child = PrivilegedCommand::new("sleep").arg("2").spawn().unwrap();
8
9    if let Some(id) = child.id() {
10        println!("Spawned process with ID: {id}");
11    }
12
13    // Do some work while the process runs
14    println!("Doing other work while process runs...");
15
16    sleep(Duration::from_secs(1));
17
18    // Check if the process has finished (non-blocking)
19    match child.try_wait().unwrap() {
20        Some(status) => println!("Process already finished with: {status}"),
21        None => println!("Process still running..."),
22    }
23
24    // Wait for the process to complete
25    println!("Waiting for process to finish...");
26    let output = child.wait().unwrap();
27
28    println!("Exit status: {}", output.status);
29}
Source

pub fn args<I, S>(self, args: I) -> Self
where I: IntoIterator<Item = S>, S: Into<String>,

Adds multiple arguments to pass to the program.

Source

pub fn gui(self, gui: bool) -> Self

Sets whether to use a GUI prompt for authentication.

  • true: Use GUI prompt (AppleScript on macOS, pkexec on Linux, UAC on Windows)
  • false: Use terminal-based sudo (default)

On Windows, this parameter is ignored as only UAC elevation is available.

Examples found in repository?
examples/basic.rs (line 6)
3fn main() {
4    let output = PrivilegedCommand::new("cat")
5        .arg("/etc/shadow")
6        .gui(true)
7        .prompt("Administrator privileges required to read the test file")
8        .run()
9        .unwrap();
10
11    println!("Exit status: {}", output.status);
12
13    match output.stdout_str() {
14        Some(stdout) => println!("Out: {stdout}"),
15        None => println!("Out: <not available on this platform>"),
16    }
17
18    match output.stderr_str() {
19        Some(stderr) => println!("Err: {stderr}"),
20        None => println!("Err: <not available on this platform>"),
21    }
22}
Source

pub fn prompt(self, prompt: impl Into<String>) -> Self

Sets a custom prompt message for authentication.

On Windows, this is ignored as UAC displays its own prompt. On Linux with GUI mode, this is ignored due to pkexec limitations.

Examples found in repository?
examples/basic.rs (line 7)
3fn main() {
4    let output = PrivilegedCommand::new("cat")
5        .arg("/etc/shadow")
6        .gui(true)
7        .prompt("Administrator privileges required to read the test file")
8        .run()
9        .unwrap();
10
11    println!("Exit status: {}", output.status);
12
13    match output.stdout_str() {
14        Some(stdout) => println!("Out: {stdout}"),
15        None => println!("Out: <not available on this platform>"),
16    }
17
18    match output.stderr_str() {
19        Some(stderr) => println!("Err: {stderr}"),
20        None => println!("Err: <not available on this platform>"),
21    }
22}
Source

pub fn run(&self) -> Result<PrivilegedOutput>

Executes the command with elevated privileges.

§Returns

A PrivilegedOutput containing the exit status and optionally captured stdout/stderr. Note that stdout/stderr are None on Windows.

Examples found in repository?
examples/basic.rs (line 8)
3fn main() {
4    let output = PrivilegedCommand::new("cat")
5        .arg("/etc/shadow")
6        .gui(true)
7        .prompt("Administrator privileges required to read the test file")
8        .run()
9        .unwrap();
10
11    println!("Exit status: {}", output.status);
12
13    match output.stdout_str() {
14        Some(stdout) => println!("Out: {stdout}"),
15        None => println!("Out: <not available on this platform>"),
16    }
17
18    match output.stderr_str() {
19        Some(stderr) => println!("Err: {stderr}"),
20        None => println!("Err: <not available on this platform>"),
21    }
22}
Source

pub fn spawn(&self) -> Result<PrivilegedChild>

Spawns the command with elevated privileges, returning a handle to the process.

Unlike run, this method returns immediately after spawning, allowing you to perform other work while the privileged process runs.

§Returns

A PrivilegedChild handle that can be used to wait for the process to finish.

§Platform Behavior
  • macOS/Linux: Returns a handle wrapping the underlying process.
  • Windows: Returns a handle wrapping the Windows process HANDLE.
§Example
use privesc::PrivilegedCommand;

let child = PrivilegedCommand::new("/usr/bin/long-running-task")
    .spawn()?;

// Do other work...

let output = child.wait()?;
Examples found in repository?
examples/spawn.rs (line 7)
5fn main() {
6    // Spawn a privileged process without blocking
7    let mut child = PrivilegedCommand::new("sleep").arg("2").spawn().unwrap();
8
9    if let Some(id) = child.id() {
10        println!("Spawned process with ID: {id}");
11    }
12
13    // Do some work while the process runs
14    println!("Doing other work while process runs...");
15
16    sleep(Duration::from_secs(1));
17
18    // Check if the process has finished (non-blocking)
19    match child.try_wait().unwrap() {
20        Some(status) => println!("Process already finished with: {status}"),
21        None => println!("Process still running..."),
22    }
23
24    // Wait for the process to complete
25    println!("Waiting for process to finish...");
26    let output = child.wait().unwrap();
27
28    println!("Exit status: {}", output.status);
29}

Trait Implementations§

Source§

impl Clone for PrivilegedCommand

Source§

fn clone(&self) -> PrivilegedCommand

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PrivilegedCommand

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.