fix CLI
This commit is contained in:
98
trash/proc2log
Executable file
98
trash/proc2log
Executable file
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# proc2log: new processes monitor
|
||||
|
||||
import os
|
||||
import argparse
|
||||
from time import sleep
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
'-p',
|
||||
'--period',
|
||||
help='peroid in seconds between proc checks, default value: 0.1',
|
||||
default=0.1,
|
||||
type=float
|
||||
)
|
||||
args = parser.parse_args()
|
||||
period = args.period
|
||||
|
||||
unknown_name = '<unknown>'
|
||||
|
||||
|
||||
# получение чистого пид сета
|
||||
def foo():
|
||||
proc_list = os.listdir('/proc')
|
||||
proc_set = set()
|
||||
for i in proc_list:
|
||||
if i.isdigit() != True:
|
||||
continue
|
||||
proc_set.add(i)
|
||||
return proc_set
|
||||
|
||||
|
||||
# имя через пид
|
||||
def pid_to_name(pid):
|
||||
try:
|
||||
with open('/proc/' + pid + '/status') as f:
|
||||
for line in f:
|
||||
return line[:-1].split('\t')[1]
|
||||
except FileNotFoundError:
|
||||
return unknown_name
|
||||
|
||||
|
||||
# печать одного пида и имени
|
||||
def print_pid(pid):
|
||||
|
||||
try:
|
||||
with open('/proc/' + pid + '/status') as f:
|
||||
for lineno, line in enumerate(f):
|
||||
name = line[:-1].split('\t')[1]
|
||||
print('+ {}, {}'.format(pid, name))
|
||||
pid_dict[pid] = name
|
||||
if lineno >= 0:
|
||||
break
|
||||
|
||||
except FileNotFoundError:
|
||||
name = pid_dict.pop(pid, unknown_name)
|
||||
print(' - {}, {}'.format(pid, name))
|
||||
|
||||
except ProcessLookupError:
|
||||
name = pid_dict.pop(pid, unknown_name)
|
||||
print(' - {}, {}'.format(pid, name))
|
||||
|
||||
|
||||
# нахождение и печать дельт сетов
|
||||
def delta(old_set):
|
||||
|
||||
new_set = set(os.listdir('/proc'))
|
||||
plus = new_set - old_set
|
||||
minus = old_set - new_set
|
||||
|
||||
if len(plus) > 0:
|
||||
for pid in plus:
|
||||
print_pid(pid)
|
||||
|
||||
if len(minus) > 0:
|
||||
for pid in minus:
|
||||
print_pid(pid)
|
||||
|
||||
return new_set
|
||||
|
||||
|
||||
print('proc2log started with period {} seconds'.format(period))
|
||||
print('+ PID, NAME - PID, NAME')
|
||||
|
||||
# первичное наполнение словаря значениями pid:name для печати имён исчезнувших процессов
|
||||
pid_dict = dict()
|
||||
for pid in foo():
|
||||
pid_dict[pid] = pid_to_name(pid)
|
||||
|
||||
pid_set = set(os.listdir('/proc'))
|
||||
try:
|
||||
while True:
|
||||
pid_set = delta(pid_set)
|
||||
sleep(period)
|
||||
except KeyboardInterrupt:
|
||||
exit()
|
||||
|
||||
Reference in New Issue
Block a user