- Четыре команды в терминале Linux для того, чтобы узнать кто вы
- Команда w
- Команда who
- Команда whoami
- Команда last
- Сценарии использования
- Linux who are you
- NAME
- SYNOPSIS
- DESCRIPTION
- OPTIONS
- OPERANDS
- STDIN
- INPUT FILES
- ENVIRONMENT VARIABLES
- ASYNCHRONOUS EVENTS
- STDOUT
- STDERR
- OUTPUT FILES
- EXTENDED DESCRIPTION
- EXIT STATUS
- CONSEQUENCES OF ERRORS
- APPLICATION USAGE
- EXAMPLES
- RATIONALE
- 10 ‘who’ Command Examples for Linux Newbies
Четыре команды в терминале Linux для того, чтобы узнать кто вы
Будучи подростком очень часто смотрел фильмы на видеомагнитофоне. На нескольких кассетах (некоторые из них были фирменными, с изображением актеров и названием фильмов) обитали фильмы с участием Джеки Чана. Одним из таких фильмов был «Кто я?», вышедший в 1998 году. Не поверите, но воспоминание именно об этом фильме побудило написать данный пост! Ниже расскажу про четыре способа ответить на этот вопрос посредством терминала Linux.
Команда w
Да, вот так просто. Введите в терминале всего одну букву и «выхлоп» выдаст список пользователей, которые залогинены в системе и команды, которые они выполняли.
Команда who
Используйте ее, чтобы получить список пользователей, залогиненных в системе. В отличие от предыдущей команды она просто показывает того, кто вошел на сервер.
Команда whoami
Ощущаете, как идем на увеличение количества символов в команде? Именно эта команда позволит узнать кто вы есть. По крайней мере, под какой учетной записью залогинены в системе.
Команда last
Выводит в «выхлопе» историю подключений для определенного пользователя. Для этого после самой команды нужно указать его логин, если же этого не сделать, то появится история для всех пользователей на сервере.
Сценарии использования
Казалось бы зачем нужны эти команды и как их можно использовать в повседневной практике? На самом деле, сценариев использования несколько, расскажу лишь о тех, которые встречались мне:
- на одном из клиентских серверов был спрятан вывод текущего пользователя и имя хоста в консоли, отображалось только значок доллара $. Чтобы понять под каким пользователем я нахожусь в данный момент (обычный или с привилегиями) приходилось использовать команду whoami.
- клиент предоставил root-доступ одному из разработчиков сайта и тот «успешно» затер директорию с нужными скриптами, но в этом никак не признавался, поэтому при помощи команды last показали вплоть до точного времени, какую команду он вводил.
- иногда на сервер подключаются несколько человек одновременно и порой полезно знать кто и с какого IP-адреса подключился (а то вдруг под учеткой доверенного человека на сервер проник злоумышленник), для этого используются некоторые из перечисленных выше команд.
Напоминаю, что другие полезные материалы по теории и практике Linux доступны в соответствующем разделе на канале. Чтобы не пропустить новые заметки подпишитесь на Просто Код и его обновления в Телеграме .
Linux who are you
NAME
who - display who is on the system
SYNOPSIS
who [-mTu] who [-mu]-s[-bHlprt][file] who [-mTu][-abdHlprt][file] who -q [file] who am i who am I
DESCRIPTION
The who utility shall list various pieces of information about accessible users. The domain of accessibility is implementation-defined. Based on the options given, who can also list the user's name, terminal line, login time, elapsed time since activity occurred on the line, and the process ID of the command interpreter for each current system user.
OPTIONS
The who utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. The following options shall be supported. The metavariables, such as line>, refer to fields described in the STDOUT section. -a Process the implementation-defined database or named file with the -b, -d, -l, -p, -r, -t, -T and -u options turned on. -b Write the time and date of the last reboot. -d Write a list of all processes that have expired and not been respawned by the init system process. The exit> field shall appear for dead processes and contain the termination and exit values of the dead process. This can be useful in determining why a process terminated. -H Write column headings above the regular output. -l (The letter ell.) List only those lines on which the system is waiting for someone to login. The name> field shall be LOGIN in such cases. Other fields shall be the same as for user entries except that the state> field does not exist. -m Output only information about the current terminal. -p List any other process that is currently active and has been previously spawned by init. -q (Quick.) List only the names and the number of users currently logged on. When this option is used, all other options shall be ignored. -r Write the current run-level of the init process. -s List only the name>, line>, and time> fields. This is the default case. -t Indicate the last change to the system clock. -T Show the state of each terminal, as described in the STDOUT section. -u Write "idle time" for each displayed user in addition to any other information. The idle time is the time since any activity occurred on the user's terminal. The method of determining this is unspecified. This option shall list only those users who are currently logged in. The name> is the user's login name. The line> is the name of the line as found in the directory /dev. The time> is the time that the user logged in. The activity> is the number of hours and minutes since activity last occurred on that particular line. A dot indicates that the terminal has seen activity in the last minute and is therefore "current". If more than twenty-four hours have elapsed or the line has not been used since boot time, the entry shall be marked old>. This field is useful when trying to determine whether a person is working at the terminal or not. The pid> is the process ID of the user's login process.
OPERANDS
The following operands shall be supported: am i, am I In the POSIX locale, limit the output to describing the invoking user, equivalent to the -m option. The am and i or I must be separate arguments. file Specify a pathname of a file to substitute for the implementation-defined database of logged-on users that who uses by default.
STDIN
INPUT FILES
ENVIRONMENT VARIABLES
The following environment variables shall affect the execution of who: LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.) LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments). LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. LC_TIME Determine the locale used for the format and contents of the date and time strings. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES . TZ Determine the timezone used when writing date and time information. If TZ is unset or null, an unspecified default timezone shall be used.
ASYNCHRONOUS EVENTS
STDOUT
The who utility shall write its default format to the standard output in an implementation-defined format, subject only to the requirement of containing the information described above. XSI-conformant systems shall write the default information to the standard output in the following general format: name>[state>]line>time>[activity>][pid>][comment>][exit>] The following format shall be used for the -T option: "%s %c %s %s\n" name>, terminal state>, terminal name>, time of login> where terminal state> is one of the following characters: + The terminal allows write access to other users. - The terminal denies write access to other users. ? The terminal write-access state cannot be determined. In the POSIX locale, the time of login> shall be equivalent in format to the output of: date +"%b %e %H:%M" If the -u option is used with -T, the idle time shall be added to the end of the previous format in an unspecified format.
STDERR
The standard error shall be used only for diagnostic messages.
OUTPUT FILES
EXTENDED DESCRIPTION
EXIT STATUS
The following exit values shall be returned: 0 Successful completion. >0 An error occurred.
CONSEQUENCES OF ERRORS
Default. The following sections are informative.
APPLICATION USAGE
The name init used for the system process is the most commonly used on historical systems, but it may vary. The "domain of accessibility" referred to is a broad concept that permits interpretation either on a very secure basis or even to allow a network-wide implementation like the historical rwho.
EXAMPLES
RATIONALE
Due to differences between historical implementations, the base options provided were a compromise to allow users to work with those functions. The standard developers also considered removing all the options, but felt that these options offered users valuable functionality. Additional options to match historical systems are available on XSI- conformant systems. It is recognized that the who command may be of limited usefulness, especially in a multi- level secure environment. The standard developers considered, however, that having some standard method of determining the "accessibility" of other users would aid user portability. No format was specified for the default who output for systems not supporting the XSI Extension. In such a user-oriented command, designed only for human use, this was not considered to be a deficiency. The format of the terminal name is unspecified, but the descriptions of ps, talk, and write require that they use the same format. It is acceptable for an implementation to produce no output for an invocation of who mil.
10 ‘who’ Command Examples for Linux Newbies
In our earlier article, we have explained 11 ways to find user account info and login details in Linux. One of the various commands we mentioned was the who command which displays users who are currently logged on to a Linux system, including the terminals they are connecting from.
This article will explain some useful examples of who command for Linux newbies.
The basic syntax for using who command is as follows.
$ who who [OPTION]. [ FILE | ARG1 ARG2 ]
1. If you run who command without any arguments, it will display account information (user login name, user’s terminal, time of login as well as the host the user is logged in from) on your system similar to the one shown in the following output.
$ who ravi tty1 2018-03-16 19:27 tecmint pts/0 2018-03-16 19:26 (192.168.56.1) root pts/1 2018-03-16 19:27 (192.168.56.1)
2. To print the heading of the columns displayed, use the -H flag as shown.
$ who -H NAME LINE TIME COMMENT ravi tty1 2018-03-16 19:27 tecmint pts/0 2018-03-16 19:26 (192.168.56.1) root pts/1 2018-03-16 19:27 (192.168.56.1)
3. To print the login names and total number of logged on users, use the -q flag.
$ who -q ravi tecmint root # users=3
4. In case you want to show only hostname and user associated with stdin, use the -m switch.
$ who -m tecmint pts/0 2018-03-16 19:26 (192.168.56.1)
5. Next, to add user’s message status as + , — or ? , use the -T option.
$ who -T ravi + tty1 2018-03-16 19:27 tecmint + pts/0 2018-03-16 19:26 (192.168.56.1) root + pts/1 2018-03-16 19:27 (192.168.56.1)
The who command also helps you to view some useful system information such as last boot time, current runlevel (target under systemd), print dead processes as well as processes spawned by init.
6. To view the time of last system boot, use the -b flag and adding the -u option allows for listing of logged on users in the same output.
$ who -b system boot 2018-01-19 02:39
$ who -bu system boot 2018-03-16 19:25 ravi tty1 2018-03-16 19:27 00:33 2366 tecmint pts/0 2018-03-16 19:26 . 2332 (192.168.56.1) root pts/1 2018-03-16 19:27 00:32 2423 (192.168.56.1)
7. You can check the current runlevel with the -r option.
$ who -r run-level 3 2018-03-16 02:39
8. The following command will print dead processes.
$ who -d pts/1 2018-03-16 11:10 9986 term=0 exit=0
9. Furthermore, to see active processes spawned by init, use the -p option.
10. Last but not least, the -a flag allows for printing of default output combined with information from some of the options we have covered.
$ who -a system boot 2018-06-16 02:39 run-level 3 2018-01-19 02:39 LOGIN tty1 2018-01-19 02:39 3258 ttyS0 2018-01-19 02:39 3259 + pts/0 2018-03-16 05:33 . 20678 (208.snat-111-91-115.hns.net.in) pts/1 2018-03-14 11:10 9986 term=0 exit=0
You can find more options by consulting the who man page.
In this article, we have explained 10 who command examples for Linux newbies. Use the comment section below to ask any questions or give us your feedback.