Python psutil.AccessDenied() Examples
The following are 30
code examples of psutil.AccessDenied().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
psutil
, or try the search function
.
Example #1
Source File: test_system.py From vnpy_crypto with MIT License | 7 votes |
def test_prcess_iter_w_params(self): for p in psutil.process_iter(attrs=['pid']): self.assertEqual(list(p.info.keys()), ['pid']) with self.assertRaises(ValueError): list(psutil.process_iter(attrs=['foo'])) with mock.patch("psutil._psplatform.Process.cpu_times", side_effect=psutil.AccessDenied(0, "")) as m: for p in psutil.process_iter(attrs=["pid", "cpu_times"]): self.assertIsNone(p.info['cpu_times']) self.assertGreaterEqual(p.info['pid'], 0) assert m.called with mock.patch("psutil._psplatform.Process.cpu_times", side_effect=psutil.AccessDenied(0, "")) as m: flag = object() for p in psutil.process_iter( attrs=["pid", "cpu_times"], ad_value=flag): self.assertIs(p.info['cpu_times'], flag) self.assertGreaterEqual(p.info['pid'], 0) assert m.called
Example #2
Source File: test_connections.py From psutil with BSD 3-Clause "New" or "Revised" License | 7 votes |
def compare_procsys_connections(self, pid, proc_cons, kind='all'): """Given a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. """ try: sys_cons = psutil.net_connections(kind=kind) except psutil.AccessDenied: # On MACOS, system-wide connections are retrieved by iterating # over all processes if MACOS: return else: raise # Filter for this proc PID and exlucde PIDs from the tuple. sys_cons = [c[:-1] for c in sys_cons if c.pid == pid] sys_cons.sort() proc_cons.sort() self.assertEqual(proc_cons, sys_cons)
Example #3
Source File: test_windows.py From vnpy_crypto with MIT License | 6 votes |
def wrap_exceptions(fun): def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: from psutil._pswindows import ACCESS_DENIED_SET if err.errno in ACCESS_DENIED_SET: raise psutil.AccessDenied(None, None) if err.errno == errno.ESRCH: raise psutil.NoSuchProcess(None, None) raise return wrapper # =================================================================== # System APIs # ===================================================================
Example #4
Source File: new_process.py From clusterfuzz with Apache License 2.0 | 6 votes |
def kill_process_tree(root_pid): """Kill process tree.""" try: parent = psutil.Process(root_pid) children = parent.children(recursive=True) except (psutil.AccessDenied, psutil.NoSuchProcess, OSError): logs.log_warn('Failed to find or access process.') return for child in children: try: child.kill() except (psutil.AccessDenied, psutil.NoSuchProcess, OSError): logs.log_warn('Failed to kill process child.') try: parent.kill() except (psutil.AccessDenied, psutil.NoSuchProcess, OSError): logs.log_warn('Failed to kill process.')
Example #5
Source File: linux.py From bitmask-dev with GNU General Public License v3.0 | 6 votes |
def _maybe_get_running_openvpn(): """ Looks for previously running openvpn instances. :rtype: psutil Process """ openvpn = None for p in psutil.process_iter(): try: # This needs more work, see #3268, but for the moment # we need to be able to filter out arguments in the form # --openvpn-foo, since otherwise we are shooting ourselves # in the feet. cmdline = p.cmdline() if any(map(lambda s: s.find( "LEAPOPENVPN") != -1, cmdline)): openvpn = p break except psutil.AccessDenied: pass return openvpn
Example #6
Source File: utils.py From clusterfuzz with Apache License 2.0 | 6 votes |
def get_process_ids(process_id, recursive=True): """Return list of pids for a process and its descendants.""" # Try to find the running process. if not psutil.pid_exists(process_id): return [] pids = [process_id] try: psutil_handle = psutil.Process(process_id) children = psutil_handle.children(recursive=recursive) for child in children: pids.append(child.pid) except psutil.NoSuchProcess: # Avoid too much logging when the process already died. return [] except (psutil.AccessDenied, OSError): logs.log_warn('Failed to get process children.') return [] return pids
Example #7
Source File: test_linux.py From vnpy_crypto with MIT License | 6 votes |
def test_exe_mocked(self): with mock.patch('psutil._pslinux.readlink', side_effect=OSError(errno.ENOENT, "")) as m1: with mock.patch('psutil.Process.cmdline', side_effect=psutil.AccessDenied(0, "")) as m2: # No such file error; might be raised also if /proc/pid/exe # path actually exists for system processes with low pids # (about 0-20). In this case psutil is supposed to return # an empty string. ret = psutil.Process().exe() assert m1.called assert m2.called self.assertEqual(ret, "") # ...but if /proc/pid no longer exist we're supposed to treat # it as an alias for zombie process with mock.patch('psutil._pslinux.os.path.lexists', return_value=False): self.assertRaises( psutil.ZombieProcess, psutil.Process().exe)
Example #8
Source File: utils.py From mars with Apache License 2.0 | 6 votes |
def get_next_port(typ=None): import psutil try: conns = psutil.net_connections() typ = typ or socket.SOCK_STREAM occupied = set(sc.laddr.port for sc in conns if sc.type == typ and LOW_PORT_BOUND <= sc.laddr.port <= HIGH_PORT_BOUND) except psutil.AccessDenied: occupied = _get_ports_from_netstat() occupied.update(_local_occupied_ports) randn = struct.unpack('<Q', os.urandom(8))[0] idx = int(randn % (1 + HIGH_PORT_BOUND - LOW_PORT_BOUND - len(occupied))) for i in range(LOW_PORT_BOUND, HIGH_PORT_BOUND + 1): if i in occupied: continue if idx == 0: _local_occupied_ports.add(i) return i idx -= 1 raise SystemError('No ports available.')
Example #9
Source File: test_linux.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_exe_mocked(self): with mock.patch('psutil._pslinux.readlink', side_effect=OSError(errno.ENOENT, "")) as m1: with mock.patch('psutil.Process.cmdline', side_effect=psutil.AccessDenied(0, "")) as m2: # No such file error; might be raised also if /proc/pid/exe # path actually exists for system processes with low pids # (about 0-20). In this case psutil is supposed to return # an empty string. ret = psutil.Process().exe() assert m1.called assert m2.called self.assertEqual(ret, "") # ...but if /proc/pid no longer exist we're supposed to treat # it as an alias for zombie process with mock.patch('psutil._pslinux.os.path.lexists', return_value=False): self.assertRaises( psutil.ZombieProcess, psutil.Process().exe)
Example #10
Source File: process_handler.py From clusterfuzz with Apache License 2.0 | 6 votes |
def get_runtime_snapshot(): """Return a list of current processes and their command lines as string.""" process_strings = [] for process in psutil.process_iter(): try: process_info = process.as_dict(attrs=['name', 'cmdline', 'pid', 'ppid']) process_string = '{name} ({pid}, {ppid})'.format( name=process_info['name'], pid=process_info['pid'], ppid=process_info['ppid']) process_cmd_line = process_info['cmdline'] if process_cmd_line: process_string += ': {cmd_line}'.format( cmd_line=(' '.join(process_cmd_line))) process_strings.append(process_string) except (psutil.AccessDenied, psutil.NoSuchProcess, OSError): # Ignore the error, use whatever info is available for access. pass return '\n'.join(sorted(process_strings))
Example #11
Source File: test_misc.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_ad_on_process_creation(self): # We are supposed to be able to instantiate Process also in case # of zombie processes or access denied. with mock.patch.object(psutil.Process, 'create_time', side_effect=psutil.AccessDenied) as meth: psutil.Process() assert meth.called with mock.patch.object(psutil.Process, 'create_time', side_effect=psutil.ZombieProcess(1)) as meth: psutil.Process() assert meth.called with mock.patch.object(psutil.Process, 'create_time', side_effect=ValueError) as meth: with self.assertRaises(ValueError): psutil.Process() assert meth.called
Example #12
Source File: test_misc.py From vnpy_crypto with MIT License | 6 votes |
def test_ad_on_process_creation(self): # We are supposed to be able to instantiate Process also in case # of zombie processes or access denied. with mock.patch.object(psutil.Process, 'create_time', side_effect=psutil.AccessDenied) as meth: psutil.Process() assert meth.called with mock.patch.object(psutil.Process, 'create_time', side_effect=psutil.ZombieProcess(1)) as meth: psutil.Process() assert meth.called with mock.patch.object(psutil.Process, 'create_time', side_effect=ValueError) as meth: with self.assertRaises(ValueError): psutil.Process() assert meth.called
Example #13
Source File: test_process.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_num_threads(self): # on certain platforms such as Linux we might test for exact # thread number, since we always have with 1 thread per process, # but this does not apply across all platforms (MACOS, Windows) p = psutil.Process() if OPENBSD: try: step1 = p.num_threads() except psutil.AccessDenied: raise unittest.SkipTest("on OpenBSD this requires root access") else: step1 = p.num_threads() with ThreadTask(): step2 = p.num_threads() self.assertEqual(step2, step1 + 1)
Example #14
Source File: test_process.py From vnpy_crypto with MIT License | 6 votes |
def test_threads(self): p = psutil.Process() if OPENBSD: try: step1 = p.threads() except psutil.AccessDenied: raise unittest.SkipTest("on OpenBSD this requires root access") else: step1 = p.threads() with ThreadTask(): step2 = p.threads() self.assertEqual(len(step2), len(step1) + 1) # on Linux, first thread id is supposed to be this process if LINUX: self.assertEqual(step2[0].id, os.getpid()) athread = step2[0] # test named tuple self.assertEqual(athread.id, athread[0]) self.assertEqual(athread.user_time, athread[1]) self.assertEqual(athread.system_time, athread[2])
Example #15
Source File: test_windows.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_special_pid(self): p = psutil.Process(4) self.assertEqual(p.name(), 'System') # use __str__ to access all common Process properties to check # that nothing strange happens str(p) p.username() self.assertTrue(p.create_time() >= 0.0) try: rss, vms = p.memory_info()[:2] except psutil.AccessDenied: # expected on Windows Vista and Windows 7 if not platform.uname()[1] in ('vista', 'win-7', 'win7'): raise else: self.assertTrue(rss > 0)
Example #16
Source File: test_process.py From vnpy_crypto with MIT License | 6 votes |
def test_children_duplicates(self): # find the process which has the highest number of children table = collections.defaultdict(int) for p in psutil.process_iter(): try: table[p.ppid()] += 1 except psutil.Error: pass # this is the one, now let's make sure there are no duplicates pid = sorted(table.items(), key=lambda x: x[1])[-1][0] p = psutil.Process(pid) try: c = p.children(recursive=True) except psutil.AccessDenied: # windows pass else: self.assertEqual(len(c), len(set(c)))
Example #17
Source File: test_system.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_prcess_iter_w_attrs(self): for p in psutil.process_iter(attrs=['pid']): self.assertEqual(list(p.info.keys()), ['pid']) with self.assertRaises(ValueError): list(psutil.process_iter(attrs=['foo'])) with mock.patch("psutil._psplatform.Process.cpu_times", side_effect=psutil.AccessDenied(0, "")) as m: for p in psutil.process_iter(attrs=["pid", "cpu_times"]): self.assertIsNone(p.info['cpu_times']) self.assertGreaterEqual(p.info['pid'], 0) assert m.called with mock.patch("psutil._psplatform.Process.cpu_times", side_effect=psutil.AccessDenied(0, "")) as m: flag = object() for p in psutil.process_iter( attrs=["pid", "cpu_times"], ad_value=flag): self.assertIs(p.info['cpu_times'], flag) self.assertGreaterEqual(p.info['pid'], 0) assert m.called
Example #18
Source File: test_system.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_process_iter(self): self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()]) sproc = self.spawn_testproc() self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()]) p = psutil.Process(sproc.pid) p.kill() p.wait() self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()]) with mock.patch('psutil.Process', side_effect=psutil.NoSuchProcess(os.getpid())): self.assertEqual(list(psutil.process_iter()), []) with mock.patch('psutil.Process', side_effect=psutil.AccessDenied(os.getpid())): with self.assertRaises(psutil.AccessDenied): list(psutil.process_iter())
Example #19
Source File: test_connections.py From vnpy_crypto with MIT License | 6 votes |
def compare_procsys_connections(self, pid, proc_cons, kind='all'): """Given a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. """ try: sys_cons = psutil.net_connections(kind=kind) except psutil.AccessDenied: # On OSX, system-wide connections are retrieved by iterating # over all processes if OSX: return else: raise # Filter for this proc PID and exlucde PIDs from the tuple. sys_cons = [c[:-1] for c in sys_cons if c.pid == pid] sys_cons.sort() proc_cons.sort() self.assertEqual(proc_cons, sys_cons) # ===================================================================== # --- Test unconnected sockets # =====================================================================
Example #20
Source File: test_system.py From vnpy_crypto with MIT License | 6 votes |
def test_process_iter(self): self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()]) sproc = get_test_subprocess() self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()]) p = psutil.Process(sproc.pid) p.kill() p.wait() self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()]) with mock.patch('psutil.Process', side_effect=psutil.NoSuchProcess(os.getpid())): self.assertEqual(list(psutil.process_iter()), []) with mock.patch('psutil.Process', side_effect=psutil.AccessDenied(os.getpid())): with self.assertRaises(psutil.AccessDenied): list(psutil.process_iter())
Example #21
Source File: test_windows.py From vnpy_crypto with MIT License | 6 votes |
def test_special_pid(self): p = psutil.Process(4) self.assertEqual(p.name(), 'System') # use __str__ to access all common Process properties to check # that nothing strange happens str(p) p.username() self.assertTrue(p.create_time() >= 0.0) try: rss, vms = p.memory_info()[:2] except psutil.AccessDenied: # expected on Windows Vista and Windows 7 if not platform.uname()[1] in ('vista', 'win-7', 'win7'): raise else: self.assertTrue(rss > 0)
Example #22
Source File: test_process.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_threads(self): p = psutil.Process() if OPENBSD: try: step1 = p.threads() except psutil.AccessDenied: raise unittest.SkipTest("on OpenBSD this requires root access") else: step1 = p.threads() with ThreadTask(): step2 = p.threads() self.assertEqual(len(step2), len(step1) + 1) athread = step2[0] # test named tuple self.assertEqual(athread.id, athread[0]) self.assertEqual(athread.user_time, athread[1]) self.assertEqual(athread.system_time, athread[2])
Example #23
Source File: test_process.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_halfway_terminated_process(self): # Test that NoSuchProcess exception gets raised in case the # process dies after we create the Process object. # Example: # >>> proc = Process(1234) # >>> time.sleep(2) # time-consuming task, process dies in meantime # >>> proc.name() # Refers to Issue #15 def assert_raises_nsp(fun, fun_name): try: ret = fun() except psutil.ZombieProcess: # differentiate from NSP raise except psutil.NoSuchProcess: pass except psutil.AccessDenied: if OPENBSD and fun_name in ('threads', 'num_threads'): return raise else: # NtQuerySystemInformation succeeds even if process is gone. if WINDOWS and fun_name in ('exe', 'name'): return raise self.fail("%r didn't raise NSP and returned %r " "instead" % (fun, ret)) p = self.spawn_psproc() p.terminate() p.wait() if WINDOWS: # XXX call_until(psutil.pids, "%s not in ret" % p.pid) self.assertProcessGone(p) ns = process_namespace(p) for fun, name in ns.iter(ns.all): assert_raises_nsp(fun, name) # NtQuerySystemInformation succeeds even if process is gone. if WINDOWS and not GITHUB_WHEELS: normcase = os.path.normcase self.assertEqual(normcase(p.exe()), normcase(PYTHON_EXE))
Example #24
Source File: test_process.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_threads_2(self): p = self.spawn_psproc() if OPENBSD: try: p.threads() except psutil.AccessDenied: raise unittest.SkipTest( "on OpenBSD this requires root access") self.assertAlmostEqual( p.cpu_times().user, sum([x.user_time for x in p.threads()]), delta=0.1) self.assertAlmostEqual( p.cpu_times().system, sum([x.system_time for x in p.threads()]), delta=0.1)
Example #25
Source File: test_misc.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def assert_stdout(exe, *args, **kwargs): exe = '%s' % os.path.join(SCRIPTS_DIR, exe) cmd = [PYTHON_EXE, exe] for arg in args: cmd.append(arg) try: out = sh(cmd, **kwargs).strip() except RuntimeError as err: if 'AccessDenied' in str(err): return str(err) else: raise assert out, out return out
Example #26
Source File: test_misc.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_access_denied__repr__(self, func=repr): self.assertEqual( repr(psutil.AccessDenied(321)), "psutil.AccessDenied (pid=321)") self.assertEqual( repr(psutil.AccessDenied(321, name='foo')), "psutil.AccessDenied (pid=321, name='foo')") self.assertEqual( repr(psutil.AccessDenied(321, msg='foo')), "psutil.AccessDenied foo")
Example #27
Source File: test_process.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_ionice_win(self): p = psutil.Process() if not CI_TESTING: self.assertEqual(p.ionice(), psutil.IOPRIO_NORMAL) init = p.ionice() try: # base p.ionice(psutil.IOPRIO_VERYLOW) self.assertEqual(p.ionice(), psutil.IOPRIO_VERYLOW) p.ionice(psutil.IOPRIO_LOW) self.assertEqual(p.ionice(), psutil.IOPRIO_LOW) try: p.ionice(psutil.IOPRIO_HIGH) except psutil.AccessDenied: pass else: self.assertEqual(p.ionice(), psutil.IOPRIO_HIGH) # errs self.assertRaisesRegex( TypeError, "value argument not accepted on Windows", p.ionice, psutil.IOPRIO_NORMAL, value=1) self.assertRaisesRegex( ValueError, "is not a valid priority", p.ionice, psutil.IOPRIO_HIGH + 1) finally: p.ionice(init)
Example #28
Source File: test_process.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_send_signal_mocked(self): sig = signal.SIGTERM p = self.spawn_psproc() with mock.patch('psutil.os.kill', side_effect=OSError(errno.ESRCH, "")): self.assertRaises(psutil.NoSuchProcess, p.send_signal, sig) p = self.spawn_psproc() with mock.patch('psutil.os.kill', side_effect=OSError(errno.EPERM, "")): self.assertRaises(psutil.AccessDenied, p.send_signal, sig)
Example #29
Source File: test_process.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_zombie_process(self): def succeed_or_zombie_p_exc(fun): try: return fun() except (psutil.ZombieProcess, psutil.AccessDenied): pass parent, zombie = self.spawn_zombie() # A zombie process should always be instantiable zproc = psutil.Process(zombie.pid) # ...and at least its status always be querable self.assertEqual(zproc.status(), psutil.STATUS_ZOMBIE) # ...and it should be considered 'running' assert zproc.is_running() # ...and as_dict() shouldn't crash zproc.as_dict() # ...its parent should 'see' it (edit: not true on BSD and MACOS # descendants = [x.pid for x in psutil.Process().children( # recursive=True)] # self.assertIn(zpid, descendants) # XXX should we also assume ppid be usable? Note: this # would be an important use case as the only way to get # rid of a zombie is to kill its parent. # self.assertEqual(zpid.ppid(), os.getpid()) # ...and all other APIs should be able to deal with it ns = process_namespace(zproc) for fun, name in ns.iter(ns.all): succeed_or_zombie_p_exc(fun) assert psutil.pid_exists(zproc.pid) if not TRAVIS and MACOS: # For some reason this started failing all of the sudden. # Maybe they upgraded MACOS version? # https://travis-ci.org/giampaolo/psutil/jobs/310896404 self.assertIn(zproc.pid, psutil.pids()) self.assertIn(zproc.pid, [x.pid for x in psutil.process_iter()]) psutil._pmap = {} self.assertIn(zproc.pid, [x.pid for x in psutil.process_iter()])
Example #30
Source File: device_recovery.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def KillAllAdb(): def get_all_adb(): for p in psutil.process_iter(): try: # Note: p.as_dict is compatible with both older (v1 and under) as well # as newer (v2 and over) versions of psutil. # See: http://grodola.blogspot.com/2014/01/psutil-20-porting.html pinfo = p.as_dict(attrs=['pid', 'name', 'cmdline']) if pinfo['name'] == 'adb': pinfo['cmdline'] = ' '.join(pinfo['cmdline']) yield p, pinfo except (psutil.NoSuchProcess, psutil.AccessDenied): pass for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL]: for p, pinfo in get_all_adb(): try: pinfo['signal'] = sig logger.info('kill %(signal)s %(pid)s (%(name)s [%(cmdline)s])', pinfo) p.send_signal(sig) except (psutil.NoSuchProcess, psutil.AccessDenied): pass for _, pinfo in get_all_adb(): try: logger.error('Unable to kill %(pid)s (%(name)s [%(cmdline)s])', pinfo) except (psutil.NoSuchProcess, psutil.AccessDenied): pass