- Linux Logout user / Logoff User Commands
- logout command syntax and example
- Task: Linux logout all other users
- pkill command syntax
- Ubuntu Documentation
- Log out or switch users
- Lock the screen
- See Also
- Suspend
- See Also
- Power off or restart
- Лог файлы Linux по порядку
- Основные лог файлы
- И другие журналы
- Чем просматривать — lnav
Linux Logout user / Logoff User Commands
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | pkill |
Est. reading time | 2m |
a) pkill command – Kill processes by name.
b) kill command – terminate or signal a process.
c) logout command – Logout of a login shell. This command can be used by normal users to end their own session.
logout command syntax and example
If you are logged in as nixcraft user and just wanted to exit a login shell type the following command or hit CTRL+D:
$ logout
You will be logout of a login shell session or secure shell session.
Task: Linux logout all other users
If you would like to logout other users, you must login as root user. Next you need to use the pkill command.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
pkill command syntax
Warning : Do not kill root user or other system level user process. The following example, will kill all process on your server. Do not run the pkill for root user:
pkill -KILL -u root
To see list of logged in user type who or w command:
# who
OR
# w
To logout a user called raj, enter:
# pkill -KILL -u raj
OR
$ sudo pkill -KILL -u raj
See also
- For more information read our previous “Linux kill and logout users” tutorial.
- Man pages: pgrep(1)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Its one of things i hardly ever remember, never mind that i take the effort to write it down, but if you do need it a post like this is worth a million…
thanks
Works in OpenBSD 4.5 also. Great tip.
Whow, thanks for this posting! Just what I needed, highly appreciated!
Thanks, I was looking for such a command
i want to show the login time and logout time of all users then i will sort it according to their name help me pls…
Thanks a lot!
pkill worked fine in the GUI session!
Regards;
Thanks a lot.
I found here very usefull information about my quistions.
Best regards.
what’s the KILL flag do?
thanks, it works me to kill my locked sessions in a server
Hey, Thanks… This is exactly i requried.
Thanks you buddy….I have seen some of your posts regarding Linux commands. They are very useful for beginners like me.
if i logged twice from putty as same user root then if i want to logout one root user then how i would do it.As same user logged twice then in that case if i kill process of root -user then both will get kill…so is their is any ip based parameter to logout one root ?
Mark! do the work!
Wow. What bad information. Lets say you have root logged in under two sessions.
pkill -KILL -u root
That kills all processes owned by root. Meaning most system processes.
Let’s say you have one user in multiple sessions and that user is not root. Well, you just killed both sessions, even if that’s not what you wanted.
This is terrible advice, and the article should be called “Linux Kill All Processes by User”, and have nothing to do with “logging off”.
how The system should send an email alert when the root user has logged out from ssh/terminal.
@Scott, if you know the better command how to logout the user you could write it here, not just come and start wonder here how bed info that is!
How to identify which roles are running in Linux server by using Command line.
How to remotely GUI access linux gateway server .
I want to be able log multiple users off with a message without shutting down. Any thoughts?
ThanKs, comes handy when dude forgot to log out of his guest session here!
Yeah first time i found a usefull answer to my linux questions, : Ctrl + D
😀
Источник
Ubuntu Documentation
When you have finished using your computer, you can turn it off, suspend it (to save power), or leave it powered on and log out.
Log out or switch users
To let other users use your computer, you can either log out, or leave yourself logged in and just switch users. If you switch users, all of your applications will continue running, and everything will be where you left it when you log back in.
To Log Out or Switch User , click the system menu on the right side of the top bar, click your name and then choose the correct option.
The Log Out and Switch User entries only appear in the menu if you have more than one user account on your system.
Lock the screen
If you’re leaving your computer for a short time, you should lock your screen to prevent other people from accessing your files or running applications. When you return, you will see the lock screen . Enter your password to log back in. If you don’t lock your screen, it will lock automatically after a certain amount of time.
To lock your screen, click the system menu on the right side of the top bar and select Lock from the menu.
When your screen is locked, other users can log in to their own accounts by clicking Log in as another user at the bottom right of the login screen. You can switch back to your desktop when they are finished.
See Also
- Automatically lock your screen — Prevent other people from using your desktop when you go away from your computer.
- The screen locks itself too quickly — Change how long to wait before locking the screen in the Privacy settings.
Suspend
To save power, suspend your computer when you are not using it. If you use a laptop, the system, by default, suspends your computer automatically when you close the lid. This saves your state to your computer’s memory and powers off most of the computer’s functions. A very small amount of power is still used during suspend.
To suspend your computer manually, click the system menu on the right side of the top bar, expand Power Off / Log Out , and select Suspend .
See Also
- Set up automatic suspend — Configure your computer to suspend automatically.
- Use less power and improve battery life — Tips to reduce the power consumption of your computer.
- What happens when I suspend my computer? — Suspend sends your computer to sleep so it uses less power.
Power off or restart
If you want to power off your computer entirely, or do a full restart, click the system menu on the right side of the top bar, expand Power Off / Log Out , and select Power Off… . A dialog will open offering you the options to either Restart or Power Off .
If there are other users logged in, you may not be allowed to power off or restart the computer because this will end their sessions. If you are an administrative user, you may be asked for your password to power off.
You may want to power off your computer if you wish to move it and do not have a battery, if your battery is low or does not hold charge well. A powered off computer also uses less energy than one which is suspended.
Источник
Лог файлы Linux по порядку
Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе Linux, который никогда не читал лог файлы. Операционная система и работающие приложения постоянно создают различные типы сообщений, которые регистрируются в различных файлах журналов. Умение определить нужный файл журнала и что искать в нем поможет существенно сэкономить время и быстрее устранить ошибку.
Журналирование является основным источником информации о работе системы и ее ошибках. В этом кратком руководстве рассмотрим основные аспекты журналирования операционной системы, структуру каталогов, программы для чтения и обзора логов.
Основные лог файлы
Все файлы журналов, можно отнести к одной из следующих категорий:
Большинство же лог файлов содержится в директории /var/log .
- /var/log/syslog или /var/log/messages содержит глобальный системный журнал, в котором пишутся сообщения с момента запуска системы, от ядра Linux, различных служб, обнаруженных устройствах, сетевых интерфейсов и много другого.
- /var/log/auth.log или /var/log/secure — информация об авторизации пользователей, включая удачные и неудачные попытки входа в систему, а также задействованные механизмы аутентификации.
- /var/log/dmesg — драйвера устройств. Одноименной командой можно просмотреть вывод содержимого файла. Размер журнала ограничен, когда файл достигнет своего предела, старые сообщения будут перезаписаны более новыми. Задав ключ —level= можно отфильтровать вывод по критерию значимости.
- /var/log/alternatives.log — Вывод программы update-alternatives , в котором находятся символические ссылки на команды или библиотеки по умолчанию.
- /var/log/anaconda.log — Записи, зарегистрированные во время установки системы.
- /var/log/audit — Записи, созданные службой аудита auditd .
- /var/log/boot.log — Информация, которая пишется при загрузке операционной системы.
- /var/log/cron — Отчет службы crond об исполняемых командах и сообщения от самих команд.
- /var/log/cups — Все, что связано с печатью и принтерами.
- /var/log/faillog — Неудачные попытки входа в систему. Очень полезно при проверке угроз в системе безопасности, хакерских атаках, попыток взлома методом перебора. Прочитать содержимое можно с помощью команды faillog .
- var/log/kern.log — Журнал содержит сообщения от ядра и предупреждения, которые могут быть полезны при устранении ошибок пользовательских модулей встроенных в ядро.
- /var/log/maillog/ или /var/log/mail.log — Журнал почтового сервера, используемого на ОС.
- /var/log/pm-powersave.log — Сообщения службы экономии заряда батареи.
- /var/log/samba/ — Логи файлового сервера Samba , который используется для доступа к общим папкам Windows и предоставления доступа пользователям Windows к общим папкам Linux.
- /var/log/spooler — Для представителей старой школы, содержит сообщения USENET. Чаще всего бывает пустым и заброшенным.
- /var/log/Xorg.0.log — Логи X сервера. Чаще всего бесполезны, но если в них есть строки начинающиеся с EE, то следует обратить на них внимание.
Для каждого дистрибутива будет отдельный журнал менеджера пакетов.
- /var/log/yum.log — Для программ установленных с помощью Yum в RedHat Linux.
- /var/log/emerge.log — Для ebuild -ов установленных из Portage с помощью emerge в Gentoo Linux.
- /var/log/dpkg.log — Для программ установленных с помощью dpkg в Debian Linux и всем семействе родственных дистрибутивах.
И немного бинарных журналов учета пользовательских сессий.
- /var/log/lastlog — Последняя сессия пользователей. Прочитать можно командой last .
- /var/log/tallylog — Аудит неудачных попыток входа в систему. Вывод на экран с помощью утилиты pam_tally2 .
- /var/log/btmp — Еже один журнал записи неудачных попыток входа в систему. Просто так, на всякий случай, если вы еще не догадались где следует искать следы активности взломщиков.
- /var/log/utmp — Список входов пользователей в систему на данный момент.
- /var/log/wtmp — Еще один журнал записи входа пользователей в систему. Вывод на экран командой utmpdump .
И другие журналы
Так как операционная система, даже такая замечательная как Linux, сама по себе никакой ощутимой пользы не несет в себе, то скорее всего на сервере или рабочей станции будет крутится база данных, веб сервер, разнообразные приложения. Каждое приложения или служба может иметь свой собственный файл или каталог журналов событий и ошибок. Всех их естественно невозможно перечислить, лишь некоторые.
- /var/log/mysql/ — Лог базы данных MySQL.
- /var/log/httpd/ или /var/log/apache2/ — Лог веб сервера Apache, журнал доступа находится в access_log , а ошибки — в error_log .
- /var/log/lighthttpd/ — Лог веб сервера lighttpd.
В домашнем каталоге пользователя могут находится журналы графических приложений, DE.
/.xsession-errors — Вывод stderr графических приложений X11.
/.xfce4-session.verbose-log — Сообщения рабочего стола XFCE4.
Чем просматривать — lnav
Почти все знают об утилите less и команде tail -f . Также для этих целей сгодится редактор vim и файловый менеджер Midnight Commander. У всех есть свои недостатки: less неважно обрабатывает журналы с длинными строками, принимая их за бинарники. Midnight Commander годится только для беглого просмотра, когда нет необходимости искать по сложному шаблону и переходить помногу взад и вперед между совпадениями. Редактор vim понимает и подсвечивает синтаксис множества форматов, но если журнал часто обновляется, то появляются отвлекающие внимания сообщения об изменениях в файле. Впрочем это легко можно обойти с помощью .
Недавно я обнаружил еще одну годную и многообещающую, но слегка еще сыроватую, утилиту — lnav, в расшифровке Log File Navigator.
Установка пакета как обычно одной командой.
Навигатор журналов lnav понимает ряд форматов файлов.
- Access_log веб сервера.
- CUPS page_log
- Syslog
- glog
- dpkg.log
- strace
- Произвольные записи с временными отметками
- gzip, bzip
- Журнал VMWare ESXi/vCenter
Что в данном случае означает понимание форматов файлов? Фокус в том, что lnav больше чем утилита для просмотра текстовых файлов. Программа умеет кое что еще. Можно открывать несколько файлов сразу и переключаться между ними.
Программа умеет напрямую открывать архивный файл.
Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу . Это с моего syslog-а.
Кроме этого поддерживается подсветка синтаксиса, дополнение по табу и разные полезности в статусной строке. К недостаткам можно отнести нестабильность поведения и зависания. Надеюсь lnav будет активно развиваться, очень полезная программа на мой взгляд.
Источник