-
Notifications
You must be signed in to change notification settings - Fork 193
/
find_pid_by_name.rs
76 lines (60 loc) · 1.91 KB
/
find_pid_by_name.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
Find PID By Process name
For More Codes: https://github.com/Whitecat18/Rust-for-Malware-Development.git
Resources Used: MSDOS
@5mukx
*/
macro_rules! okey {
($msg:expr, $($arg:expr), *) => {
println!("[+] {}", format!($msg, $($arg),*));
}
}
macro_rules! error {
($msg:expr, $($arg:expr), *) => {
println!("[!] {}", format!($msg,$($arg),*));
};
}
use std::{ffi::CString, mem};
use winapi::um::{
errhandlingapi::GetLastError,
handleapi::CloseHandle,
tlhelp32::{CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS
}};
fn get_pid(process_name: &str) -> u32{
unsafe{
let mut pe: PROCESSENTRY32 = std::mem::zeroed();
pe.dwSize = mem::size_of::<PROCESSENTRY32>() as u32;
let snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if snap.is_null(){
error!("Error while snapshoting processes : Error : {}",GetLastError());
std::process::exit(0);
}
let mut pid = 0;
let mut result = Process32First(snap, &mut pe) != 0;
while result{
let exe_file = CString::from_vec_unchecked(pe.szExeFile
.iter()
.map(|&file| file as u8)
.take_while(|&c| c!=0)
.collect::<Vec<u8>>(),
);
if exe_file.to_str().unwrap() == process_name {
pid = pe.th32ProcessID;
break;
}
result = Process32Next(snap, &mut pe) !=0;
}
if pid == 0{
error!("Unable to get PID for {}: {}",process_name , "PROCESS DOESNT EXISTS");
std::process::exit(0);
}
CloseHandle(snap);
pid
}
}
fn main(){
// talking snapshot of all in the system.
let process_name = "notepad.exe";
let pid = get_pid(&process_name);
okey!("Got PID: {}",pid);
}