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.
Как узнать, кто подключился по SSH
Иногда становится интересно: кто же сейчас копается на сервере, а главное – откуда (с каких ip-адресов). Стандартный метод подключения к серверу – SSH. Его то мы и будем искать среди наших коннектов. Если у вас современный Linux-дистрибутив, скорее всего, для работы сокетами у вас используется утилита ss. Так, к примеру, вы можете посмотреть все входящие и исходящие ssh-соединения:
ss -o state established '( dport = :ssh or sport = :ssh )'
Если же в ваших руках сервер-динозавр: стабильный, но не свежий, скорее всего, у вас будет использоваться утилита netstat. Так вы сможете получить всё те же входящие и исходящие ssh-соединения:
netstat -tnpa | grep 'ESTABLISHED.*sshd'
И совсем уже экзотический вариант – воспользоваться утилитой lsof, которая отвечает уже за открытые файловые дескрипторы. Но в Unix у нас «всё есть файл», так что и для открытых соединений сгодится:
lsof -n -a -itcp -stcp:established -c sshd
Дыры в безопасности, утечки данных и иные проблемы в информационной безопасности. Примеры и новости, связанные с проблемами в безопасности информационных систем. Художественные и документальные произведения, где используются или описываются взломы …
Команды и инструкции терминала (консоли) Linux, MacOS, Windows и прочих операционных систем. Трюки и особенности командных оболочек, скрипты для администрирования Unix. Программирование и скриптование Windows и Linux, тонкая настройка Macos. …
Операционная система Linux (Линукс или Лайнакс) во многом похожая на проприетарную Unix. Линукс распространён на серверах, что означает, что изучая её вы улучшаете свой навык администрирования, DevOps и программирования. Открытая …
Заметки об обеспечении безопасности в информационных системах. Настройка брендмауэров (фаерволов) на операционных системах Linux, Windows, MacOS, Unix. Новости об интересных уязвимостях в системах, мониторинге использования ресурсов, алертинге подозрительных действий. Работа …
Настройки сетевых подключений в различных операционных системах. Сетевые протоколы и клиентские/серверные приложения для работы по ним. Настройка серверов и приложений для оптимальной работы. Тюнинг приложений, запуск и настройка серверов, анализ …
How to get the list of all users who can access a server via ssh?
How can I get the list of all the users who can ssh to a server via ssh username@server.domain ? Please note that I’m aware of this question and that is not doing what I want! If it helps the server has so many users in so many different groups and under the home directory there are some group directories and many user directories in those group directories. Edited: Please note that the result I get from /etc/passwd is not what I want and is as follows:
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh libuuid:x:100:101::/var/lib/libuuid:/bin/sh Debian-exim:x:101:103::/var/spool/exim4:/bin/false statd:x:102:65534::/var/lib/nfs:/bin/false sshd:x:103:65534::/var/run/sshd:/usr/sbin/nologin shelladmin:x:1000:1000:shelladmin. /home/shelladmin:/bin/bash messagebus:x:104:106::/var/run/dbus:/bin/false festival:x:105:29::/home/festival:/bin/false ntp:x:106:108::/home/ntp:/bin/false
This list doesn’t even include my own username! let alone the other 1000 users. Edited 2: So I chatted with Yaron a little and Here are some more info about the system:
-bash-4.2$ ls -lsa /etc/init.d/nis ls: cannot access /etc/init.d/nis: No such file or directory -bash-4.2$ ls -lsa /var/yp ls: cannot access /var/yp: No such file or directory if it helps, this is the putput of ls -lsa /var -bash-4.2$ ls -lsa /var total 48 4 drwxr-xr-x 12 root root 4096 Oct 25 2016 . 4 drwxr-xr-x 22 root root 4096 Oct 25 2016 .. 4 drwxr-xr-x 2 root root 4096 Oct 26 2016 backups 4 drwxr-xr-x 10 root root 4096 Oct 25 2016 cache 4 drwxr-xr-x 34 root root 4096 Oct 25 2016 lib 4 drwxrwsr-x 2 root staff 4096 May 7 2012 local 0 lrwxrwxrwx 1 root root 9 Oct 25 2016 lock -> /run/lock 4 drwxr-xr-x 9 root root 4096 Dec 10 06:25 log 4 drwxrwsr-x 2 root mail 4096 Jul 30 00:51 mail 4 drwxr-xr-x 2 root root 4096 Nov 21 2012 opt 0 lrwxrwxrwx 1 root root 4 Oct 25 2016 run -> /run 4 drwxr-xr-x 5 root root 4096 Oct 25 2016 spool 4 drwxrwxrwt 12 root root 4096 Dec 10 08:18 tmp 4 drwxr-xr-x 2 root root 4096 Feb 16 2013 www -bash-4.2$ getent passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh libuuid:x:100:101::/var/lib/libuuid:/bin/sh Debian-exim:x:101:103::/var/spool/exim4:/bin/false statd:x:102:65534::/var/lib/nfs:/bin/false sshd:x:103:65534::/var/run/sshd:/usr/sbin/nologin shelladmin:x:1000:1000:shelladmin. /home/shelladmin:/bin/bash messagebus:x:104:106::/var/run/dbus:/bin/false festival:x:105:29::/home/festival:/bin/false ntp:x:106:108::/home/ntp:/bin/false -bash-4.2$ cat /etc/nsswitch.conf # /etc/nsswitch.conf # # Example configuration of GNU Name Service Switch functionality. # If you have the `glibc-doc-reference' and `info' packages installed, try: # `info libc "Name Service Switch"' for information about this file. passwd: files ldap group: files ldap shadow: files ldap hosts: files dns networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis -bash-4.2$ cd /etc/sssd/ -bash: cd: /etc/sssd/: No such file or directory
How can I track who SSH’es into my linux machine?
I’m running Ubuntu 10.04. Is there a way I can get a daily report of who has logged onto the box, what time, and even — this may be asking too much — a report of the commands they used? This is a low-usage box and so I think this would be a nice way to see what activity is happening on it. Along these same lines, I heard it was not possible to track when things are done on the box via non-interactive shells, such as rsync or just remotely executing single commands via ssh. Is that true, or is there a way to log and track this as well?
6 Answers 6
The information of who logged in when is available in /var/log/auth.log (or other log files on other distributions). There are multiple log monitoring programs that can extract the information you configure as relevant. On any sane system, every user authentication is logged.
To log every command invocation (but not their arguments), use process accounting, provided by the acct package on Ubuntu. If the accounting subsystem is up and running, then lastcomm shows information about finished processes.
You can also use who or w to see who is currently logged in to the system, including SSH users.
You can also try entering the command last into the console, which displays all recent log-ins, including the user name they logged in under (but does not record if they changed their user name after logging in), IP, date, and duration of time logged in.
This command was mentioned by @jasonwryan in a comment here.
You can also modify the bash shell to do some rsylog.
Effectively, you setup rsyslog on a remote host to accept specific connections. Then modify the host shell on which you want to monitor — by compiling your version, with one which has the following enabled:
vi config-top.h #define SYSLOG_HISTORY #if defined (SYSLOG_HISTORY) # define SYSLOG_FACILITY LOG_USER # define SYSLOG_LEVEL LOG_INFO #endif
Once compiled with this enabled, you can replace bash with this version OR have users be logged into this one by redirecting their logins to it.
These 2 commands give the same result, I used them a lot to check who have logged in.
Note: 22.22.22.22 logged in 4 times, and still in there.
last root pts/0 22.22.22.22 Fri Apr 23 08:36 still logged in root pts/0 22.22.22.22 Fri Apr 23 08:29 - 08:36 (00:06) root pts/0 22.22.22.22 Fri Apr 23 08:27 - 08:29 (00:02) root pts/0 22.22.22.22 Fri Apr 23 08:25 - 08:27 (00:01) root pts/0 22.22.22.22 Thu Apr 15 11:51 - 12:00 (00:09) reboot system boot 5.4.0-51-generic Thu Apr 15 11:50 still running wtmp begins Thu Apr 15 11:50:06 2021
grep -E "Accepted publickey" /var/log/auth.log Apr 23 12:25:50 server sshd[59026]: Accepted publickey for root from 22.22.22.22 port 62685 ssh2: RSA SHA256:12 Apr 23 12:27:41 server sshd[59165]: Accepted publickey for root from 22.22.22.22 port 63240 ssh2: RSA SHA256:12 Apr 23 12:29:52 server sshd[60083]: Accepted publickey for root from 22.22.22.22 port 63860 ssh2: RSA SHA256:12 Apr 23 08:36:27 server sshd[63873]: Accepted publickey for root from 22.22.22.22 port 49318 ssh2: RSA SHA256:12