Skip to content Skip to sidebar Skip to footer

Find Out Who Is Logged In On Linux Using Python

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

Solution 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)]

Solution 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-1419:09 (:0.0)
monty    pts/0        2013-01-1419: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'])

Solution 3:

from subprocess import Popen, PIPE, STDOUT

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

# Output >>> sudo_O  :02013-01-1411:48 (:0)
>>> sudo_O  pts/02013-01-1411:48 (:0)
>>> sudo_O  pts/12013-01-1412:41 (:0)
>>> sudo_O  pts/22013-01-1412:42 (:0)

Solution 4:

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

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

Solution 5:

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

Post a Comment for "Find Out Who Is Logged In On Linux Using Python"