Find out who is logged in on linux using python [c

2020-05-06 13:39发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

I have 8 servers that I would like to monitor. All servers have a tornado python server installed. One of the servers is a monitor that polls other servers and alerts me by SMS if there is a problem.

One of the alerts is when a user logs into one of the servers.

How can I use Python to detect who is logged in on my Ubuntu server? I need to return logged in users to the main monitor. I hope this makes things clear..

回答1:

The best thing I found online is psutil. See the psutil documentation

First install psutil :

pip install psutil

After that everything is easy as an example run python console from terminal:

import psutil 

psutil.users()

Output:

[user(name='root', terminal='pts/0', host='your-local-host-from-isp.net',
started=1358152704.0)]


回答2:

Use the subprocess module, and run the command who.

In [5]: import subprocess

In [6]: subprocess.check_output("who")
Out[6]: 'monty    pts/0        2013-01-14 16:21 (:0.0)\n'

You can fetch the number of current logins using : who | wc -l:

In [42]: !who
monty    pts/2        2013-01-14 19:09 (:0.0)
monty    pts/0        2013-01-14 19:07 (:0.0)

In [43]: p=Popen(["who"],stdout=PIPE)

In [44]: Popen(["wc","-l"],stdin=p.stdout).communicate()[0]
2

Names of the users:

In [54]: users=check_output("who")

In [55]: set([x.split()[0] for x in users.splitlines()])
Out[55]: set(['monty'])


回答3:

from subprocess import Popen, PIPE, STDOUT

who = Popen(['who'],stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print who.stdout.read()

# Output 
>>> sudo_O  :0           2013-01-14 11:48 (:0)
>>> sudo_O  pts/0        2013-01-14 11:48 (:0)
>>> sudo_O  pts/1        2013-01-14 12:41 (:0)
>>> sudo_O  pts/2        2013-01-14 12:42 (:0)


回答4:

And if you dont want to install 3-rd party software. You can always run unix who utility

import os
os.popen('who').read()


回答5:

In [1]: import subprocess
In [2]: print subprocess.check_output("who").split()[0]
Out[3]: 'rikatee'