Sure! Here's a Rust version of your PowerShell script, designed with best practices in mind, as a senior programmer would approach it. This Rust program replicates the functionality of your PowerShell script, managing VMware services and network adapters, ensuring the program runs with administrative privileges, and starting the VMware application.
// main.rs
use std::process::{Command, exit};
use std::io::{self, ErrorKind};
use std::ffi::OsString;
use windows::Win32::Security::{
AllocateAndInitializeSid, CheckTokenMembership, FreeSid, SECURITY_NT_AUTHORITY,
DOMAIN_ALIAS_RID_ADMINS, SECURITY_BUILTIN_DOMAIN_RID, PSID,
};
use windows::Win32::System::Services::{
OpenSCManagerW, OpenServiceW, QueryServiceConfigW, ChangeServiceConfigW, StartServiceW,
ControlService, CloseServiceHandle, SC_MANAGER_CONNECT, SERVICE_START, SERVICE_QUERY_STATUS,
SERVICE_CHANGE_CONFIG, SERVICE_NO_CHANGE, SERVICE_DEMAND_START, SERVICE_CONTROL_STOP,
SERVICE_STOP, SERVICE_STATUS, SERVICE_QUERY_CONFIG,
};
use windows::Win32::UI::Shell::{
ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS,
};
use windows::Win32::Foundation::{HWND, SW_SHOW, HANDLE, BOOL};
use windows::core::PCWSTR;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Ensure the program is running with administrative privileges
if !is_running_as_admin() {
elevate()?;
}
// List of VMware services to manage
let vmware_services = &[
"VMware Authorization Service",
"VMware Autostart Service",
"VMware DHCP Service",
"VMware NAT Service",
"VMware USB Arbitration Service",
];
// Start VMware services
for service_name in vmware_services {
if let Err(e) = start_service(service_name) {
eprintln!("Failed to start service '{}': {}", service_name, e);
}
}
// Enable VMware network adapters
if let Err(e) = enable_vmware_adapters() {
eprintln!("Failed to enable VMware network adapters: {}", e);
}
// Start the VMware Workstation application
if let Err(e) = start_vmware_application() {
eprintln!("Failed to start VMware application: {}", e);
}
// Wait for the VMware application to exit
// This is handled within the start_vmware_application function
// After VMware exits, stop services and disable adapters
for service_name in vmware_services {
if let Err(e) = stop_service(service_name) {
eprintln!("Failed to stop service '{}': {}", service_name, e);
}
}
if let Err(e) = disable_vmware_adapters() {
eprintln!("Failed to disable VMware network adapters: {}", e);
}
Ok(())
}
/// Checks if the current process is running with administrative privileges
fn is_running_as_admin() -> bool {
unsafe {
let mut admin_group_sid: PSID = std::ptr::null_mut();
let nt_authority = SECURITY_NT_AUTHORITY;
let mut result = false;
let res = AllocateAndInitializeSid(
&nt_authority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&mut admin_group_sid,
);
if res.as_bool() {
let mut is_member = BOOL(0);
if CheckTokenMembership(
HANDLE(0),
admin_group_sid,
&mut is_member,
).as_bool() && is_member.as_bool()
{
result = true;
}
FreeSid(admin_group_sid);
}
result
}
}
/// Attempts to elevate the process to have administrative privileges
fn elevate() -> io::Result<()> {
unsafe {
let mut shell_execute_info = SHELLEXECUTEINFOW::default();
shell_execute_info.cbSize = std::mem::size_of::<SHELLEXECUTEINFOW>() as u32;
shell_execute_info.fMask = SEE_MASK_NOCLOSEPROCESS;
shell_execute_info.hwnd = HWND(0);
shell_execute_info.lpVerb = PCWSTR::from_raw("runas\0".encode_utf16().collect::<Vec<u16>>().as_ptr());
let exe_path = std::env::current_exe()?;
let exe_path_str = exe_path.into_os_string().into_string().unwrap();
let exe_path_wide: Vec<u16> = exe_path_str.encode_utf16().chain(std::iter::once(0)).collect();
shell_execute_info.lpFile = PCWSTR::from_raw(exe_path_wide.as_ptr());
shell_execute_info.nShow = SW_SHOW;
if ShellExecuteExW(&mut shell_execute_info).as_bool() {
exit(0);
} else {
Err(io::Error::new(
ErrorKind::Other,
"Failed to restart with administrative privileges.",
))
}
}
}
/// Starts a specified Windows service and sets its startup type to 'Manual'
fn start_service(service_name: &str) -> Result<(), windows::core::Error> {
unsafe {
let scm_handle = OpenSCManagerW(None, None, SC_MANAGER_CONNECT)?;
let service_handle = OpenServiceW(
scm_handle,
PCWSTR::from_raw(format!("{}\0", service_name).encode_utf16().collect::<Vec<u16>>().as_ptr()),
SERVICE_START | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG,
)?;
// Query the current service configuration
let mut buffer = vec![0u8; 8192];
let mut bytes_needed = 0u32;
QueryServiceConfigW(
service_handle,
buffer.as_mut_ptr() as *mut _,
buffer.len() as u32,
&mut bytes_needed,
)?;
let config = *(buffer.as_ptr() as *const _);
// Change startup type to 'Manual' if it's not already
if (*config).dwStartType != SERVICE_DEMAND_START {
ChangeServiceConfigW(
service_handle,
SERVICE_NO_CHANGE,
SERVICE_DEMAND_START,
SERVICE_NO_CHANGE,
None,
None,
None,
None,
None,
None,
None,
)?;
}
// Start the service
StartServiceW(service_handle, &[])?;
CloseServiceHandle(service_handle);
CloseServiceHandle(scm_handle);
}
Ok(())
}
/// Stops a specified Windows service
fn stop_service(service_name: &str) -> Result<(), windows::core::Error> {
unsafe {
let scm_handle = OpenSCManagerW(None, None, SC_MANAGER_CONNECT)?;
let service_handle = OpenServiceW(
scm_handle,
PCWSTR::from_raw(format!("{}\0", service_name).encode_utf16().collect::<Vec<u16>>().as_ptr()),
SERVICE_STOP | SERVICE_QUERY_STATUS,
)?;
let mut service_status = SERVICE_STATUS::default();
ControlService(service_handle, SERVICE_CONTROL_STOP, &mut service_status)?;
CloseServiceHandle(service_handle);
CloseServiceHandle(scm_handle);
}
Ok(())
}
/// Enables all VMware network adapters
fn enable_vmware_adapters() -> io::Result<()> {
let command = r#"Get-NetAdapter | Where-Object {$_.InterfaceDescription -like "*VMware*"} | Enable-NetAdapter -Confirm:$false"#;
run_powershell_command(command)
}
/// Disables all VMware network adapters
fn disable_vmware_adapters() -> io::Result<()> {
let command = r#"Get-NetAdapter | Where-Object {$_.InterfaceDescription -like "*VMware*"} | Disable-NetAdapter -Confirm:$false"#;
run_powershell_command(command)
}
/// Executes a PowerShell command
fn run_powershell_command(command: &str) -> io::Result<()> {
let status = Command::new("powershell")
.args(&["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", command])
.status()?;
if status.success() {
Ok(())
} else {
Err(io::Error::new(
ErrorKind::Other,
"PowerShell command execution failed.",
))
}
}
/// Starts the VMware Workstation application and waits for it to exit
fn start_vmware_application() -> io::Result<()> {
let vmware_path = r"C:\Program Files (x86)\VMware\VMware Workstation\vmware.exe";
let mut child = Command::new(vmware_path).spawn()?;
child.wait()?;
Ok(())
}
Explanation:
-
Administrative Privileges Check and Elevation:
- The
is_running_as_admin function checks if the current process has administrative privileges by checking if it belongs to the Administrators group.
- If not running as admin, the
elevate function uses ShellExecuteExW with the "runas" verb to restart the program with elevated privileges.
-
Service Management:
- The
start_service and stop_service functions use Windows API calls to start and stop services, respectively.
- Before starting a service, the program ensures that its startup type is set to 'Manual' using
ChangeServiceConfigW.
- Services are managed via the Service Control Manager (
OpenSCManagerW), and appropriate permissions are requested.
-
Network Adapter Management:
- The
enable_vmware_adapters and disable_vmware_adapters functions execute PowerShell commands to enable or disable network adapters whose interface descriptions contain "VMware".
- The
run_powershell_command function handles the execution of PowerShell commands from Rust.
-
Starting VMware Application:
- The
start_vmware_application function launches the VMware Workstation application and waits for it to exit using child.wait().
-
Main Function Logic:
- The program performs the following steps in order:
- Checks for administrative privileges and elevates if necessary.
- Starts the specified VMware services.
- Enables the VMware network adapters.
- Starts the VMware application and waits for it to exit.
- After the application exits, it stops the VMware services and disables the network adapters.
Notes for a Senior Programmer:
Dependencies:
To build this program, ensure that you have the windows crate in your Cargo.toml:
[dependencies]
windows = { version = "0.48.0", features = ["Win32_Foundation", "Win32_System_Services", "Win32_Security", "Win32_UI_Shell"] }
Building and Running:
- Install Rust and Cargo from the official website: https://www.rust-lang.org/.
- Create a new Rust project or add this code to your existing project.
- Add the necessary dependencies to your
Cargo.toml file.
- Build the project using
cargo build --release.
- Run the executable. If not run as administrator, it will prompt for elevation.
Disclaimer:
- Ensure that you have the necessary permissions and that it's safe to start and stop VMware services on your system.
- Modifying services and network adapters can disrupt network connectivity and system stability.
- Test this program in a safe environment before deploying it to production systems.