def collect_status(pid, appname, site): ip_out = get_host_info()[0] ip_inner = get_host_info()[1] server_id = get_host_info()[2] physical_mem = psutil.virtual_memory().total / 1024 / 1024 #Unit of M cpu_count = psutil.cpu_count() its = int(time.time()) p_ins = Process(pid) pstatus = p_ins.status() create_time = time.strftime("%Y%m%d %H:%M:%S", time.localtime(p_ins.create_time())) memory_percent = p_ins.memory_percent() memory_used = memory_percent * physical_mem cpu_calc_list = [] for i in range(6): cpu_calc = p_ins.cpu_percent(interval=0.1) cpu_calc_list.append(cpu_calc) cpu_percent = float(sum(cpu_calc_list) / len(cpu_calc_list)) num_fds = p_ins.num_fds() connections = p_ins.connections() connections_num = len(connections) #appname=p_ins.cwd() if p_ins.name() == 'jsvc': app_path = p_ins.exe().split('/')[:-2] else: app_path = p_ins.cwd() #appname = app_path.split('/')[-1] appname = appname if p_ins.children(recursive=True): children_list = str(p_ins.children(recursive=True)) else: children_list = None message = { 'site': site, 'ip': ip_out, 'ip_inner': ip_inner, 'server_id': server_id, 'pstatus': pstatus, 'metric_name': 'app_monitor', 'its': its, 'pid': pid, 'physical_mem': physical_mem, 'memory_used': memory_used, 'memory_percent': memory_percent, 'cpu_count': cpu_count, 'cpu_percent': cpu_percent, 'num_fds': num_fds, 'connections_num': connections_num, 'create_time': create_time, 'appname': appname, 'app_path': app_path, 'children': children_list } return message
def main(): connections = psutil.net_connections() listen = list(filter(lambda x: x.status == 'LISTEN', connections)) listen_sorted = sorted(listen, key=lambda x: x.laddr.port) print(f"{'ip':<12} {'port':<6} {'user':<16} {'started':<15} {'parent':<15} {'cwd':<30} {'cmdline'}".upper()) for l in listen_sorted: ip = l.laddr.ip port = l.laddr.port if not l.pid: cwd, user, cmdline, started = 4 * ["NOPERM"] else: p = Process(l.pid) parent = p.parent().name() cwd = p.cwd() user = p.username() cmdline = " ".join(p.cmdline()) started = arrow.get(p.create_time()).humanize() print(f"{ip:<12} {port:<6} {user:<16} {started:<15} {parent:<15} {cwd:<30} {cmdline}")
def get_executable_file(l_command_variations: List[str], process: psutil.Process) -> str: """ >>> if lib_platform.is_platform_linux: ... import getpass ... import unittest ... import importlib ... import importlib.util ... import time ... save_actual_directory = str(pathlib.Path().cwd().absolute()) ... test_directory = lib_path.get_test_directory_path('lib_shell', test_directory_name='tests') ... # for travis we need to be owner - otherwise we get permission error ... lib_path.make_test_directory_and_subdirs_fully_accessible_by_current_user(test_directory) ... os.chdir(str(test_directory)) ... try: ... process = subprocess.Popen(['./test test/test test.sh', './test test/some_parameter', 'p1', 'p2']) ... psutil_process=psutil.Process(process.pid) ... # test relative path ... l_command_variations = get_l_command_variations('./test test/test test.sh "./test test/some_parameter" p1 p2') ... assert get_executable_file(l_command_variations, psutil_process) == './test test/test test.sh' ... # test absolute path ... l_command_variations = get_l_command_variations(str(test_directory / 'test test/test test.sh') + ' "./test test/some_parameter" p1 p2') ... assert get_executable_file(l_command_variations, psutil_process).endswith('/test test/test test.sh') ... # test executable not existing, with blank in executable ... l_command_variations = get_l_command_variations('./test test/not_existing.sh "./test test/some_parameter" p1 p2') ... unittest.TestCase().assertRaises(RuntimeError, get_executable_file, l_command_variations, psutil_process) ... psutil_process.kill() ... finally: ... os.chdir(save_actual_directory) """ is_absolute_path = get_is_absolute_path(l_command_variations[0]) for command_variation in l_command_variations: if is_absolute_path: if pathlib.Path(command_variation).exists(): return command_variation else: executable_path = pathlib.Path(process.cwd()) / command_variation if executable_path.exists(): return command_variation raise RuntimeError( f'can not parse the command line, maybe the executable not present anymore: "{l_command_variations[0]}"' )
def get_quoted_command(s_command: Union[str, pathlib.Path], process: psutil.Process) -> str: """ for the case the command executable contains blank, it would be interpreted as parameter >>> if lib_platform.is_platform_linux: ... import importlib ... import importlib.util ... import getpass ... save_actual_directory = str(pathlib.Path().cwd().absolute()) ... test_directory = lib_path.get_test_directory_path('lib_shell', test_directory_name='tests') ... # for travis we need to be owner - otherwise we get permission error ... lib_path.make_test_directory_and_subdirs_fully_accessible_by_current_user(test_directory) ... os.chdir(str(test_directory)) ... try: ... # test relative path with blank in command and parameters ... process = subprocess.Popen(['./test test/test test.sh', './test test/some_parameter', 'p1', 'p2']) ... psutil_process=psutil.Process(process.pid) ... expected = '"./test test/test test.sh" "./test test/some_parameter" p1 p2' ... assert get_quoted_command('./test test/test test.sh "./test test/some_parameter" p1 p2', psutil_process) == expected ... psutil_process.kill() ... # test relative path with blank in command, without parameters ... process = subprocess.Popen(['./test test/test test.sh']) ... psutil_process=psutil.Process(process.pid) ... expected = '"./test test/test test.sh"' ... assert get_quoted_command('./test test/test test.sh', psutil_process) == expected ... psutil_process.kill() ... # test relative path without blank in command, without parameters ... process = subprocess.Popen(['./test.sh']) ... psutil_process=psutil.Process(process.pid) ... assert get_quoted_command('./test.sh', psutil_process) == './test.sh' ... psutil_process.kill() ... # test absolute path with blank in command and parameters ... absolute_exec_path = str(test_directory / 'test test/test test.sh') ... process = subprocess.Popen([str(test_directory / 'test test/test test.sh') , ' "./test test/some_parameter"', 'p1', 'p2']) ... psutil_process=psutil.Process(process.pid) ... expected = '/tests/test test/test test.sh" "./test test/some_parameter" p1 p2' ... assert get_quoted_command(absolute_exec_path + ' "./test test/some_parameter" p1 p2', psutil_process).endswith(expected) ... psutil_process.kill() ... # test absolute path with blank in command without parameters ... absolute_exec_path = str(test_directory / 'test test/test test.sh') ... process = subprocess.Popen([str(test_directory / 'test test/test test.sh')]) ... psutil_process=psutil.Process(process.pid) ... expected = '/tests/test test/test test.sh"' ... assert get_quoted_command(absolute_exec_path, psutil_process).endswith(expected) ... psutil_process.kill() ... # test absolute path without blank in command without parameters ... absolute_exec_path = str(test_directory / 'test.sh') ... process = subprocess.Popen([str(test_directory / 'test.sh')]) ... psutil_process=psutil.Process(process.pid) ... expected = '/tests/test.sh' ... assert get_quoted_command(absolute_exec_path, psutil_process).endswith(expected) ... psutil_process.kill() ... # test absolute path without blank in command with parameters ... absolute_exec_path = str(test_directory / 'test.sh') + ' some parameter' ... process = subprocess.Popen([str(test_directory / 'test.sh'), 'some', 'parameter']) ... psutil_process=psutil.Process(process.pid) ... expected = '/tests/test.sh some parameter' ... assert get_quoted_command(absolute_exec_path, psutil_process).endswith(expected) ... psutil_process.kill() ... finally: ... os.chdir(save_actual_directory) """ s_command = str(s_command) if " " not in s_command: return s_command l_command_variations = get_l_command_variations(s_command) s_executable_file = get_executable_file(l_command_variations, process) s_parameters = s_command.split(s_executable_file, 1)[1] # if there is no blank in the executable, the lexer will work anyway - but might fail if blank in parameters if " " not in s_executable_file: return s_command # if s_command is just the executable with a blank in the absolute path if get_is_absolute_path(s_command): if pathlib.Path(s_command).exists(): return quote_string(s_command) # if s_command is just the executable with a blank in the relative path else: if (pathlib.Path(process.cwd()) / s_command).exists(): return quote_string(s_command) # return "executable with blanks" parameter1 parameter2 parameter3 quoted_command = quote_string(s_executable_file) + s_parameters return quoted_command