Reputation: 225
I'm writing a Windows CLI app and I need to run it as administrator. In C# I would add this line to app.manifest:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
How I do that in Rust?
Upvotes: 11
Views: 6533
Reputation: 17
Here is another way to run as administrator. I use the function ShellExecuteA to gain privilege without config anything. This approach allows you to elevate permissions without requiring any additional configuration.
fn run_as_admin() -> bool{
if let Ok(current_exe) = std::env::current_exe() {
if let Some(current_exe_str) = current_exe.to_str() {
unsafe {
let hwnd: HWND = std::mem::zeroed();
let status = ShellExecuteA(
hwnd,
PCSTR::from_raw("runas\0".as_ptr()),
PCSTR::from_raw(current_exe_str.as_ptr()),
PCSTR::null(),
PCSTR::null(),
SW_SHOW,
);
if !status.is_invalid() {
return true;
}
}
}
}
false
Hope this help.
Upvotes: -2
Reputation: 710
Too late, but answering anyway. :-)
Please take a look at the winres
library. It contains the following example:
The following manifest will brand the exe as requesting administrator privileges. Thus, everytime it is executed, a Windows UAC dialog will appear.
let mut res = winres::WindowsResource::new(); res.set_manifest(r#" <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> </assembly> "#);
The full example is documented and available here.
I have been using this library in a project that contains an icon and requires admin privileges, its build.rs
using winres
is hosted here. See the generated executable:
HTH
Upvotes: 19
Reputation: 72044
There is an open RFC #721 for manifest support in Rust.
Aside from discussing ways to add native support, the posts contain links to various workarounds using linker switches or other tools. There is currently no nice way to pass linker switches; you have to put a rustflags
option into a Cargo config file and pass the arguments through to rustc
like this: ["-C", "link-args=/exoticlinkerswitch"]
. This is obviously not very portable.
For tools, you can use mt.exe
from the Windows SDK to add a manifest to your program after it has been compiled.
Note that Cargo does not currently have a way to execute post-build steps automatically. However, there is a Cargo extension, cargo-make
that supports such build processes. You can install it via cargo install cargo-make
.
Upvotes: 2