-
Notifications
You must be signed in to change notification settings - Fork 312
Expand file tree
/
Copy pathkillProcessByName.py
More file actions
47 lines (37 loc) · 1.3 KB
/
Copy pathkillProcessByName.py
File metadata and controls
47 lines (37 loc) · 1.3 KB
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
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:killProcessByName.py
User: Guodong
Create Date: 2016/10/31
Create Time: 16:56
"""
import psutil
# learn from getpass.getuser()
def getuser():
"""Get the username from the environment or password database.
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
"""
import os
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
return user
currentUserName = getuser()
ProcessNameToKill = 'chrome.exe'
if ProcessNameToKill in [x.name() for x in psutil.process_iter()]:
print "Process \"%s\" is found!" % ProcessNameToKill
else:
print "Process \"%s\" is NOT running!" % ProcessNameToKill
for process in psutil.process_iter():
if process.name() == ProcessNameToKill:
try:
# root user can only kill its process, but can NOT kill other users process
if process.username().endswith(currentUserName):
process.kill()
print "Process \"%s(pid=%s)\" is killed!" % (process.name(), process.pid)
except Exception as e:
print e