Python psutil.users() Examples

The following are 30 code examples of psutil.users(). 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 psutil with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def test_users(self):
        users = psutil.users()
        self.assertNotEqual(users, [])
        for user in users:
            assert user.name, user
            self.assertIsInstance(user.name, str)
            self.assertIsInstance(user.terminal, (str, type(None)))
            if user.host is not None:
                self.assertIsInstance(user.host, (str, type(None)))
            user.terminal
            user.host
            assert user.started > 0.0, user
            datetime.datetime.fromtimestamp(user.started)
            if WINDOWS or OPENBSD:
                self.assertIsNone(user.pid)
            else:
                psutil.Process(user.pid) 
Example #2
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
def connected_users(self) -> ConnectedUserResponseList:
        """
        Get the list of connected users.
        :return: List of :class:`platypush.message.response.system.ConnectUserResponse`.
        """
        import psutil
        users = psutil.users()

        return ConnectedUserResponseList([
            ConnectUserResponse(
                name=u.name,
                terminal=u.terminal,
                host=u.host,
                started=datetime.fromtimestamp(u.started),
                pid=u.pid,
            )
            for u in users
        ])

    # noinspection PyShadowingBuiltins 
Example #3
Source File: test_linux.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_users_mocked(self):
        # Make sure ':0' and ':0.0' (returned by C ext) are converted
        # to 'localhost'.
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0.0',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        # ...otherwise it should be returned as-is
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', 'foo',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'foo')
            assert m.called 
Example #4
Source File: test_system.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_users(self):
        users = psutil.users()
        self.assertNotEqual(users, [])
        for user in users:
            assert user.name, user
            self.assertIsInstance(user.name, str)
            self.assertIsInstance(user.terminal, (str, type(None)))
            if user.host is not None:
                self.assertIsInstance(user.host, (str, type(None)))
            user.terminal
            user.host
            assert user.started > 0.0, user
            datetime.datetime.fromtimestamp(user.started)
            if WINDOWS or OPENBSD:
                self.assertIsNone(user.pid)
            else:
                psutil.Process(user.pid) 
Example #5
Source File: test_misc.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #6
Source File: activity.py    From autosuspend with GNU General Public License v2.0 6 votes vote down vote up
def check(self) -> Optional[str]:
        for entry in psutil.users():
            if (
                self._user_regex.fullmatch(entry.name) is not None
                and self._terminal_regex.fullmatch(entry.terminal) is not None
                and self._host_regex.fullmatch(entry.host) is not None
            ):
                self.logger.debug(
                    "User %s on terminal %s from host %s " "matches criteria.",
                    entry.name,
                    entry.terminal,
                    entry.host,
                )
                return (
                    "User {user} is logged in on terminal {terminal} "
                    "from {host} since {started}".format(
                        user=entry.name,
                        terminal=entry.terminal,
                        host=entry.host,
                        started=entry.started,
                    )
                )
        return None 
Example #7
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def user_name():
            arr = []
            for user in psutil.users():
                if str(user[0]) is not 'None' and user[0] not in arr:
                    arr.append(user[0])
            return arr 
Example #8
Source File: security_audit_implement.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def logged_user(response):

	values = [[Klanguage().to_ts(1135), Klanguage().to_ts(1141), Klanguage().to_ts(1142), Klanguage().to_ts(1143)]]

	for user in psutil.users():
		values.append([
			user[0],
			user[1],
			user[2],
			time_op.timestamp2string(int(user[3]))
		])

	response["authentication"].append({
		"name" : Klanguage().to_ts(1140),
		"values" : values
	}) 
Example #9
Source File: authentication.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def logged_user(response):

	values = [["NAME", "TERMINAL", "HOST", "STARTED"]]

	for user in psutil.users():
		values.append([
			user[0],
			user[1],
			user[2],
			time_op.timestamp2string(int(user[3]))
		])

	response["authentication"].append({
		"name" : "Who is logged on",
		"value" : len(values) - 1,
		"values" : values
	}) 
Example #10
Source File: test_misc.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #11
Source File: test_misc.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #12
Source File: test_system.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_users(self):
        users = psutil.users()
        self.assertNotEqual(users, [])
        for user in users:
            assert user.name, user
            self.assertIsInstance(user.name, str)
            self.assertIsInstance(user.terminal, (str, type(None)))
            if user.host is not None:
                self.assertIsInstance(user.host, (str, type(None)))
            user.terminal
            user.host
            assert user.started > 0.0, user
            datetime.datetime.fromtimestamp(user.started)
            if WINDOWS or OPENBSD:
                self.assertIsNone(user.pid)
            else:
                psutil.Process(user.pid) 
Example #13
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_users_mocked(self):
        # Make sure ':0' and ':0.0' (returned by C ext) are converted
        # to 'localhost'.
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0.0',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        # ...otherwise it should be returned as-is
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', 'foo',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'foo')
            assert m.called 
Example #14
Source File: test_contracts.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_users(self):
        # Duplicate of test_system.py. Keep it anyway.
        for user in psutil.users():
            self.assertIsInstance(user.name, str)
            self.assertIsInstance(user.terminal, (str, type(None)))
            self.assertIsInstance(user.host, (str, type(None)))
            self.assertIsInstance(user.pid, (int, type(None)))


# ===================================================================
# --- Featch all processes test
# =================================================================== 
Example #15
Source File: test_memory_leaks.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_users(self):
        self.execute(psutil.users) 
Example #16
Source File: test_posix.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_users(self):
        out = sh("who")
        lines = out.split('\n')
        users = [x.split()[0] for x in lines]
        terminals = [x.split()[1] for x in lines]
        self.assertEqual(len(users), len(psutil.users()))
        for u in psutil.users():
            self.assertIn(u.name, users)
            self.assertIn(u.terminal, terminals) 
Example #17
Source File: test_posix.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_nic_names(self):
        output = sh("ifconfig -a")
        for nic in psutil.net_io_counters(pernic=True).keys():
            for line in output.split():
                if line.startswith(nic):
                    break
            else:
                self.fail(
                    "couldn't find %s nic in 'ifconfig -a' output\n%s" % (
                        nic, output))

    # can't find users on APPVEYOR or TRAVIS 
Example #18
Source File: test_contracts.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        if POSIX:
            import pwd
            import grp
            users = pwd.getpwall()
            groups = grp.getgrall()
            self.all_uids = set([x.pw_uid for x in users])
            self.all_usernames = set([x.pw_name for x in users])
            self.all_gids = set([x.gr_gid for x in groups]) 
Example #19
Source File: test_contracts.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_users(self):
        # Duplicate of test_system.py. Keep it anyway.
        for user in psutil.users():
            self.assertIsInstance(user.name, str)
            self.assertIsInstance(user.terminal, (str, type(None)))
            self.assertIsInstance(user.host, (str, type(None)))
            self.assertIsInstance(user.pid, (int, type(None)))


# ===================================================================
# --- Featch all processes test
# =================================================================== 
Example #20
Source File: test_misc.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_procinfo(self):
        self.assert_stdout('procinfo.py', str(os.getpid()))

    # can't find users on APPVEYOR or TRAVIS 
Example #21
Source File: test_misc.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_procinfo(self):
        self.assert_stdout('procinfo.py', str(os.getpid()))

    # can't find users on APPVEYOR or TRAVIS 
Example #22
Source File: test_memory_leaks.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def test_users(self):
        self.execute(psutil.users) 
Example #23
Source File: node.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def get_users(self):
        return [u._asdict() for u in psutil.users()] 
Example #24
Source File: activity.py    From autosuspend with GNU General Public License v2.0 5 votes vote down vote up
def _list_sessions_sockets(self) -> Sequence[Tuple[int, str]]:
        """List running X sessions by iterating the X sockets.

        This method assumes that X servers are run under the users using the
        server.
        """
        sockets = glob.glob("/tmp/.X11-unix/X*")
        self.logger.debug("Found sockets: %s", sockets)

        results = []
        for sock in sockets:
            # determine the number of the X display
            try:
                display = int(sock[len("/tmp/.X11-unix/X") :])
            except ValueError:
                self.logger.warning(
                    "Cannot parse display number from socket %s. Skipping.",
                    sock,
                    exc_info=True,
                )
                continue

            # determine the user of the display
            try:
                user = pwd.getpwuid(os.stat(sock).st_uid).pw_name
            except (FileNotFoundError, KeyError):
                self.logger.warning(
                    "Cannot get the owning user from socket %s. Skipping.",
                    sock,
                    exc_info=True,
                )
                continue

            results.append((display, user))

        return results 
Example #25
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def user_details():
            return psutil.users() 
Example #26
Source File: test_contracts.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def setUp(self):
        if POSIX:
            import pwd
            import grp
            users = pwd.getpwall()
            groups = grp.getgrall()
            self.all_uids = set([x.pw_uid for x in users])
            self.all_usernames = set([x.pw_name for x in users])
            self.all_gids = set([x.gr_gid for x in groups]) 
Example #27
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def user_details():
            return psutil.users() 
Example #28
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def user_name():
            arr = []
            for user in psutil.users():
                if str(user[0]) is not 'None' and user[0] not in arr:
                    arr.append(user[0])
            return arr 
Example #29
Source File: ss-agent.py    From ServerSan with Apache License 2.0 5 votes vote down vote up
def get_sessions():
    info = '%d user(s) in Total' % len(psutil.users())
    for user in psutil.users():
        info += '\n%s on %s from %s at %s' % (
            user[0], user[1], user[2], time.strftime("%Y-%m-%d %H:%M", time.localtime(user[3])))
    return info 
Example #30
Source File: test_posix.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_nic_names(self):
        output = sh("ifconfig -a")
        for nic in psutil.net_io_counters(pernic=True).keys():
            for line in output.split():
                if line.startswith(nic):
                    break
            else:
                self.fail(
                    "couldn't find %s nic in 'ifconfig -a' output\n%s" % (
                        nic, output))

    # can't find users on APPVEYOR or TRAVIS