Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I know it's an amateur question. I need to write a Bash shell script which count how many users are online at the moment on the SSH server. I need to ignore multiple logins and show the username and the place where they logged in.

Thanks.

share|improve this question
    
Shell meaning Linux shell? Which linux shell? "Online atm at the server", how do people log in to your server (ssh, telnet, ftp, etc.)? That may change things. –  nerdwaller Dec 11 '13 at 21:12
    
Linux shell, bash shell, SSH logs, i tried with rwho but it show the multiple logins –  Patrik Zelena Dec 11 '13 at 21:20
1  
If you're interested in showing the location of each login, perhaps you need to reconsider ignoring multiple logins; if I'm connected via SSH to host A from both host B and host C, you can either show me as logged in twice, once from each host, or throw away some information. –  Aaron Miller Dec 11 '13 at 21:38
    
Jeh, It shows all the hosts, that's why I need to ignore multiple logins and show the first host, not all. –  Patrik Zelena Dec 11 '13 at 21:42

2 Answers 2

This smells like homework but oh well:

#!/bin/bash

users=$(users | xargs -n1 | sort -u)
for u in $users; do
    w -h | awk '{print $1 " " $3}' | grep -m1 $u
done

Explanation:

First we builds a list of logged in users with the "user" command, and filter out duplicates by putting one on each line (xargs -n) and sorting with uniques filtered (sort -u).

w -h prints a list of all logged in users, we pipe that through awk printing only the desired fields (1 and 3), piping the result through grep to filter all but the user we're looking for on each loop iteration. -m1 ensures it stops after the first match, you could also pipe through 'head -1' instead.

share|improve this answer

Same question was asked on stackoverflow. Not sure what the procedure is, but I guess I'll re-post my answer To get unique list of users with some login across the network

 rwho | awk '{ print $2 " " $1 }' | sort | uniq -f 1

To get count

 rwho | awk '{ print $2 " " $1 }' | sort | uniq -f 1 | wc -l

And same thing with who for login on a particular host

 who | awk '{ print $5 " " $1 }' | sort | uniq -f 1
 who | awk '{ print $5 " " $1 }' | sort | uniq -f 1 | wc -l

Could use w instead, but that can truncate the hostname, which may not be desired behavior.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.