예제 #1
0
 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
예제 #2
0
 def test_name_long_cmdline_ad_exc(self):
     # Same as above but emulates a case where cmdline() raises
     # AccessDenied in which case psutil is supposed to return
     # the truncated name instead of crashing.
     name = "long-program-name"
     with mock.patch("psutil._psplatform.Process.name", return_value=name):
         with mock.patch("psutil._psplatform.Process.cmdline",
                         side_effect=psutil.AccessDenied(0, "")):
             p = psutil.Process()
             self.assertEqual(p.name(), "long-program-name")
예제 #3
0
 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
예제 #4
0
 def wrapper(self, *args, **kwargs):
     try:
         return callable(self, *args, **kwargs)
     except OSError:
         err = sys.exc_info()[1]
         if err.errno in ACCESS_DENIED_SET:
             raise psutil.AccessDenied(None, None)
         if err.errno == errno.ESRCH:
             raise psutil.NoSuchProcess(None, None)
         raise
예제 #5
0
    def test_signal_stop(self, mock_send_signal):
        proc = PostmasterProcess(-123)
        self.assertEquals(proc.signal_stop('immediate'), False)

        mock_send_signal.side_effect = [
            None, psutil.NoSuchProcess(123),
            psutil.AccessDenied()
        ]
        proc = PostmasterProcess(123)
        self.assertEquals(proc.signal_stop('immediate'), None)
        self.assertEquals(proc.signal_stop('immediate'), True)
        self.assertEquals(proc.signal_stop('immediate'), False)
예제 #6
0
def systemInfo():
    print("cpu状态:" + str(psutil.cpu_stats()))
    print("cpu的逻辑个数:" + str(psutil.cpu_count()))
    print("cpu的物理数量:" + str(psutil.cpu_count(logical=False)))
    print("cpu的整个信息:" + str(psutil.cpu_times()))
    print("cpu的IDLE信息:" + str(psutil.cpu_times().idle))
    print("内存的完整信息:" + str(psutil.virtual_memory()))
    mem = psutil.virtual_memory()
    print("内存总数:" + str(mem.total))
    print("空闲的内存信息:" + str(mem.free))
    print("swap分区信息:" + str(psutil.swap_memory()))
    print("D盘利用率:" + str(psutil.disk_usage('D:/')))
    print("IO信息:" + str(psutil.disk_io_counters()))
    print("磁盘的完整信息:" + str(psutil.disk_partitions()))
    print("分区的状态:" + str(psutil.disk_usage("/")))
    print("硬盘IO总个数:" + str(psutil.disk_io_counters()))
    print("单个分区IO个数:" + str(psutil.disk_io_counters(perdisk=True)))
    print("网络总IO信息:" + str(psutil.net_io_counters()))
    print("输出网络每个接口信息:" + str(psutil.net_io_counters(pernic=True)))
    print("用户登录信息:" + str(psutil.users()))
    #psutil.boot_time()  # 以linux时间格式返回
    print("开机时间:" + str(
        datetime.datetime.fromtimestamp(
            psutil.boot_time()).strftime("%Y-%m-%d %H: %M: %S")))  # 转换成自然时间格

    print(
        "==========================================系统进程管理==========================================="
    )
    print("所有进程的PID:" + str(psutil.pids()))  #方法获取所有进程的PID,
    #psutil.Process(2423) 单个进程的名称, 路径状态等
    print("查看系统全部进程:" + str(psutil.pids()))

    #查看单个进程
    p = psutil.Process(1160)
    print("3172进程名:" + str(p.name()))  # 进程名
    #p.exe()  # 进程的bin路径
    #p.cwd()  # 进程的工作目录绝对路径
    print(psutil.AccessDenied(pid=3172, name='Weibo.exe'))
    print("进程状态:" + str(p.status()))  # 进程状态
    print("进程创建时间:" + str(p.create_time()))  # 进程创建时间
    print("进程的cpu时间信息,包括user,system两个cpu信息:" +
          str(p.cpu_times()))  # 进程的cpu时间信息,包括user,system两个cpu信息
    print("进程内存利用率:" + str(p.memory_percent()))  # 进程内存利用率
    print("进程内存rss,vms信息:" + str(p.memory_info()))  # 进程内存rss,vms信息
    print("进程的IO信息,包括读写IO数字及参数:" + str(p.io_counters()))  # 进程的IO信息,包括读写IO数字及参数
    #print(p.connections())  #0 返回进程列表
    # p.uids()  # 进程uid信息
    # p.gids()  # 进程的gid信息
    print("程开启的线程数:" + str(p.num_threads()))  # 进程开启的线程数
예제 #7
0
 def test_proc_name(self):
     subp = get_test_subprocess(cmd=[self.funky_name])
     if WINDOWS:
         # On Windows name() is determined from exe() first, because
         # it's faster; we want to overcome the internal optimization
         # and test name() instead of exe().
         with mock.patch("psutil._psplatform.cext.proc_exe",
                         side_effect=psutil.AccessDenied(os.getpid())) as m:
             name = psutil.Process(subp.pid).name()
             assert m.called
     else:
         name = psutil.Process(subp.pid).name()
     self.assertIsInstance(name, str)
     if self.expect_exact_path_match():
         self.assertEqual(name, os.path.basename(self.funky_name))
예제 #8
0
    def test_wait_for_user_backends_to_close(self, mock_wait):
        c1 = Mock()
        c1.cmdline = Mock(return_value=["postgres: startup process"])
        c2 = Mock()
        c2.cmdline = Mock(return_value=["postgres: postgres postgres [local] idle"])
        c3 = Mock()
        c3.cmdline = Mock(side_effect=psutil.NoSuchProcess(123))
        with patch('psutil.Process.children', Mock(return_value=[c1, c2, c3])):
            proc = PostmasterProcess(123)
            self.assertIsNone(proc.wait_for_user_backends_to_close())
            mock_wait.assert_called_with([c2])

        c3.cmdline = Mock(side_effect=psutil.AccessDenied(123))
        with patch('psutil.Process.children', Mock(return_value=[c3])):
            proc = PostmasterProcess(123)
            self.assertIsNone(proc.wait_for_user_backends_to_close())
예제 #9
0
    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())
예제 #10
0
    def proc_rlimit(
            proc: Union[int, psutil.Process],
            res: int,
            new_limits: Optional[Tuple[int, int]] = None) -> Tuple[int, int]:
        """Identical to ``Process.rlimit()``, but is implemented for some platforms
        other than Linux.

        WARNING: This function may not be able to set the soft and hard resource limits
        in one operation. If it returns with an error, one or both of the limits may have
        been changed.

        Args:
            proc: Either an integer PID or a ``psutil.Process`` specifying the process
                to operate on. If a ``psutil.Process`` is given and ``new_limits`` is
                passed, this function preemptively checks ``Process.is_running()``.
            res: The resource (one of the ``resource.RLIMIT_*`` constants) to get/set.
            new_limits: If given and not ``None``, the new ``(soft, hard)`` resource
                limits to set.

        Returns:
            A tuple of the given process's ``(soft, hard)`` limits for the given
            resource (prior to setting the new limits).

        """

        pid = _get_pid(proc, check_running=(new_limits is not None))

        if new_limits is not None:
            soft, hard = new_limits

            if soft > hard:
                raise ValueError("current limit exceeds maximum limit")

            if soft < 0:
                soft = resource.RLIM_INFINITY
            if hard < 0:
                hard = resource.RLIM_INFINITY

            new_limits = (soft, hard)

        try:
            return _psimpl.proc_rlimit(pid, res, new_limits)
        except ProcessLookupError as ex:
            raise psutil.NoSuchProcess(pid) from ex
        except PermissionError as ex:
            raise psutil.AccessDenied(pid) from ex
예제 #11
0
    def proc_get_umask(proc: Union[int, psutil.Process]) -> int:
        """Get the umask of the given process.

        Args:
            proc: Either an integer PID or a ``psutil.Process`` specifying the process
                to operate on.

        Returns:
            The given process's umask.

        """

        pid = _get_pid(proc)

        try:
            return _psimpl.proc_get_umask(pid)
        except ProcessLookupError as ex:
            raise psutil.NoSuchProcess(pid) from ex
        except PermissionError as ex:
            raise psutil.AccessDenied(pid) from ex
예제 #12
0
    def proc_getgroups(proc: Union[int, psutil.Process]) -> List[int]:
        """Get the supplementary group list for the given process.

        Args:
            proc: Either an integer PID or a ``psutil.Process`` specifying the process
                to operate on.

        Returns:
            A list containing the given process's supplementary groups.

        """

        pid = _get_pid(proc)

        try:
            return _psimpl.proc_getgroups(pid)
        except ProcessLookupError as ex:
            raise psutil.NoSuchProcess(pid) from ex
        except PermissionError as ex:
            raise psutil.AccessDenied(pid) from ex
예제 #13
0
    def test_process__repr__(self, func=repr):
        p = psutil.Process(self.spawn_testproc().pid)
        r = func(p)
        self.assertIn("psutil.Process", r)
        self.assertIn("pid=%s" % p.pid, r)
        self.assertIn("name='%s'" % str(p.name()),
                      r.replace("name=u'", "name='"))
        self.assertIn("status=", r)
        self.assertNotIn("exitcode=", r)
        p.terminate()
        p.wait()
        r = func(p)
        self.assertIn("status='terminated'", r)
        self.assertIn("exitcode=", r)

        with mock.patch.object(psutil.Process,
                               "name",
                               side_effect=psutil.ZombieProcess(os.getpid())):
            p = psutil.Process()
            r = func(p)
            self.assertIn("pid=%s" % p.pid, r)
            self.assertIn("status='zombie'", r)
            self.assertNotIn("name=", r)
        with mock.patch.object(psutil.Process,
                               "name",
                               side_effect=psutil.NoSuchProcess(os.getpid())):
            p = psutil.Process()
            r = func(p)
            self.assertIn("pid=%s" % p.pid, r)
            self.assertIn("terminated", r)
            self.assertNotIn("name=", r)
        with mock.patch.object(psutil.Process,
                               "name",
                               side_effect=psutil.AccessDenied(os.getpid())):
            p = psutil.Process()
            r = func(p)
            self.assertIn("pid=%s" % p.pid, r)
            self.assertNotIn("name=", r)
예제 #14
0
    def proc_getsid(proc: Union[int, psutil.Process]) -> int:
        """Get the sessopm ID of the given process.

        On platforms where ``os.getsid()`` returns EPERM for processes in other sessions,
        this function may still be able to get the session ID for these processes.

        Args:
            proc: Either an integer PID or a ``psutil.Process`` specifying the process
                to operate on.

        Returns:
            The session ID of the given process.

        """

        pid = _get_pid(proc)

        try:
            return _psimpl.proc_getsid(pid)
        except ProcessLookupError as ex:
            raise psutil.NoSuchProcess(pid) from ex
        except PermissionError as ex:
            raise psutil.AccessDenied(pid) from ex
예제 #15
0
    def proc_getrlimit(proc: Union[int, psutil.Process],
                       res: int) -> Tuple[int, int]:
        """A version of ``proc_rlimit()`` that only supports *getting* resource limits
        (but is implemented on more platforms).

        Args:
            proc: Either an integer PID or a ``psutil.Process`` specifying the process
                to operate on.
            res: The resource (one of the ``resource.RLIMIT_*`` constants) to get/set.

        Returns:
            A tuple of the given process's ``(soft, hard)`` limits for the given
            resource.

        """

        pid = _get_pid(proc)

        try:
            return _psimpl.proc_getrlimit(pid, res)
        except ProcessLookupError as ex:
            raise psutil.NoSuchProcess(pid) from ex
        except PermissionError as ex:
            raise psutil.AccessDenied(pid) from ex
예제 #16
0
    def test_callback_executor(self, mock_popen):
        mock_popen.return_value.children.return_value = []
        mock_popen.return_value.is_running.return_value = True

        ce = CallbackExecutor()
        ce._kill_children = Mock(side_effect=Exception)
        self.assertIsNone(ce.call([]))
        ce.join()

        self.assertIsNone(ce.call([]))

        mock_popen.return_value.kill.side_effect = psutil.AccessDenied()
        self.assertIsNone(ce.call([]))

        ce._process_children = []
        mock_popen.return_value.children.side_effect = psutil.Error()
        mock_popen.return_value.kill.side_effect = psutil.NoSuchProcess(123)
        self.assertIsNone(ce.call([]))

        mock_popen.side_effect = Exception
        ce = CallbackExecutor()
        ce._condition.wait = Mock(side_effect=[None, Exception])
        self.assertIsNone(ce.call([]))
        ce.join()
예제 #17
0
 def mock_cmdlines(p):
     if p.index == 0:
         raise psutil.AccessDenied()
     return MockPsutilProcess.cmdlines[p.index]
    threads=[PsutilProcessThreadMock(1), PsutilProcessThreadMock(2)],
    create_time=1,
    memory_percent=1.1,
)
zombie_process = PsutilProcessMock(
    pid=5,
    cmdline=psutil.ZombieProcess(5),
    cpu_percent=0.0,
    username="******",
    threads=[],
    create_time=1,
    memory_percent=1.1,
)
access_denied_process = PsutilProcessMock(
    pid=6,
    cmdline=psutil.AccessDenied(),
    cpu_percent=0.0,
    username="******",
    threads=[],
    create_time=1,
    memory_percent=1.1,
)
no_such_process = PsutilProcessMock(
    pid=7,
    cmdline=psutil.NoSuchProcess(7),
    cpu_percent=0.0,
    username="******",
    threads=[],
    create_time=1,
    memory_percent=1.1,
)
예제 #19
0
    def test_monitor_process_traps_accessdenied(self):

        with patch('psutil.Process.memory_info', spec=True) as mocked:
            mocked.side_effect = psutil.AccessDenied('')
            self.system_status.monitor_processes()
예제 #20
0
 def test_get_pid_folder_returns_pid_if_access_denied(self):
     pid = os.path.join(self.pr.recovery_directory_hostname, "10000000")
     os.makedirs(pid)
     with mock.patch('psutil.Process.cmdline', side_effect=psutil.AccessDenied()):
         result = self.pr.get_pid_folder_to_load_a_checkpoint_from()
     self.assertEqual(pid, result)
예제 #21
0
 def test_monitor_process_traps_accessdenied(self, test_system_status):
     """Test that monitoring processes can cope with being denied access to process info."""
     test_system_status.mocked_procs[
         0].memory_info.side_effect = psutil.AccessDenied('')
     test_system_status.system_status.monitor_processes()
예제 #22
0
 def test_name(self):
     name = psutil.Process(self.pid).name()
     with mock.patch("psutil._psplatform.cext.proc_exe",
                     side_effect=psutil.AccessDenied(os.getpid())) as fun:
         self.assertEqual(psutil.Process(self.pid).name(), name)
         assert fun.called
예제 #23
0
 def deny_cmdline(obj):
     raise psutil.AccessDenied()
예제 #24
0
 def test_access_denied_exception(self, mock_net):
     import psutil
     mock_net.side_effect = psutil.AccessDenied("")
     self.assertFalse(self._call(12345))
예제 #25
0
 def deny_name(obj):
     raise psutil.AccessDenied()
예제 #26
0
 def test_access_denied__repr__(self):
     self.assertEqual(repr(psutil.AccessDenied(321)),
                      "psutil.AccessDenied(pid=321)")
     self.assertEqual(
         repr(psutil.AccessDenied(321, name="name", msg="msg")),
         "psutil.AccessDenied(pid=321, name='name', msg='msg')")
 def test_monitor_process_traps_accessdenied(self, test_system_status):
     """Test that monitoring processes can cope with being denied access to process info."""
     with patch('psutil.Process.memory_info', spec=True) as mocked:
         mocked.side_effect = psutil.AccessDenied('')
         test_system_status.system_status.monitor_processes()
예제 #28
0
 def test_access_denied__str__(self):
     self.assertEqual(str(psutil.AccessDenied(321)), "(pid=321)")
     self.assertEqual(str(psutil.AccessDenied(321, name="name", msg="msg")),
                      "msg (pid=321, name='name')")