Linux show online users

How can I find the number of users online in Linux?

How can I see how many people are logged on to a Linux machine? I know the ‘users’ command shows all the people logged in but I need a number. Is there a switch for users that I am missing in the man page? I thought of using the grep -c command, but there must be something that is the same in each username for this to work. Is there an easier way?

13 Answers 13

You are looking for the wc (word count) command.

note that this approach (an who/w solutions) show only users logged in, not necessarily active users (i.e. users that start a process and then logout leaving the running process behind). Just to give a heads up about the difference.

Classically, the command is ‘who’ rather than ‘users’, but ‘who’ gives you more information. Looking back at the original Unix articles (mid-70s), the example would have been:

Using ‘wc -l’ counts lines of output — it works with both ‘users’ and ‘who’. Using ‘-w’ only works reliably when there is one word per user (as with ‘users’ but not with ‘who’).

You could use ‘grep -c’ to count the lines. Since you are only interested in non-blank user names, you could do:

There’s always at least one character on each line.

As noted in the comments by John T, the users command differs from who in a number of respects. The most important one is that instead of giving one name per line, it spreads the names out several per line — I don’t have a machine with enough different users logged in to test what happens when the number of users becomes large. The other difference is that ‘who’ reports on terminal connections in use. With multiple terminal windows open, it will show multiple lines for a single user, whereas ‘users’ seems to list a logged in user just once.

Читайте также:  Том подкачки в линукс

As a consequence of this difference, the ‘ grep -c . ‘ formulation won’t work with the ‘users’ command; ‘ wc -w ‘ is necessary.

Источник

Shell script to show online users

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.

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.

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.

Jeh, It shows all the hosts, that’s why I need to ignore multiple logins and show the first host, not all.

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 '' | grep -m1 $u done 

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.

Источник

How to view and count users on a Linux system

Computer Hope

The who command shows you every login session open on the machine:

Читайте также:  Завершить все процессы пользователя linux

Who command

You can also use the w command to get a more detailed view of what each login session is doing:

W command

You can count the total number of open sessions by counting the lines in the output of who or w with the -h option. (The -h option omits header lines, which we don’t want to count.) To do this, pipe the output using the vertical bar («|«) to create a command pipeline. The output of one program in the pipeline is passed as input to the next. Here, we count the lines of both who and w -h by piping them to wc -l, effectively generating a count of active sessions.

who wc

Counting unique users

The above method counts login sessions, but if a user has more than one login session open they are counted more than once. To count unique users, we have to get more creative. We can use the cut command to strip all information except for the user name:

who cut

The above command says, «take the output of who, and display only the first field of information, which is delimited by a space.» It gives us a list of only the usernames, but we still need to filter out repeated names.

To do this, we can add the sort -u command. This sorts the names alphabetically and filters out any lines that are not unique:

who cut sort

And finally, to count these unique users, we add wc -l at the end of our command pipeline:

who cut sort wc

Using ps to count users running a process

Another useful technique is to use the ps command to create a list every user on the system that owns a currently-running process. To do this, we can use ps with the options -e, -a, -h, and -o user. They can be combined as follows:

ps command

This command says, «show information for every process owned by any user, do not show headers, and print only the name of the user

Notice that in addition to the users previously listed by who, we also see root listed here. The who command shows only users logged in to a terminal session, but ps lists users that own a running process, even if they don’t have a terminal open. The ps command includes root, and it may include other system-specific users.

Читайте также:  Dithering controls nvidia linux

As before, we can sort our output and only list unique names:

ps sort

. and produce the total desired:

ps sort wc

Источник

Как я могу узнать количество пользователей онлайн в Linux?

Как я могу увидеть, сколько людей вошли на компьютер с Linux? Я знаю, что команда ‘users’ показывает всех людей, вошедших в систему, но мне нужен номер. Есть ли переключатель для пользователей, которого мне не хватает на странице руководства? Я думал об использовании команды grep -c , но в каждом имени пользователя должно быть что-то одинаковое, чтобы это работало. Есть ли более простой способ?

13 ответов 13

Классически, команда «кто», а не «пользователи», но «кто» дает вам больше информации. Оглядываясь назад на оригинальные статьи Unix (середина 70-х годов), можно привести следующий пример:

Использование ‘wc -l’ подсчитывает количество строк вывода — оно работает как с ‘users’, так и с ‘who’. Использование «-w» надежно работает только тогда, когда на пользователя приходится одно слово (как с «пользователями», но не с «кто»).

Вы можете использовать ‘grep -c’ для подсчета строк. Поскольку вас интересуют только непустые имена пользователей, вы можете сделать:

В каждой строке всегда есть хотя бы один символ.

Как отмечено в комментариях Джона Т, команда users отличается от who по ряду аспектов. Наиболее важным является то, что вместо того, чтобы давать одно имя в строке, оно распределяет имена по несколько в строке — у меня нет машины с достаточным количеством зарегистрированных пользователей, чтобы проверить, что происходит, когда число пользователей становится большим. Другое отличие состоит в том, что «кто» сообщает об используемых терминальных соединениях. Если открыто несколько окон терминала, для одного пользователя будет отображаться несколько строк, тогда как «пользователи», по-видимому, выводят зарегистрированного пользователя только один раз.

Как следствие этого различия, grep -c . «Формулировка не будет работать с командой« пользователи »; ‘ wc -w ‘ необходим.

Источник

Оцените статью
Adblock
detector