rust 命令行程序 检测自己是否 管理员权限运行

180it 2024-10-10 PM 151℃ 0条
[dependencies]
winapi = { version = "0.3", features = ["winnt", "processthreadsapi", "securitybaseapi", "handleapi", "errhandlingapi"] }


extern crate winapi;

use std::ptr::null_mut;
use winapi::um::processthreadsapi::OpenProcessToken;
use winapi::um::securitybaseapi::GetTokenInformation;
use winapi::um::winnt::{TokenElevation, HANDLE, TOKEN_ELEVATION, TOKEN_QUERY};
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::handleapi::CloseHandle;

fn is_running_as_admin() -> bool {
    unsafe {
        let mut token_handle: HANDLE = null_mut();
        let process_handle = winapi::um::processthreadsapi::GetCurrentProcess();

        if OpenProcessToken(process_handle, TOKEN_QUERY, &mut token_handle) == 0 {
            return false;
        }

        let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
        let mut return_length = 0;

        let result = GetTokenInformation(
            token_handle,
            TokenElevation,
            &mut elevation as *mut _ as *mut _,
            std::mem::size_of::<TOKEN_ELEVATION>() as u32,
            &mut return_length,
        );

        CloseHandle(token_handle);

        if result == 0 {
            return false;
        }

        elevation.TokenIsElevated != 0
    }
}

fn main() {
    if is_running_as_admin() {
        println!("程序以管理员权限运行。");
    } else {
        println!("程序未以管理员权限运行。");
    }

    // 这里可以添加其他逻辑,例如执行 PowerShell 命令
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

rust 命令行程序 检测自己是否 管理员权限运行