Linux посмотреть ssh сессии

List all connected SSH sessions?

I just SSH’d into root, and then SSH’d again into root on the same machine. So I have two windows open both SSH’d into root on my remote machine. From the shell, how can I see a list of these two sessions?

7 Answers 7

who or w ; who -a for additional information.

These commands just show all login sessions on a terminal device. An SSH session will be on a pseudo-terminal slave ( pts ) as shown in the TTY column, but not all pts connections are SSH sessions. For instance, programs that create a pseudo-terminal device such as xterm or screen will show as pts . See Difference between pts and tty for a better description of the different values found in the TTY column. Furthermore, this approach won’t show anybody who’s logged in to an SFTP session, since SFTP sessions aren’t shell login sessions.

I don’t know of any way to explicitly show all SSH sessions. You can infer this information by reading login information from utmp / wtmp via a tool like last , w , or who like I’ve just described, or by using networking tools like @sebelk described in their answer to find open tcp connections on port 22 (or wherever your SSH daemon(s) is/are listening).

A third approach you could take is to parse the log output from the SSH daemon. Depending on your OS distribution, SSH distribution, configuration, and so on, your log output may be in a number of different places. On an RHEL 6 box, I found the logs in /var/log/sshd.log . On an RHEL 7 box, and also on an Arch Linux box, I needed to use journalctl -u sshd to view the logs. Some systems might output SSH logs to syslog. Your logs may be in these places or elsewhere. Here’s a sample of what you might see:

[myhost ~]% grep hendrenj /var/log/sshd.log | grep session May 1 15:57:11 myhost sshd[34427]: pam_unix(sshd:session): session opened for user hendrenj by (uid=0) May 1 16:16:13 myhost sshd[34427]: pam_unix(sshd:session): session closed for user hendrenj May 5 14:27:09 myhost sshd[43553]: pam_unix(sshd:session): session opened for user hendrenj by (uid=0) May 5 18:23:41 myhost sshd[43553]: pam_unix(sshd:session): session closed for user hendrenj 

The logs show when sessions open and close, who the session belongs to, where the user is connecting from, and more. However, you’re going to have to do a lot of parsing if you want to get this from a simple, human-readable log of events to a list of currently active sessions, and it still probably won’t be an accurate list when you’re done parsing, since the logs don’t actually contain enough information to determine which sessions are still active — you’re essentially just guessing. The only advantage you gain by using these logs is that the information comes directly from SSHD instead of via a secondhand source like the other methods.

Читайте также:  Узнать пароль пользователя линукс

I recommend just using w . Most of the time, this will get you the information you want.

Источник

How to List All Connected SSH Sessions on Linux

Secure Shell (SSH) is a commonly used protocol for secure remote access to Linux servers. When multiple users are connected to a Linux server via SSH, it can be useful to list all connected SSH sessions for administrative or monitoring purposes. In this article, we will discuss how to list all connected SSH sessions on Linux using various command line tools.

List of SSH sessions connected with the who command

The who command is a simple and widely available command-line tool for listing logged in users on a Linux system. To list all connected SSH sessions, you can use the “who -a” command. The -a option shows all users, including those who are not logged in through the system console. The result will show your username, terminal, and login date and time.

$ who -a root pts/0 2020-12-19 14:20 (10.0.0.1) user1 pts/1 2020-12-19 15:25 (10.0.0.2) user2 pts/2 2020-12-19 14:30 (10.0.0.3)

In this example, the output shows that there are three users currently connected: «root», «user1» and «user2», along with the endpoint they connected to and the IP addresses they connected from.

List of SSH sessions connected with the w command

Another command-line tool that can be used to list connected SSH sessions is “w”. This command displays information about users currently logged on to the system, and also displays the process each user is running. To list all connected SSH sessions, you can use the “w -h” command, which omits the header and shows only the process.

$ w -h root pts/0 14:20 2.00s 0.00s ssh 10.0.0.1 user1 pts/1 14:25 1.00s 0.00s ssh 10.0.0.2 user2 pts/2 14:30 1.00s 0.00s ssh 10.0.0.3

In this example, the output shows that the three users are currently connected, the terminal they are connected to, and the IP addresses they are connecting from.

List of SSH sessions connected with the last command

The last command is used to display users who have recently logged on to the system. This command can also be used to list connected SSH sessions using the latest “-i” command.

$ last -i root pts/0 10.0.0.1 Sun Dec 19 14:20 - 14:25 (00:05) user1 pts/1 10.0.0.2 Sun Dec 19 14:25 - 14:30 (00:05) user2 pts/2 10.0.0.3 Sun Dec 19 14:30 - 14:35 (00:05)

In this example, the output shows the three users currently connected, the endpoint they connected to, the IP addresses they connected from, and the length of their session.

List of SSH sessions connected with the who -u command

You can also use the “who -u” command to list all connected SSH sessions. This command displays the user, terminal, and login date and time.

$ who -u root pts/0 2020-12-19 14:20 (10.0.0.1) user1 pts/1 2020-12-19 14:25 (10.0.0.2) user2 pts/2 2020-12-19 14:30 (10.0.0.3)

The “-u” option shows users and their idle time, but does not show IP addresses. So, if IP information is important to you, you can combine this command with the “-i” option which will show the IP addresses.

$ who -u -i root pts/0 2020-12-19 14:20 (10.0.0.1) . . . . . . . . . . . . . . . user1 pts/1 2020-12-19 14:25 (10.0.0.2) . . . . . . . . . . . . . . . user2 pts/2 2020-12-19 14:30 (10.0.0.3) . . . . . . . . . . . . . . .

List of SSH sessions connected with the ss command

Another command that can be used to list connected SSH sessions is ss. This command is similar to netstat but more efficient and is used to dump socket statistics. To list all connected SSH sessions, you can use the “ss -t -a” command.

$ ss -t -a | grep ssh tcp ESTAB 0 0 10.0.0.1:ssh 10.0.0.1:46754 users:(("sshd",pid=9987,fd=3)) tcp ESTAB 0 0 10.0.0.2:ssh 10.0.0.2:47754 users:(("sshd",pid=9987,fd=3)) tcp ESTAB 0 0 10.0.0.3:ssh 10.0.0.3:48754 users:(("sshd",pid=9987,fd=3))

The “-t” option shows only TCP connections and the “-a” option shows all sockets. The grep command is used to filter the output and shows only ssh connections.

Читайте также:  Linux установка драйверов ati

Conclusion

In this article, we have discussed several command-line tools for listing connected SSH sessions on Linux. Each command has its own specific options and output format, so it’s up to you to choose the one that best suits your needs. It is always recommended to consult the man pages of each command before using it, to ensure that you are using the correct options and getting the expected result.

Источник

Как проверить историю IP адресов для SSH сессий

В случае если сервер на Linux был взломан, возникает необходимость собрать информацию, например, получить время и IP адреса последних SSH сессий. Это может помочь не только установить источник опасности, но и, например, ответить на вопрос: был ли подобран пароль (или скомпрометирован сертификат) SSH либо злоумышленник воспользовался уязвимостью программного обеспечения.

К счастью, в дистрибутивах Linux хранятся журналы входа в систему, как по сети, так и для пользователей, который непосредственно сидят перед компьютером.

IP адрес предыдущего подключения по SSH

При каждом подключении по SSH выводится строка с IP, с которого было сделано предыдущее подключение, также показывается дата и время этого подключения:

Last login: Thu Oct 7 14:14:48 2021 from 31.28.200.227

История IP адресов SSH подключений

Кроме последней сессии, в системе хранится информация обо всех успешных входах за последние месяцы. Эта информация содержится в файле utmp / wtmp. На самом деле, файл utmp могут использовать различные программы (не только SSH), которые хотят сохранить информацию о входе пользователя.

Во многих дистрибутивах имеется файл /var/log/wtmp, куда программы записывают входы в систему. Проверить последние записи можно командой:

Все записи, в которых встречаются IP адреса — были сделаны по SSH подключению.

Записи без IP адресов — это входы пользователей, находящихся непосредственно перед компьютером.

Дополнительно вы можете проверить другие файлы журналов: /var/log/secure (на дистрибутивах на основе RH) или /var/log/auth.log (на дистрибутивах на основе Debian). В этих файлах служба sshd обычно хранит следы сделанных подключений, даже если они не стали результатом успешных входов (как это делают utmp/wtmp, которые сохраняют только информацию об успешных входах).

Apr 3 16:21:01 xxxxxxvlp05 sshd[6266]: Connection closed by xxx.xxx.13.76 . Apr 3 09:09:49 xxxxxxvlp05 sshd[26275]: Failed password for invalid user __super from xxx.xxx.13.76 port 45229 ssh2

Служба sshd на IIRC Solaris (которая необязательно является sshd службой OpenSSH) хранит эту информацию в /var/adm/messages.

Читайте также:  Java jre jdk linux

При этом необходимо помнить, что если атакующий получил доступ с правами суперпользователя, то есть скомпрометирован аккаунт root или другого пользователя с повышенными привилегиями, то все записи в файлах /var/log/wtmp или /var/adm/messages могут быть изменены атакующим. Для защиты от этого необходимо регулярно выгружать журналы в безопасное хранилище.

Как узнать, кто в настоящий момент подключён по SSH

Чтобы увидеть пользователей, вошедших в систему, используйте любую из следующих команд:

Следующие команды также покажут активные SSH сессии — у каждой из них различается набор выводимой информации, поэтому вы можете выбрать ту из них, которая вам больше всего подходит:

netstat -tnpa | grep 'ESTABLISHED.*sshd' ss -tap | grep 'ESTAB.*sshd' ps ax | grep sshd echo $SSH_CONNECTION

Источник

joshschmelzle / list-ssh-sessions.md

I was curious how to view sessions on a Linux box I had at my desk. Similar to the session table on an Aruba controller ( show loginsessions ). Here are some ways you can list active SSH sessions; some commands return more output than others. This applies to most modern Linux boxes or say a WLAN Pi.

All examples below are using 2 MobaXterm user sessions from a Windows machine to a Linux 4.14.42-sunxi64 aarch64 (NanoPi NEO2).

wlanpi@wlanpi:~$ w 15:00:36 up 2:36, 2 users, load average: 0.21, 0.20, 0.18 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT wlanpi pts/0 192.168.1.68 14:51 0.00s 0.41s 0.01s w wlanpi pts/2 192.168.1.68 13:00 9:00 0.49s 0.49s -bash 
wlanpi@wlanpi:~$ who wlanpi pts/0 2018-05-23 14:51 (192.168.1.68) wlanpi pts/2 2018-05-23 13:00 (192.168.1.68) 

This one is for when you’re in a pseudo shell and should return your IP and port and the IP you’re connected to and port. This won’t show other sessions.

wlanpi@wlanpi:~$ echo $SSH_CONNECTION 192.168.1.68 5875 192.168.1.94 22 

netstat -tnpa | grep ‘ESTABLISHED.*sshd’

wlanpi@wlanpi:~$ sudo netstat -tnpa | grep 'ESTABLISHED.*sshd' tcp 0 0 192.168.1.94:22 192.168.1.68:19172 ESTABLISHED 927/sshd: wlanpi [p tcp 0 0 192.168.1.94:22 192.168.1.68:5875 ESTABLISHED 17200/sshd: wlanpi tcp 0 0 192.168.1.94:22 192.168.1.68:5876 ESTABLISHED 17222/sshd: wlanpi tcp 0 0 192.168.1.94:22 192.168.1.68:19168 ESTABLISHED 886/sshd: wlanpi [p 
wlanpi@wlanpi:~$ ps auxwww | grep sshd: root 886 0.9 1.2 11872 6092 ? Ss 14:51 0:00 sshd: wlanpi [priv] root 927 0.8 1.2 11876 6076 ? Ss 14:51 0:00 sshd: wlanpi [priv] wlanpi 997 2.2 0.9 12060 4460 ? S 14:51 0:00 sshd: wlanpi@pts/0 wlanpi 1070 0.0 0.9 11876 4508 ? S 14:51 0:00 sshd: wlanpi@notty wlanpi 1196 0.0 0.1 4308 580 pts/2 S+ 14:51 0:00 grep sshd: root 17200 0.0 1.2 11872 6120 ? Ss 13:00 0:00 sshd: wlanpi [priv] root 17222 0.0 1.2 11876 5992 ? Ss 13:00 0:00 sshd: wlanpi [priv] wlanpi 17294 0.0 0.9 12212 4700 ? S 13:00 0:00 sshd: wlanpi@pts/2 wlanpi 17365 0.0 0.9 11876 4552 ? S 13:00 0:00 sshd: wlanpi@notty 
wlanpi@wlanpi:~$ pgrep -ai sshd 777 /usr/sbin/sshd -D 886 sshd: wlanpi [priv] 927 sshd: wlanpi [priv] 997 sshd: wlanpi@pts/0 1070 sshd: wlanpi@notty 17200 sshd: wlanpi [priv] 17222 sshd: wlanpi [priv] 17294 sshd: wlanpi@pts/2 17365 sshd: wlanpi@notty 

Источник

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