def get_terminal_emulator_name(): shell_pid = os.getppid() term_em = "unknown" try: #get the parent of the shell term_em_pid = sh.ps('-o', 'ppid=', '-p', shell_pid).strip() term_em_name = sh.ps('-o', 'comm=', '-p', term_em_pid) term_em = term_em_name.strip() except Exception: term_em = "unknown" return term_em
def process(h, data_dir, warcs_dir): done_path = os.path.join(data_dir, 'archived.txt') done = load_list(done_path) current_path = os.path.join(data_dir, 'current.txt') with FileLock(current_path): current = load_list(current_path, need_lock=False) job, repo_path = find_job(data_dir, done, current) if job is not None: current.add(job) save_list(current_path, current, need_lock=False) logger = logging.getLogger('archive-%s' % job) hdlr = logging.FileHandler('archive-%s.log' % job) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) if None not in [job, repo_path]: try: process_repo(h, repo_path, job, warcs_dir) done.add(job) save_list(done_path, done) except: logger.error('Error occurred') logger.error(traceback.format_exc()) o = sh.ps(o='ppid') assert '\n%d\n' % os.getpid() not in o logger.info('All done')
def check(self): running = False self.status = self.ERROR try: if self.pidfile: with open(self.pidfile) as f: pidfile_pid = f.read() pidfile_pid = pidfile_pid.strip() self.metrics += (('pidfile_pid', pidfile_pid, 'int32'), ) else: pidfile_pid = None except Exception as e: return self.error('Could not read pidfile: %s' % e) for line in sh.ps('auwx', _tty_out=False): [user, pid, cpu, mem, vsz, rss, tt, stat, started, time, cmd] = line.split()[:11] if cmd.startswith(self.name) or re.search(r'/%s\b' % self.name, cmd): running = True self.metrics += ( ('user', user, 'string'), ('pid', pid, 'uint32'), ('cpu', cpu, 'double'), ('memory', mem, 'double'), ('vsize', vsz, 'uint64'), ('rsize', rss, 'uint64'), ('command', cmd, 'string'), ) break if running: self.status = self.OK else: self.metrics += (('pid', 0, 'uint32'), )
def is_pid_of_suites_runner(pid): try: os.kill(int(pid), 0) except (ValueError, OSError): return False try: cmd = sh.ps('h', p=str(pid), o='cmd').stdout.strip() return 'suites_runner' in cmd except sh.ErrorReturnCode: return False
def getProcessInformation(self): lista=ps("-aux").split("\n") # print lista; data=[] for kolumna in lista[1:-1]: kolumna=kolumna.split() data.append([kolumna[10],kolumna[0],float(kolumna[2]),float(kolumna[3]),int(kolumna[1])]) print kolumna[10],kolumna[0],kolumna[2],kolumna[3],kolumna[1] return data
def check_if_running_polkit_auth(): """ check if polkit authentication agent is running and launch it if it is not """ try: grep(ps('aux'), '[p]olkit-gnome-authentication-agent-1') except sh.ErrorReturnCode_1: logger.debug('polkit auth agent not found, trying to launch it...') run_polkit_auth_agent()
def focus_changed(screen, prev_window): win = screen.get_active_window() if not win: return global chrome_registered process_cmd = ps('-p', win.get_pid(), '-o', 'cmd', 'h').strip() print win.get_name() if not chrome_registered and process_cmd.split()[0].split('/')[-1] == "google-chrome": win.connect("name-changed", chrome_tab_changed) chrome_registered = True
def KillProcess(): try: pid = sh.pgrep(sh.ps("aux"), 'minergate-cli') for a in pid.split('\n'): if a != '': os.kill(int(a), signal.SIGKILL) return True except: return False
def evaluate_mem(_pid, logfile): """ Use the ps command for profiling memory for now. """ print "Start benchmarking the RSS memory usage, result will be in " + logfile with open(logfile, "w") as wf: while 1: info = sh.awk(sh.tr(sh.ps("aux"), "-s", "' '"), "-vpid={}".format(_pid), "{if ($2==pid) {print $6}}").strip() wf.write("{:<12s}: {:10s}\n".format(str(datetime.datetime.now()), info)) wf.flush() # FIXME: ugly solution here time.sleep(1)
def get_memory_usage(): memory_usage = 'NA' # for Windows syste returns 'NA' if platform.system() == 'Linux': #if not hasattr(sys, 'getwindowsversion'): # For Linux, Not for windoes OS import sh memory_usage = float(sh.awk(sh.ps('u','-p',os.getpid()),'{sum=sum+$6}; END {print sum/1024}')) # MB #print ( 'PLATFORM: ', platform.system() , memory_usage) return memory_usage
def focus_changed(screen, prev_window): global registered_windows window = screen.get_active_window() if not window: return process_cmd = ps('-p', window.get_pid(), '-o', 'cmd', 'h').strip() monitor(process_cmd, window.get_name()) if window not in registered_windows: #and process_cmd.split()[0].split('/')[-1] == "google-chrome": window.connect("name-changed", window_name_changed) registered_windows.add(window)
def get_cmd_from_ps(needle): result = sh.grep(sh.cat(sh.ps('-wwaeopid,cmd')), needle) if result.exit_code == 0: for line in result.stdout.split('\n'): line = line.strip() if not line: continue match = re.search(r'^(\d*)\s*(.*)', line) if match.group(2).startswith('grep'): continue return match.group(2) raise KeyError('Failed to find: %s' % needle)
def monitor_publisher_size(): #ps aux | grep publish | awk '{print $6}' from sh import ps, grep, pkill try: psinfo = grep(ps('aux'), 'publish') mem_used = int(psinfo.strip().split()[5]) print 'mem_publish:', mem_used if mem_used >= 1 * 1024 * 1024: #(1G = 1*1024*1024K) pkill('-f', 'publish.py') except Exception: import traceback traceback.print_exc()
def run(self): while True: #tableData1=self.data.getProcessInformation() lista=ps("-aux").split("\n") data=[] for kolumna in lista[1:-1]: kolumna=kolumna.split() data.append([kolumna[10],kolumna[0],float(kolumna[2]),float(kolumna[3]),int(kolumna[1])]) self.signalUpdateProcess.emit(data) #self.data._model.update(tableData1) time.sleep(1)
def find_process_pid(process_line, child_process=False): ps_opts = 'auxww' if not child_process else 'auxfww' try: pid = sh.awk( sh.grep( sh.grep(sh.ps(ps_opts, _piped=True, _tty_out=False), "-ie", process_line), '-v', 'grep'), "{print $2}", ) except sh.ErrorReturnCode: raise AssertionError("Cannot find process pid") return pid.strip()
def main(): if len(sys.argv) < 2: log.info('查看进程 ps -u %s'%getuser()) print ps('-u', getuser()) else: id = sys.argv[1] if not findId(id): log.warn('进程 [ %s ] 不存在'%id) return for i in [15, 2, 1]: if findId(id): log.info('进程 [ %s ] 存在,关闭 %d ...'%(id, i)) killId(id, i) log.info('等待检查关闭结果') time.sleep(3) else: log.info('进程关闭成功.') return if findId(id): log.error('关闭失败,尝试使用kill -9 %s'%id) else: log.info('使用kill 1 成功.')
def _process_exists(pid): """ Checks whether a given PID exists in the system Parameters ---------- pid: `int` The PID to check for Returns ------- True if a process with the provided `pid` exists in the system. False Otherwise """ try: sh.ps(['-h', '-p', pid]) except Exception: # sh.raises an Exception if the command doesn't return 0 return False return True
def main(): if len(sys.argv) < 2: log.info('查看进程 ps -u %s' % getuser()) print ps('-u', getuser()) else: id = sys.argv[1] if not findId(id): log.warn('进程 [ %s ] 不存在' % id) return for i in [15, 2, 1]: if findId(id): log.info('进程 [ %s ] 存在,关闭 %d ...' % (id, i)) killId(id, i) log.info('等待检查关闭结果') time.sleep(3) else: log.info('进程关闭成功.') return if findId(id): log.error('关闭失败,尝试使用kill -9 %s' % id) else: log.info('使用kill 1 成功.')
def GetHotwordPID(): # logger.info (sh.glob("*")) # logger.info(sh.sort(sh.du(sh.glob("*"), "-sb"), "-rn")) # logger.info(sh.grep(sh.grep(sh.ps("-aux"), "python"), "hotword")) # logger.info(sh.grep(sh.grep(sh.ps("-aux"), "python")), "hotword") out = sh.grep(sh.ps("-aux"), "python") # logger.info ("***out***:\r\n", out, "*******") # logger.info (type(out)) match = re.findall(b'[^\s]+\s+(\d+).+hotword.py', out.stdout, re.MULTILINE) # pprint.pprint(match) for item in match: plogger.info.plogger.info(item) return int(item.decode("utf-8"))
def _command(cmd=''): if cmd == 'df': result = df('-h') elif cmd == 'ps': result = ps('-ef', _tty_out=False) elif cmd == 'ifconfig': result = ifconfig() elif cmd == 'hostinfo': result = hostinfo() elif cmd == 'sw_vers': result = sw_vers() else: redirect('/') return template(TEXTPAGE, title=cmd.upper(), text=result)
def _stop_bot(self, param): action_result = self.add_action_result(phantom.ActionResult(dict(param))) pid = self._state.get('pid', '') if pid: self._state.pop('pid') try: if 'slack_bot.pyc' in sh.ps('ww', pid): # pylint: disable=E1101 sh.kill(pid) # pylint: disable=E1101 action_result.set_status(phantom.APP_SUCCESS, "SlackBot has been stopped.") except: action_result.set_status(phantom.APP_SUCCESS, "SlackBot isn't running, not going to stop it.") else: action_result.set_status(phantom.APP_SUCCESS, "SlackBot isn't running, not going to stop it.") rest_url = consts.SLACK_PHANTOM_ASSET_INFO_URL.format(url=self.get_phantom_base_url(), asset_id=self.get_asset_id()) ret_val, resp_json = self._make_rest_call(action_result, rest_url, False) if phantom.is_fail(ret_val): return ret_val asset_config = resp_json.get('configuration', {}) ingest_config = asset_config.get('ingest', {}) poll = ingest_config.get('poll') if poll is None: return action_result.set_status(phantom.APP_SUCCESS, "{} Failed to disable ingestion, please check that ingest settings are correct." .format(action_result.get_message())) if not poll: return action_result.set_status(phantom.APP_SUCCESS, "{} Ingestion isn't enabled, not going to disable it.".format(action_result.get_message())) ingest_config['poll'] = False body = {'configuration': asset_config} ret_val, resp_json = self._make_rest_call(action_result, rest_url, False, method=requests.post, body=body) if phantom.is_fail(ret_val): return ret_val return action_result.set_status(phantom.APP_SUCCESS, "{} Ingestion has been disabled.".format(action_result.get_message()))
def getProcessInformation(self): lista = ps("-aux").split("\n") # print lista; data = [] for kolumna in lista[1:-1]: kolumna = kolumna.split() data.append([ kolumna[10], kolumna[0], float(kolumna[2]), float(kolumna[3]), int(kolumna[1]) ]) print kolumna[10], kolumna[0], kolumna[2], kolumna[3], kolumna[1] return data
def run(self): while True: #tableData1=self.data.getProcessInformation() lista = ps("-aux").split("\n") data = [] for kolumna in lista[1:-1]: kolumna = kolumna.split() data.append([ kolumna[10], kolumna[0], float(kolumna[2]), float(kolumna[3]), int(kolumna[1]) ]) self.signalUpdateProcess.emit(data) #self.data._model.update(tableData1) time.sleep(1)
def kill(self): # # this is not working, as we do not jet use subprocess # if self.data['pid'] is not None: self.data['pid'].terminate() self.data['pid'] = None # # TODO: this is not a good way to kill, as it apears that we only read 80 chars for each line in ps # result = sh.ps("-o", "pid,command", _tty_in=False, _tty_out=False) for line in result.split("\n"): if "notebook" in line and "ipython" in line: attributes = line.strip().split(' ') pid = attributes[0] print("TERMINATING", pid) sh.kill("-9", pid)
def dhclient(iface, enable, script=None): # Disable the dhcp client and flush interface try: dhclients = sh.awk( sh.grep(sh.grep(sh.ps("ax"), iface, _timeout=5), "dhclient", _timeout=5), "{print $1}") dhclients = dhclients.split() for dhclient in dhclients: sh.kill(dhclient) except Exception as e: _logger.info("Failed to stop dhclient: %s" % e) pass if enable: if script: sh.dhclient("-nw", "-sf", script, iface, _bg=True) else: sh.dhclient("-nw", iface, _bg=True)
def is_up(self): ''' Test if the proxy is running. ''' import sh from syr.process import pid_from_port, program_from_pid up = False try: program_running = False port_listening = False for line in sh.ps('ax', columns=1000, _iter=True): if self.program in line: program_running = True if program_running: # if anyone is listening on self.port self.pid = pid_from_port(self.port) if self.pid: self.listening_program = program_from_pid(self.pid) port_listening = True else: self.namespace.log.debug( 'program not listening: {}'. format(self)) else: self.namespace.log.debug('program not running: {}'.format(self.program)) up = program_running and port_listening #if not up: #DEBUG # self.namespace.log.debug(stacktrace()) #DEBUG except: self.namespace.log.debug(traceback.format_exc()) up = False return up
def dhclient(iface, enable, script=None): # Disable the dhcp client and flush interface try: dhclients = sh.awk( sh.grep( sh.grep(sh.ps("ax"), iface, _timeout=5), "dhclient", _timeout=5), "{print $1}") dhclients = dhclients.split() for dhclient in dhclients: sh.kill(dhclient) except Exception as e: _logger.info("Failed to stop dhclient: %s" % e) pass if enable: if script: sh.dhclient("-nw", "-sf", script, iface, _bg=True) else: sh.dhclient("-nw", iface, _bg=True)
def get_nvidia_stats(): ctext = nvsmi() _, pblock, ublock = ctext.split('|==') pblock = pblock.split('\n')[2::3] percs = [percre.findall(pb)[-1] for pb in pblock if pb.startswith('|')] percs = [int(p[:-1]) for p in percs] ublock = ublock.split('+--')[0].split('\n')[1:-1] pids = [u.split()[1:3] for u in ublock if not ('No running' in u)] gids, pids = zip(*pids) if len(pids) > 0 else ([], []) uids = [sh.ps('u', pid).split('\n')[1].split()[0] for pid in pids] free_gpus = list(set(range(len(percs))) - set(range(len(uids)))) entries = [] for gid, pid, uid in zip(gids, pids, uids): perc = percs[int(gid)] entries.append(dict(gid=gid, pid=pid, uid=uid, perc=perc)) return free_gpus, entries
#!/usr/bin/env python # -*- coding: utf-8 -*- import sh,os,sys try: sh.grep(sh.grep(sh.ps('ux'),'sslocal'),v='grep') except Exception, e: os.system("sslocal -c $HOME/.outwall/sslocal_config.json &") finally: command_string=' '.join(sys.argv[1:]) print command_string os.system("$HOME/.outwall/proxychains-4.8.1/proxychains4 -f $HOME/.outwall/proxychains.conf "+command_string )
def check_scrapyd(): if 'scrapyd' not in sh.ps('cax'): raise RuntimeError('scrapyd not running')
def is_program_running(search_string): ''' Return whether a program is running. WARNING: Unreliable, apparently dependent on characters in search_string >>> is_program_running('nginx') True >>> is_program_running('not.running') False ''' def capture_output(line): output.append(line) if DEBUGGING: log.debug('is_program_running() searchstring: {}'.format(search_string)) try: output = [] psgrep_result = sh.psgrep(search_string) except sh.ErrorReturnCode as err: running = False except: running = False log.debug(format_exc()) else: if IS_PY2: stdout = psgrep_result.stdout else: stdout = psgrep_result.stdout.decode() running = ( (psgrep_result.exit_code == 0) and (stdout != '') and (search_string in stdout)) if not running: try: ps_result = sh.ps('-eo', 'pid,args', _out=capture_output) if IS_PY2: stdout = ps_result.stdout else: stdout = ps_result.stdout.decode() running = ( (ps_result.exit_code == 0) and (stdout != '') and (search_string in stdout)) if running: if DEBUGGING: log.debug('exit code: {}'.format(ps_result.exit_code)) #log.debug('stdout: {}'.format(ps_result.stdout)) else: running = search_string in output if not running and DEBUGGING: log.debug('output: {}'.format(output)) except: log.debug(format_exc()) else: pass if DEBUGGING: log.debug('{} is_program_running: {}'.format(search_string, running)) return running
## Step 4 ## Configure radvd to use that prefix print('Creating radvd.conf') with open(HOMEDIR+'/radvd.conf.in') as fin: conf = fin.read() confout = conf.replace('%PREFIX%', prefix) confout = confout.replace('%INTERFACE%', BORDERROUTER_INTERFACE) with open(HOMEDIR+'/radvd.conf', 'w') as fout: fout.write(confout) ## Step 5 ## Run the BorderRouter try: out = grep(ps('-A'), 'BorderRouterC') print('BorderRouter already running.') print('Killing BorderRouter...') sudo.pkill('-9', 'BorderRouterC') except Exception: pass print('Starting Border Router.') subprocess.call(["screen", "-d", "-m", "-S", "border-router", "sudo", HOMEDIR+"/BorderRouterC", '-i', BORDERROUTER_INTERFACE]) time.sleep(5) ## Step 6 ## Run radvd try: out = grep(ps('-A'), 'radvd') print('radvd is already running.')
def _on_poll(self, param): action_result = self.add_action_result(phantom.ActionResult(dict(param))) ret_val, resp_json = self._make_slack_rest_call(action_result, consts.SLACK_AUTH_TEST, {}) if not ret_val: return ret_val bot_id = resp_json.get('user_id') if not bot_id: return action_result.set_status(phantom.APP_ERROR, "Could not get bot ID from Slack") pid = self._state.get('pid', '') if pid: try: if 'slack_bot.pyc' in sh.ps('ww', pid): # pylint: disable=E1101 self.save_progress("Detected SlackBot running with pid {0}".format(pid)) return action_result.set_status(phantom.APP_SUCCESS, "SlackBot already running") except: pass config = self.get_config() bot_token = config.get('bot_token', '') ph_auth_token = config.get('ph_auth_token', None) if not ph_auth_token: return action_result.set_status(phantom.APP_ERROR, "The ph_auth_token asset configuration parameter is required to run the on_poll action.") app_version = self.get_app_json().get('app_version', '') try: ps_out = sh.grep(sh.ps('ww', 'aux'), 'slack_bot.pyc') # pylint: disable=E1101 if app_version not in ps_out: old_pid = shlex.split(str(ps_out))[1] self.save_progress("Found an old version of slackbot running with pid {}, going to kill it".format(old_pid)) sh.kill(old_pid) # pylint: disable=E1101 except: pass try: if bot_token in sh.grep(sh.ps('ww', 'aux'), 'slack_bot.pyc'): # pylint: disable=E1101 return action_result.set_status(phantom.APP_ERROR, "Detected an instance of SlackBot running with the same bot token. Not going to start new instance.") except: pass self.save_progress("Starting SlackBot") ret_val, base_url = self._get_phantom_base_url_slack(action_result) if phantom.is_fail(ret_val): return ret_val slack_bot_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'slack_bot.pyc') base_url += '/' if not base_url.endswith('/') else '' proc = subprocess.Popen(['phenv', 'python2.7', slack_bot_filename, bot_token, bot_id, base_url, app_version, ph_auth_token]) self._state['pid'] = proc.pid self.save_progress("Started SlackBot with pid: {0}".format(proc.pid)) return action_result.set_status(phantom.APP_SUCCESS, "SlackBot started")
def start_festival_server(): if "festival --server" not in ps(a=True): festival(server=True, _bg=True)
def get_pid(name): pid = sh.grep(sh.ps('ax'), name, _ok_code=range(3)) return pid and int(pid.split()[0])
#!/usr/bin/env python import sh a = sh.grep(sh.ps("afx"), 'bin/dpi-engine') if a == '': print('dpi proc is found') else: print('dpi not found')
of_date = "2017-05-29" bq_query = """ SELECT user_agent, ip, received_at, url FROM `{}.{}` WHERE _PARTITIONTIME = TIMESTAMP("{}") LIMIT 40000; """.format(project, bq_table, of_date) query_results = bq.run_sync_query(bq_query) query_results.use_legacy_sql = False print("bq running query.") print( float( sh.awk(sh.ps('u', '-p', os.getpid()), '{sum=sum+$6}; END {print sum/1024}'))) query_results.run() dataset_x = [] dataset_y = [] page_token = None print("bq query run.") while True: rows, total_rows, page_token = query_results.fetch_data( max_results=8000, page_token=page_token) print("bq fetched 8k rows.")
def window_name_changed(window): if Wnck.Screen.get_default().get_active_window() != window: return process_cmd = ps('-p', window.get_pid(), '-o', 'cmd', 'h').strip() monitor(process_cmd, window.get_name())
def ui_command_ps(self): return sh.ps("aux")
# encoding: utf-8 # from http://amoffat.github.io/sh/ from contextlib import contextmanager import sh from threading import Thread import time # ps aux | grep ssh | awk '{print $11}' print(sh.awk(sh.grep(sh.ps('aux'), 'ssh'), '{print $11}')) print(sh.grep(sh.docker.version(), 'Version:')) # most recent file print(sh.tail(sh.ls('-lrt'), '-n 1')) @contextmanager def parallel_delayed_run(callable, *args, **kwargs): delay = kwargs.get('delay', 0.5) def delayed_run(): time.sleep(delay) callable(*args) th = Thread(target=delayed_run) th.start() try: yield except sh.SignalException: print('Interrupted !') th.join()
def get_list_of_running_process(): process_name = sys.argv[1] list_of_process = sh.grep(sh.ps('-aux', _piped=True), '-v', 'python') return list_of_process
def get_list_of_pids_matching_regex(regex): process_lines = re.findall(regex, "\n".join(sh.ps("cax"))) return [int(line.split()[0]) for line in process_lines if len(line) > 0]
def findId(id): list = ps('-u', getuser()) for i in list.split('\n'): if i.strip().startswith(id + ' '): return True return False
def _ps(self): return sh.ps("-ax", _tty_out=False) # def __init__(self): # pass '''
if self.current_w: with self.window_list_lock: self.window_list[self.current_w] = line subprocess.run(["pkill", "-RTMIN+10", "i3blocks"]) def run(self): threads = [] threads.append(threading.Thread(target=self.launch_i3)) threads.append( threading.Thread(target=self.kb_watch_thread, daemon=True)) threads.append(threading.Thread(target=self.w_thread, daemon=True)) for t in threads: t.start() if __name__ == '__main__': res = sh.grep(sh.ps("aux", cols=1000), "--color=never", "i3_custom_ipc_server.py") for line in res.splitlines(): if "python3" in line and str(os.getpid()) not in line: print("I3 IPC server already running") sys.exit(1) try: sh.pkill("-f", "i3_custom_ipc_client.py") except sh.ErrorReturnCode: pass focus_watcher = FocusWatcher(len(sys.argv) > 1) focus_watcher.run()
def CheckProcess(): try: pid = sh.pgrep(sh.ps("aux"), 'minergate-cli') return True except: return False
time.sleep(1) ## Step 4 ## Configure radvd to use that prefix print('Creating radvd.conf') with open(HOMEDIR + '/radvd.conf.in') as fin: conf = fin.read() confout = conf.replace('%PREFIX%', prefix) confout = confout.replace('%INTERFACE%', BORDERROUTER_INTERFACE) with open(HOMEDIR + '/radvd.conf', 'w') as fout: fout.write(confout) ## Step 5 ## Run the BorderRouter try: out = grep(ps('-A'), 'BorderRouterC') print('BorderRouter already running.') print('Killing BorderRouter...') sudo.pkill('-9', 'BorderRouterC') except Exception: pass print('Starting Border Router.') subprocess.call([ "screen", "-d", "-m", "-S", "border-router", "sudo", HOMEDIR + "/BorderRouterC", '-i', BORDERROUTER_INTERFACE ]) time.sleep(5) ## Step 6 ## Run radvd
def print_mem_usage(): print( float( sh.awk(sh.ps('u', '-p', os.getpid()), '{sum=sum+$6}; END {print sum/1024}')), "mb") return
def xquartz_running() -> bool: for line in sh.ps("-x"): if "X11" in line: return True return False
import sh x = sh.ps() print(x)