Close all sessions linux

Linux / UNIX: Kill User Session

H ow do I kill all users session under Linux or UNIX operating system using command prompt?

You need to use the pkill command which will look up or signal processes based on name. It can send the specified signal (such as KILL) to each process. Open a command-line terminal (select Applications > Accessories > Terminal), and then type the following commands as root user:
$ sudo pkill -9 -u username
OR
# pkill -9 -u username
To list all users pids, enter:
$ pgrep -u username
OR better try:
$ ps -fp $(pgrep -d, -u userNameHere)

Example: Kill Unix / Linux User Session

In this example, list all process owned by a user called lighttpd, enter:
# ps -fp $(pgrep -d, -u lighttpd)
Sample outputs:

To kill all process owned by lighttpd user, enter:
# pkill -9 -u lighttpd
Please note that above command will also logout lighttpd user.

  • 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

Getting help

Anytime you need assistance with Linux / UNIX pkill command-line, turn to the man page first. It will give you detailed information, parameters and switches for pkill command. For example, man pkill opens the man page for the pkill command:
$ man pkill

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

🐧 Как убить сессии пользователей на Linux

Иногда вам может потребоваться убить несколько пользовательских сессий в системе Linux.

Например, вам нужно запустить задание, для которого все пользователи должны выйти из системы.

Другой пример – вы наблюдаете много сеансов ssh в своей системе и хотите убить их всех.

Если да, то как это сделать?

Есть несколько способов добиться этого результата.

Я покажу вам несколько способов, а вы сможете выбрать тот, который соответствует вашим потребностям

Как посмотреть активные сессии ssh?

Вы можете увидеть активные сеансы ssh, запустив команду w на Linux.

1) Как убить пользовательские сессии в Linux с помощью команды pkill

Вы можете напрямую убить сеанс ssh определенного пользователя, используя номер сеанса tty.

Читайте также:  Do all tablets have windows

Вы можете увидеть номер сеанса tty из вывода команды w.

В моем случае я собираюсь убить сеанс пользователя «magi», этот пользователь подключен к серверу с помощью pts/5, поэтому команда будет следующей:

Хотите понять разницу между tty и pts?

В чем разница между tty и pts?

  • TTY: tty означает Teletypewriter. Он напрямую связан с системой как клавиатура / мышь или последовательное соединение с устройством (например, консоль в вашей системе).
  • PTS: pts обозначает pseudo terminal slave. Это терминальное устройство, которое эмулируется другой программой (например, сессией ssh в вашей системе).

2) Как убить пользовательские сессии в Linux с помощью команды Killall

Вы можете убить пользовательский сеанс следующим образом с помощью команды killall.

В моем случае я убиваю сеанс пользователя «magesh» с помощью ключа «-u».

3) Как убить пользовательские сессии в Linux с помощью команды Kill

Кроме того, вы можете убить пользовательский сеанс с помощью команды kill.

Этот метод потребует нескольких дополнительных шагов по сравнению с вышеупомянутыми двумя методами, потому что вы не сможете убить сессию напрямую.

Сначала найдите номер tty сеанса пользователя из вывода команды w.

Как только он у вас есть, найдите PID соответствующего сеанса tty с помощью команды PS.

Наконец убейте идентификатор процесса сеанса.

Источник

How to Kill user sessions in Linux

Sometimes we might need to kill a user session in Linux based on requests, which can be done by sending SIGNALS with kill command.

We need to send one of the following signals based on our requirement, to kill a process in Linux.

What is SIGTERM?

The ‘SIGTERM’ is a signal used for graceful termination of a process, which can be ignored or blocked sometimes in case a process is in busy state (i.e. waiting for disk I/O).

However by default, a kill command sends the SIGTERM signal along with the request.

What is SIGKILL?

The ‘SIGKILL’ signal is used for instant termination of process, along with its child processes.

This is a brutal way to kill a process & can be opted as a final option.

Use ‘SIGKILL’ or ‘9’ with the kill command to terminate a process.

For instance:

  • All users need to be logged out of system before we trigger a monthly job
  • To kill multiple ssh sessions running in system
  • One user session went unresponsive & needs to be killed

This article further covers the list of commands that can be used to perform this operation.

To view list of active ssh sessions, use ‘w’ command.

1) Kill user session using pkill command

TTY session can be used to kill a specific user ssh session & to identify tty session, please use ‘w’ command.

For example: To kill the user “magi”, connected to the server with ‘pts/2’, use the command below:

To understand the difference between tty and pts, refer the details below:

  • TTY (Teletypewriter): is directly connected to the system as a keyboard/mouse or a serial connection to the device (i.e. the console on your system).
  • PTS (pseudo terminal slave): is a terminal device, which is emulated by another program (i.e. ssh session to your system).

2) Terminating user session, using Killall command

User session can be killed using the ‘killall’ command.

For example, to terminate user “magesh”, use “-u” switch, as shown below:

3) How to terminate user session, using Kill command

This process needs additional efforts to terminate a user, using kill command when compared to previous two steps.

Читайте также:  Веб камера под линукс

Before we proceed to kill the user session, we must find the tty session from ‘w’ command, as shown below:

Once we identify the tty session, locate the PID of corresponding tty session using ps command:

Now, terminate the process id of the user session:

Conclusion:

This article covers multiple ways to terminate user sessions. We hope this topic was apt to your requirement.

Please fill in our comment section with your valuable feedback & suggestions.

Источник

kill a screen session

I’m trying to kill a screen session. I noticed a lot of other related questions, but none of those answers are working for me. I am trying to kill the following session:

Now I am in the session. According to the documentation:

I am supposed to press «control a» and then «control \». I do that and nothing happens.

Another solution said to press Ctrl + a and type :quit. However, again it doesn’t do anything. In fact, pressing control + a , absolutely nothing happens afterwards except a message «No Other Window»

10 Answers 10

first you need to re attach to the screen session
screen -r 23520 as you have done. Then press ctrl + a and then a k and press y when it asks if you really want to kill the session

  1. Identify the name of the session:
  1. Close a session:
  • Rationale: -X = Execute command, -S session PID to execute on
  • Example: screen -XS 20411 quit
  • Source: innaM’s Answer

This command will kill all screen sessions, if that is desired:

So with all those official suggestions, I have one here that i feel is easier, and just as effective, and kind of more straight forward:

Who wants to go into an unknown and un-needed screen just to press in a couple commands that most might barely remember? This avoids going into it at all, and kills it straight off.

Plus, if you have more than one, this will take them all in one fell swoop.

This will kill all the detached screens:

This will kill all screens, attached or detached

Like you, I wanted to kill my screen session and found the documentation unhelpful. Convinced that there must be a keyboard shortcut, I found that
ctrl + a then \
works

I then get the prompt: «Really quit and kill all your windows [y\n]»

I am not sure why the documentation says ctrl + a then ctrl + \ . That doesn’t do anything for me.

I encountered this problem when updating screen. The screen command would hang when attempting to reattach the session, regardless of how many -D or -R I added to the command. However, screen -ls conveniently provides the pid of the session, allowing you to intervene using the following:

(This is similar to Brian Thomas’s answer, but his will kill all running screen sessions, which may not be what you want if you have multiple screens open but only one misbehaving.)

You can find the process id of the attached running screen. I found it same as the session id which you can get by command:
screen -ls
And you can use following command to kill that process:
kill [sessionId] or
sudo kill [sessionId]
You can kill the screen even if it is attached on some other terminal window.

we can also use the exit command to terminating screen

Press ctrl+d to kill screen window. Repeat this until you kill all screen windows. Once you ran out all windows screen will kill the session and terminating. Shortest solution if you not having many windows

Читайте также:  Astra linux canon mf3010

You can just simply type exit while in a recording mode, I found out it to be most convenient as it directly exits the running screen.

Not the answer you’re looking for? Browse other questions tagged gnu-screen or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Terminate dropped SSH sessions

My SSH sessions seem to be dropping though that is not my major problem — the major problem is my previous sessions are still alive, worse yet one of them is running visudo preventing me from accessing it!

who shows a number of sessions all except my current one I know have disconnected, how can I terminate the old ones so the release their resources?

3 Answers 3

To solve the immediate problem, that the sudoers file is locked, you can simply delete the lock file. It will usually be `/etc/sudoers.tmp»; check the man page for visudo to verify. If you delete the lock file, you can run visudo again.

To delete all sessions which are still left hanging, first find out the pid of your own current session. Then, if your own pid is 12345, do

You may want to do it without the final | sh first just to check the PIDs you’re planning on killing.

If you’re on Linux, you can instead use

to kill your oldest SSH session. Continue doing that until your current session is the only one left.

You might also want to set ServerAliveInterval 15 in your .ssh/config to send a keepalive message every 15 seconds when no data has been sent. man ssh_config for more information.

This will kill sessions hanging for 2+ days. It could be put as a cron.

This will kill all but your (last active session). Run this from terminal.

If you list processes so that you see their command and arguments (like e.g. ps -f from procps does), you should see then sshd processes called e.g.:

The terminal ( pts/7 ) is the key part here — if you compare it with your current terminal ( tty ), you can see which is your active session. There are of course other ways to do that (like looking at the PID of the currently running shell and locating that one in the process tree), but this is likely the easiest one. You can then use something along these lines:

You can then feed the PIDs to kill with xargs but always make sure you do not kill the main sshd process which handles new connections.

On a related note, be advised that quite generally parsing ps output is error-prone (especially across various systems) due to the variability of its output formats (here mitigated to large extent by the use of -o pid= -o command= ).

Источник

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