-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProcessInfo.py
More file actions
executable file
·242 lines (174 loc) · 6.29 KB
/
ProcessInfo.py
File metadata and controls
executable file
·242 lines (174 loc) · 6.29 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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/env python
"""Get process related info from ip/port unique socket info"""
from subprocess import Popen, PIPE
import pwd
import os
import ProcHandlers
import ProcFieldConstants
PH = ProcHandlers
PFC = ProcFieldConstants
ANY_IPV6_ADDR = "::"
ANY_IP_ADDR = "0.0.0.0"
PRESENT_ANY_IPV6_ADDR = "::0"
PRESENT_ANY_IP_ADDR = "0.0.0.0"
NO_PROCESS_SUMMARY = "n/a"
NO_CONN_PID = -1
NO_RETURNCODE = None
NO_UID = -1
NO_COMMAND = "unknown"
NO_USER = "unknown"
NO_PATH = "[blank]"
SOCKET_PROT_LIST = ("tcp6", "tcp", "udp6", "udp")
DOM_SOCK = "unix"
DOM_SOCK_STATE = ("FREE", "UNCONNECTED", "CONNECTING", "CONNECTED",
"DISCONNECTING")
# ---
def pid_to_cmdline(target = "self"):
"""Find the command line associated with the given process"""
__cmd = ""
__from = "/proc/{pid}/cmdline".format(pid=target)
__handler = ProcHandlers.GET_HANDLER("/proc/self/cmdline")
__act = __handler(__from)
for __res in __act:
if __cmd == "":
__cmd = __res
return __cmd
# ---
def pid_to_comm(target = "self"):
"""Find the binary associated with the given process"""
__cmd = ""
__from = "/proc/{pid}/comm".format(pid=target)
__handler = ProcHandlers.GET_HANDLER("/proc/self/comm")
__act = __handler(__from)
for __res in __act:
if __cmd == "":
__cmd = __res
return __cmd
# ---
def inode_to_socket_map():
"""Create a lookup table mapping inodes to sockets"""
__inode2sock = dict()
for __prot in SOCKET_PROT_LIST:
__act = ProcHandlers.GET_HANDLER(__prot)()
for __hilit in __act:
__curr = __act.field
__inode = __curr[PFC.F_INODE]
__sock = dict()
__sock[PFC.F_DEST_IP] = __curr[PFC.F_DEST_IP]
__sock[PFC.F_DEST_PORT] = __curr[PFC.F_DEST_PORT]
__sock[PFC.F_ORIG_IP] = __curr[PFC.F_ORIG_IP]
__sock[PFC.F_ORIG_PORT] = __curr[PFC.F_ORIG_PORT]
__sock[PFC.F_STATE] = __curr[PFC.F_STATE]
__sock[PFC.F_PROTOCOL] = __prot
__inode2sock[__inode] = __sock
__act = ProcHandlers.GET_HANDLER(DOM_SOCK)()
for __hilit in __act:
__curr = __act.field
__inode = __curr[PFC.F_INODE]
__sock = dict()
__sock[PFC.F_PROTOCOL] = DOM_SOCK
__sock[PFC.F_STATE] = DOM_SOCK_STATE[__curr[PFC.F_STATE]]
__sock[PFC.F_PATH] = __curr[PFC.F_PATH].encode("string-escape")
if __sock[PFC.F_PATH] == "":
__sock[PFC.F_PATH] = NO_PATH
__inode2sock[__inode] = __sock
return __inode2sock
# ---
# pylint: disable=R0914
def socket_inode_to_pid_map():
"""
Create a dictionary mapping inodes to the PID that has them open.
"""
__handler = ProcHandlers.GET_HANDLER("/proc/self/fd/")
__proc_base = "/proc/"
__fd_template = "/proc/{pid}/fd/"
__sock_pref = "socket:["
__trailer = "]"
__inode_map = dict()
try:
__base, __top_dirs, __top_files = os.walk(__proc_base).next()
for __dirname in __top_dirs:
if __dirname.isdigit():
__pid = __dirname
__fdpath = __fd_template.format(pid=__pid)
for __fb, __fd, __fd_list in os.walk(__fdpath):
for __fn in __fd_list:
__path = "{dir}{fn}".format(dir=__fdpath, fn=__fn)
__act = __handler(__path)
for __hilit in __act:
__sym = __act.field[PFC.F_SYMLINK]
if __sym.startswith(__sock_pref):
__inode = __sym.partition(__sock_pref)[2]
__inode = __inode.partition(__trailer)[0]
__inode_map[__inode] = __pid
__inode_map[long(__inode)] = __pid
break
except StopIteration:
pass
return __inode_map
# pylint: enable=R0914
def pid_to_proc_summ_pieces(targetpid = "self"):
"""Lookup username, uid, pid and comm of the indicated process"""
__uid = NO_UID
__pid = NO_CONN_PID
__comm = NO_COMMAND
__user = NO_USER
__stat_file = "/proc/{pid}/status".format(pid=targetpid)
__act = PH.GET_HANDLER(__stat_file)(__stat_file)
for __hilit in __act:
if __uid == NO_UID:
__uid = __act.field[PFC.F_UID]
__pid = __act.field[PFC.F_PID]
__comm = __act.field[PFC.F_PROG_NAME]
try:
__uinfo = pwd.getpwuid(__uid)
__user = __uinfo.pw_name
except KeyError:
__user = str(__uid)
return(__user, __uid, __pid, __comm)
def pid_to_proc_summ(targetpid):
"""Return basic process info associated with the given PID"""
__user, __uid, __pid, __comm = pid_to_proc_summ_pieces(targetpid)
if __uid == NO_UID:
__ps_summ = NO_PROCESS_SUMMARY
__ps_rc = -1
else:
__ps_summ = "{user} {pid} {comm}".format(user=__user, pid=__pid,
comm=__comm)
__ps_rc = 0
return(__ps_summ, __ps_rc)
def connection_to_pid(loc_port, rem_ip, rem_port, net_protocol):
"""Return the PID that has the given socket connections open."""
__rip = rem_ip
if __rip == PRESENT_ANY_IPV6_ADDR or __rip == PRESENT_ANY_IP_ADDR:
__rip = ""
elif __rip == ANY_IPV6_ADDR or __rip == ANY_IP_ADDR:
__rip = ""
__rpo = str(rem_port)
if __rpo == "0":
__rpo = ""
__prot = net_protocol
if __prot == "udp6" or __prot == "tcp6":
__prot = __prot[:-1]
__ipv = "-6"
else:
__ipv = "-4"
__fuser_arg = "{lport:d},{rip:s},{rport:s}/{prot:s}".format(lport=loc_port,
rip=__rip, rport=__rpo, prot=__prot)
# print '::dbg', __prot, __fuser_arg, __ipv
try:
__fufd = Popen(["fuser", __fuser_arg, __ipv], stdout=PIPE, stderr=PIPE)
__sout_buff, __serr_buff = __fufd.communicate()
# print '::dbg ({0:s})'.format(__sout_buff)
if __sout_buff != "":
# Trying to make "pylint" happy here...
__pid = long(str(__sout_buff).split()[0])
else:
__pid = NO_CONN_PID
except ValueError:
__pid = NO_CONN_PID
except OSError:
__pid = NO_CONN_PID
return __pid
if __name__ == "__main__":
print "This is a library of routines to get info about running processes."