Skip to content

Commit 825a15c

Browse files
committed
find pid by process name
1 parent f986d4f commit 825a15c

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Malware_Tips/find_pid_by_name.rs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
macro_rules! okey {
2+
($msg:expr, $($arg:expr), *) => {
3+
println!("[+] {}", format!($msg, $($arg),*));
4+
}
5+
}
6+
macro_rules! error {
7+
($msg:expr, $($arg:expr), *) => {
8+
println!("[!] {}", format!($msg,$($arg),*));
9+
};
10+
}
11+
12+
13+
use std::{ffi::CString, mem};
14+
15+
use winapi::um::{
16+
errhandlingapi::GetLastError,
17+
handleapi::CloseHandle,
18+
tlhelp32::{CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS
19+
}};
20+
21+
fn get_pid(process_name: &str) -> u32{
22+
unsafe{
23+
let mut pe: PROCESSENTRY32 = std::mem::zeroed();
24+
pe.dwSize = mem::size_of::<PROCESSENTRY32>() as u32;
25+
26+
let snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
27+
if snap.is_null(){
28+
error!("Error while snapshoting processes : Error : {}",GetLastError());
29+
std::process::exit(0);
30+
}
31+
32+
let mut pid = 0;
33+
34+
let mut result = Process32First(snap, &mut pe) != 0;
35+
36+
while result{
37+
38+
let exe_file = CString::from_vec_unchecked(pe.szExeFile
39+
.iter()
40+
.map(|&file| file as u8)
41+
.take_while(|&c| c!=0)
42+
.collect::<Vec<u8>>(),
43+
);
44+
45+
if exe_file.to_str().unwrap() == process_name {
46+
pid = pe.th32ProcessID;
47+
break;
48+
}
49+
result = Process32Next(snap, &mut pe) !=0;
50+
}
51+
52+
if pid == 0{
53+
error!("Unable to get PID for {}: {}",process_name , "PROCESS DOESNT EXISTS");
54+
std::process::exit(0);
55+
}
56+
57+
CloseHandle(snap);
58+
pid
59+
}
60+
}
61+
62+
fn main(){
63+
// talking snapshot of all in the system.
64+
65+
let process_name = "notepad.exe";
66+
let pid = get_pid(&process_name);
67+
okey!("Got PID: {}",pid);
68+
69+
}

0 commit comments

Comments
 (0)