In Python, we have a library wmi, the wrapper on pywin32 extention that can do this:
import wmi
c = wmi.WMI()
process_watcher = c.Win32_Process.watch_for("creation")
while True:
new_process = process_watcher()
print(new_process.Caption, new_process.ProcessId)
The previous code watches for new process creation in Windows, then prints its name and id.
How can I achieve something similar in Rust? Thank you.
Got it
Here is how it's done:
use std::collections::HashMap;
use std::time::Duration;
use serde::{Deserialize};
use wmi::*;
#[derive(Deserialize, Debug)]
#[serde(rename = "__InstanceCreationEvent")]
#[serde(rename_all = "PascalCase")]
struct NewProcessEvent {
target_instance: Process
}
#[derive(Deserialize, Debug)]
#[serde(rename = "Win32_Process")]
#[serde(rename_all = "PascalCase")]
struct Process {
process_id: u32,
name: String,
executable_path: Option<String>,
}
fn main() {
let mut filters = HashMap::<String, FilterValue>::new();
filters.insert("TargetInstance".to_owned(), FilterValue::is_a::<Process>().unwrap());
let wmi_con = WMIConnection::new(COMLibrary::new().unwrap()).unwrap();
let iterator = wmi_con.filtered_notification::<NewProcessEvent>(&filters, Some(Duration::from_secs(1))).unwrap();
for result in iterator {
let process = result.unwrap().target_instance;
println!("New process!");
println!("PID: {}", process.process_id);
println!("Name: {}", process.name);
println!("Executable: {:?}", process.executable_path);
}
}
5 Likes
system
Closed
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.