list of logged in unique users in linux - linux

I am working in linux environment as a non root user. I am using users command to get the logged in users
users
But it returns the user names multiple times because multiple shells are created with same login. Is there any way to print the unique user list using users commad.
Even i tried by
users | sort -u
Still it returns the user names multiple times.

Try with this -
who| awk '{print $1}'|sort -u

users | sort -u
Still it returns the user names multiple times.
Of course. sort is line based, and users only prints a single line.
What you want is to just look at the first word per line before sort -u in who output:
$ who|cut -f 1 -d " "|sort -u
barney
fred
wilma
or
$ who|sed 's/ .*//' |sort -u
barney
fred
wilma
However, if you are interested in some of the actual lines output by who you can also use
$ who|sort -u -k 1,1
barney pts/23 Aug 26 10:11 (:5.0)
fred pts/3 Jun 11 18:38 (:6.0)
wilma pts/0 Jul 31 07:29 (:3.0)

You can try this command: who | cut -d' ' -f1 | sort | uniq
You can use w command to get the list of logged in users and the details

This one is a bit shorter:
users | tr ' ' '\n' | sort -u

Related

Linux command to retrieve the number of times a user has logged in that week

I want a count of the number of times a user, say root or ubuntu has logged in that week - lastlog gives me the information but without doing some parsing, is there a straighforward command to obtain the information.
lastlog | grep logged | awk '{print $1}'
The above for example, gives me who are the users who never logged in.
try last command:
last -F |grep user |wc -l
https://linux-commands-examples.blogspot.com/2018/12/last.html

Counting the same lines from output

I want to list all shells with number of how many users have this shell set as default
to get example output like this :
13 /bin/bash
6 /sbin/nologin
1 /usr/sbin/nologin
the only command that I was managed to create is like this:
cut -d: -f1,7 /etc/passwd | grep -c bash
which returns me only the number of users with set bash as default
Can anyone tell me how should I modify this to get output as I mentioned before?
First, you only want column 7 from the passwd file. The usernames will just get in the way. Then sort and use the uniq command to count them:
$ cut -d: -f7 /etc/passwd | sort | uniq -c
2 /bin/bash
24 /bin/false
1 /bin/sync
1 /usr/local/bin/fish
16 /usr/sbin/nologin

How to get the latest filename alone in a directory?

I am using
ls -ltr /homedir/mydirectory/work/ |tail -n 1|cut -d ' ' -f 10
But this is a very crude way of getting the desired result.And also its unreliable.
The output I get on simply executing
ls -ltr /homedir/mydirectory/work/ |tail -n 1
is
-rw-r--r-- 1 user pusers 1764 Apr 1 12:06 firstfile.xml
So here I get the file name.
But if the output on doing the above command is like
-rw-r--r-- 100 user pusers 1764 Apr 1 12:06 firstfile.xml
the first command fails ! And understandably as I am cutting the result from the 10th character which does not hold valid now.
So how to refine it.
Why do you use the -l flag for ls if you don't need it? Make ls simply output the filenames if you don't need more information instead of trying to "parse" its non-unified output (raping poor text processing utilities...).
LAST_MODIFIED_FILE=`ls -tr | tail -n 1`
If you really want to achieve this using your method, then, use awk instead of cut
ls -ltr /var/log/ |tail -n 1| awk '{print $9}'
Extended user user529758 answer which can give result as per file name
use below commnad as per the file name
ls -tr Filename* | tail -n 1

The number of processes a user is running using bash

I would like to know how I could get the number of processes for each user that is currently logged in.
You could try some variation of this:
ps haux Ou | cut '-d ' -f1 | uniq -c
It gives you the number of processes for each users (being logged in or not). Now you could filter those results using the output of the w command or another way of determining who is logged in.
Give this a try:
ps -u "$(echo $(w -h | cut -d ' ' -f1 | sort -u))" o user= | sort | uniq -c | sort -rn
In order to properly handle usernames that may be longer than eight characters, use users instead of w. The latter truncates usernames.
ps -u "$(echo $(printf '%s\n' $(users) | sort -u))" o user= | sort | uniq -c | sort -rn
ps -u aboelnour | awk 'END {print NR}'
will show number of process which user aboelnour running it
If you are ever concerned about nearing the user process limit shown by ulimit -a, the you want to get ALL the processes (including LWPs). In such a case you should use:
ps h -Led -o user | sort | uniq -c | sort -n
On one system doing this:
ps haux Ou | cut '-d ' -f1 | uniq -c
yields:
# ps haux Ou | cut '-d ' -f1 | uniq -c
30 user1
1 dbus
3 user2
1 ntp
1 nut
1 polkitd
2 postfix
124 root
2 serv-bu+
where doing the former yields the true process count:
# ps h -Led -o user | sort | uniq -c | sort -n
1 ntp
1 nut
2 dbus
2 postfix
2 serv-builder
3 user2
6 polkitd
141 root
444 user1
Just try:
lslogins -o USER,PROC
If you just want a count of processes you can use procfs directly like this:
(requires linux 2.2 or greater)
you can use wc:
number_of_processes=`echo /proc/[0-9]* | wc -w`
or do it in pure bash (no external commands) like this
procs=( /proc/[0-9]* )
number_of_proccesses=${#procs[*]}
If you only want the current userid
procs=( /proc/[0-9]*/fd/. )
number_of_proccesses=${#procs[*]}
userlist=$(w|awk 'BEGIN{ORS=","}NR>2{print $1}'|sed 's/,$//' )
ps -u "$userlist"
Following links contain useful ps commands options including your requirements:
Displaying all processes owned by a specific user
Show All Running Processes in Linux
Here is my solution, for Linux:
$ find /proc –user $USER -maxdepth 1 -name '[0-9]*' | wc –l
This solution will not fail when the number of processes is larger than the command line limit.

Find the IP address of the client in an SSH session

I have a script that is to be run by a person that logs in to the server with SSH.
Is there a way to find out automatically what IP address the user is connecting from?
Of course, I could ask the user (it is a tool for programmers, so no problem with that), but it would be cooler if I just found out.
Check if there is an environment variable called:
$SSH_CLIENT
OR
$SSH_CONNECTION
(or any other environment variables) which gets set when the user logs in. Then process it using the user login script.
Extract the IP:
$ echo $SSH_CLIENT | awk '{ print $1}'
1.2.3.4
$ echo $SSH_CONNECTION | awk '{print $1}'
1.2.3.4
You could use the command:
server:~# pinky
that will give to you somehting like this:
Login Name TTY Idle When Where
root root pts/0 2009-06-15 13:41 192.168.1.133
Try the following to get just the IP address:
who am i|awk '{ print $5}'
Just type the following command on your Linux machine:
who
who | cut -d"(" -f2 |cut -d")" -f1
Improving on a prior answer. Gives ip address instead of hostname. --ips not available on OS X.
who am i --ips|awk '{print $5}' #ubuntu 14
more universal, change $5 to $6 for OS X 10.11:
WORKSTATION=`who -m|awk '{print $5}'|sed 's/[()]//g'`
WORKSTATION_IP=`dig +short $WORKSTATION`
if [[ -z "$WORKSTATION_IP" ]]; then WORKSTATION_IP="$WORKSTATION"; fi
echo $WORKSTATION_IP
who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'
export DISPLAY=`who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'`:0.0
I use this to determine my DISPLAY variable for the session when logging in via ssh and need to display remote X.
netstat -tapen | grep ssh | awk '{ print $4}'
A simple command to get a list of recent users logged in to the machine is last. This is ordered most recent first, so last | head -n 1 will show the last login. This may not be the currently logged in user though.
Sample output:
root pts/0 192.168.243.99 Mon Jun 7 15:07 still logged in
admin pts/0 192.168.243.17 Mon Jun 7 15:06 - 15:07 (00:00)
root pts/0 192.168.243.99 Mon Jun 7 15:02 - 15:06 (00:03)
root pts/0 192.168.243.99 Mon Jun 7 15:01 - 15:02 (00:00)
root pts/0 192.168.243.99 Mon Jun 7 13:45 - 14:12 (00:27)
root pts/0 192.168.243.99 Mon May 31 11:20 - 12:35 (01:15)
...
You can get it in a programmatic way via an SSH library (https://code.google.com/p/sshxcute)
public static String getIpAddress() throws TaskExecFailException{
ConnBean cb = new ConnBean(host, username, password);
SSHExec ssh = SSHExec.getInstance(cb);
ssh.connect();
CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
String Result = ssh.exec(sampleTask).sysout;
ssh.disconnect();
return Result;
}
an older thread with a lot of answers, but none are quite what i was looking for, so i'm contributing mine:
sshpid=$$
sshloop=0
while [ "$sshloop" = "0" ]; do
if [ "$(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT)" ];
then
read sshClientIP sshClientSport sshClientDport <<< $(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT | cut -d= -f2)
sshloop=1
else
sshpid=$(cat /proc/${sshpid}/status | grep PPid | awk '{print $2}')
[ "$sshpid" = "0" ] && sshClientIP="localhost" && sshloop=1
fi
done
this method is compatible with direct ssh, sudoed users, and screen sessions. it will trail up through the process tree until it finds a pid with the SSH_CLIENT variable, then record its IP as $sshClientIP. if it gets too far up the tree, it will record the IP as 'localhost' and leave the loop.
I'm getting the following output from who -m --ips on Debian 10:
root pts/0 Dec 4 06:45 123.123.123.123
Looks like a new column was added, so {print $5} or "take 5th column" attempts don't work anymore.
Try this:
who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'
Source:
#Yvan's comment on #AlexP's answer
#Sankalp's answer
netstat -tapen | grep ssh | awk '{ print $10}'
Output:
two # in my experiment
netstat -tapen | grep ssh | awk '{ print $4}'
gives the IP address.
Output:
127.0.0.1:22 # in my experiment
But the results are mixed with other users and stuff. It needs more work.
Assuming he opens an interactive session (that is, allocates a pseudo terminal) and you have access to stdin, you can call an ioctl on that device to get the device number (/dev/pts/4711) and try to find that one in /var/run/utmp (where there will also be the username and the IP address the connection originated from).
Usually there is a log entry in /var/log/messages (or similar, depending on your OS) which you could grep with the username.
netstat will work (at the top something like this)
tcp 0 0 10.x.xx.xx:ssh someipaddress.or.domainame:9379 ESTABLISHED
Linux: who am i | awk '{print $5}' | sed 's/[()]//g'
AIX: who am i | awk '{print $6}' | sed 's/[()]//g'
Search for SSH connections for "myusername" account;
Take first result string;
Take 5th column;
Split by ":" and return 1st part (port number don't needed, we want just IP):
netstat -tapen | grep "sshd: myusername" | head -n1 | awk '{split($5, a, ":"); print a[1]}'
Another way:
who am i | awk '{l = length($5) - 2; print substr($5, 2, l)}'
One thumb up for #Nikhil Katre's answer :
Simplest command to get the last 10 users logged in to the machine is last|head.
To get all the users simply use last command
The one using who or pinky did what is basically asked. But But But they don't give historical sessions info.
Which might also be interesting if you want to know someone who has just logged in and
logged out already when you start this checking.
if it is a multiuser system. I recommand add the user account you are looking for:
last | grep $USER | head
EDIT:
In my case, both $SSH_CLIENT and $SSH_CONNECTION do not exist.

Resources