本文整理汇总了Python中psutil.AccessDenied方法的典型用法代码示例。如果您正苦于以下问题:Python psutil.AccessDenied方法的具体用法?Python psutil.AccessDenied怎么用?Python psutil.AccessDenied使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类psutil
的用法示例。
在下文中一共展示了psutil.AccessDenied方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compare_procsys_connections
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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)
示例2: get_next_port
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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.')
示例3: _maybe_get_running_openvpn
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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
示例4: test_ad_on_process_creation
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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
示例5: test_threads
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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])
示例6: test_children_duplicates
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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)))
示例7: compare_procsys_connections
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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
# =====================================================================
示例8: test_process_iter
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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())
示例9: test_prcess_iter_w_params
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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
示例10: wrap_exceptions
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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
# ===================================================================
示例11: test_special_pid
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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)
示例12: test_exe_mocked
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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)
示例13: get_process_ids
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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
示例14: kill_process_tree
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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.')
示例15: get_runtime_snapshot
# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import AccessDenied [as 别名]
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))