- How to disconnect idle ssh session or keep idle ssh session active in Linux
- What is an idle SSH session?
- Disconnect idle SSH session (ssh close connection after sometime)
- Keep idle SSH session active (ClientAliveInterval & ClientAliveCountMax)
- Related Posts
- 🐧 Как убить сессии пользователей на Linux
- Как посмотреть активные сессии ssh?
- 1) Как убить пользовательские сессии в Linux с помощью команды pkill
- В чем разница между tty и pts?
- 2) Как убить пользовательские сессии в Linux с помощью команды Killall
- 3) Как убить пользовательские сессии в Linux с помощью команды Kill
- How to close this ssh tunnel? [closed]
- 3 Answers 3
- Close ssh tunnel without root and without killing all other ssh connections
- How do I exit an SSH connection?
- 7 Answers 7
How to disconnect idle ssh session or keep idle ssh session active in Linux
Table of Contents
How to disconnect idle SSH session? Linux terminate ssh session. Linux SSH close connection after sometime. ssh idle timeout. keep idle ssh session active in Linux. disconnect idle ssh session timeout. ssh close session timeout. ssh timeout. ssh idle timeout Linux. Autodisconnect idle ssh session Linux. Kill inactive ssh session automatically in Linux. Automatically disconnect idle ssh session in Linux. terminate inactive ssh session in Unix. ssh close connection after time. how to disconnect from ssh
What is an idle SSH session?
Here we mean that a ssh connection was made between a host and a client but there has been no activity on this connection by the user and is considered idle. Here although the ssh session is not in stuck state. You can list all the active ssh connections and then check the idle time for individual source host.
In this article I will share the trick to disconnect an idle SSH session automatically and also to avoid getting disconnected for an idle SSH session. In my last article I had shared the steps and examples to terminate an unresponsive SSH session in Linux.
The trick to disconnect idle SSH session is to use below two arguments with proper values to achieve both the scenario i.e. to disconnect an idle SSH session and also to make sure your SSH session does not gets disconnected when idle
But before disconnecting any such ssh session it is also important to know the currently active SSH sessions on your Linux node. There are various ssh authentication methods using which you can connect to Linux nodes with or without password depending upon your requirement.
From the man page
Disconnect idle SSH session (ssh close connection after sometime)
To disconnect idle SSH session i.e. to ssh close connection after some time make sure ClientAliveCountMax is 0. Because when is 0, sshd will not send client alive messages and ssh close connection after sometime if client is inactive for time period as provided with ClientAliveInterval .
Look out for the current assigned value of ClientAliveCountMax in /etc/ssh/sshd_config on node2
Next assign a null value for ClientAliveCountMax in /etc/ssh/sshd_config on the client node which for me is node2
Now we should also assign a time interval for which the session will be allowed to be active when idle. This can be defined using ClientAliveInterval again in the /etc/ssh/sshd_config file on my client node i.e. node2
For the sake of this article I am giving 10 seconds as this interval period. You can change this value based on your requirement.
Restart the sshd service and check the status
Next let us initiate the SSH session from node1 to node2
Monitor the idle SSH session on node2 using ‘ w ‘ to make sure ssh close connection after some time when idle
As you see, after 10 seconds of idle ssh session from node1 to node2, the SSH close connection after sometime automatically. Below debug message is seen on my node1
So our idle SSH session gets disconnected automatically after waiting for 10 seconds.
Keep idle SSH session active (ClientAliveInterval & ClientAliveCountMax)
Now above I showed you the trick to make sure your idle SSH session gets automatically disconnected. Now if this is becoming a problem for you then you can increase the value of ClientAliveCountMax to a non-zero value.
Additionally you can also use TCPKeepAlive in your sshd_config on the client node.
From the man page of sshd_config:
For the sake of this article I will use below values
Here sshd will send messages, called Client Alive Messages, through the encrypted channel to request a response from client if client is inactive for 5 minutes. The sshd daemon will send these messages max three times. If this threshold is reached while Client Alive Messages are being sent, sshd will disconnect the idle ssh session on the client.
These values can also be used in combination with ServerAliveInterval and ServerAliveCountMax to automatically disconnect a hung or unresponsive SSH session.
Next restart the sshd service and check the status
Lastly I hope the steps from the article to disconnect idle SSH session, ssh close connection after sometime or to avoid idle SSH session getting disconnected on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник
🐧 Как убить сессии пользователей на Linux
Иногда вам может потребоваться убить несколько пользовательских сессий в системе Linux.
Например, вам нужно запустить задание, для которого все пользователи должны выйти из системы.
Другой пример – вы наблюдаете много сеансов ssh в своей системе и хотите убить их всех.
Если да, то как это сделать?
Есть несколько способов добиться этого результата.
Я покажу вам несколько способов, а вы сможете выбрать тот, который соответствует вашим потребностям
Как посмотреть активные сессии ssh?
Вы можете увидеть активные сеансы ssh, запустив команду w на Linux.
1) Как убить пользовательские сессии в Linux с помощью команды pkill
Вы можете напрямую убить сеанс ssh определенного пользователя, используя номер сеанса tty.
Вы можете увидеть номер сеанса 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 close this ssh tunnel? [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 8 years ago .
But now I don’t know what I actually did. Does this command affect anything on the server? And how do I close this tunnel, because now I can’t use my local mysql properly.
I use OSX Lion and the server runs on Ubuntu 11.10.
3 Answers 3
Assuming you ran this command: ssh -f user@mysql-server.com -L 3306:mysql-server.com:3306 -N as described in the post you linked.
A breakdown of the command:
- ssh : that’s pretty self-explanatory. Invokes ssh .
-f : (From the man ssh page)
Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background.
Essentially, send ssh to background once you’ve entered any passwords to establish the connection; it gives the shell prompt back to you at localhost rather than logging you in to remote-host .
-L 3306:mysql-server.com:3306 : This is the interesting bit. -L (from the man ssh page):
[bind_address:]port:host:hostport Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side.
So -L 3306:mysql-server.com:3306 binds the local port 3306 to the remote port 3306 on host mysql-server.com .
When you connect to local port 3306 , the connection is forwarded over the secure channel to mysql-server.com . The remote host, mysql-server.com then connects to mysql-server.com on port 3306 .
-N : don’t execute a command. This is useful for «just forwarding ports» (quoting the man page).
Does this command affect anything on the server?
Yes, it establishes a connection between localhost and mysql-server.com on port 3306.
And how do I close this tunnel.
If you’ve used -f , you’ll notice that the ssh process you’ve opened heads into the background. The nicer method of closing it is to run ps aux | grep 3306 , find the pid of the ssh -f . -L 3306:mysql-server.com:3306 -N , and kill
. (Or maybe kill -9
; I forget if just kill works). That has the beautiful benefit of not killing all your other ssh connections; if you’ve got more than one, re-establishing them can be a slight . pain.
. because now I can’t use my local mysql properly.
This is because you’ve effectively «captured» the local mysql process and forwarded any traffic that attempts to connect to it, off to the remote mysql process. A much nicer solution would be to not use local port 3306 in the port-forward. Use something that’s not used, like 33060. (Higher numbers are generally less used; it’s pretty common to port-forward a combination like this: «2525->25», «8080->80», «33060->3306» or similar. Makes remembering slightly easier).
Источник
Close ssh tunnel without root and without killing all other ssh connections
I have an ssh tunnel listening on a local port, say 8888, opened from a remote machine with ssh -R 8888:localhost:80 myuser@myhost . I need to write a script for «myuser» on «myhost» that will close this tunnel.
The script will be executed by «myuser» on «myhost». It won’t be executed by the root nor it will be able to sudo.
One approach wound be to find PID of the process listening on 8888 using lsof or netstat and then kill the process. However, both lsof and netstat refuse to give me the PID without going sudo. With netstat I just get — instead of «PID/Program name» without sudo.
Is there a way to find out PID of the process listening on a given port without the root priviledges? The process listening on this port is running under the same user we are. Or is there any other way to close the ssh tunnel from outside of it?
Note that using the ssh escape sequence to reset the connection is not a solution as we are not in the tunnel. Our script needs to run separately of the tunnel on the same host by the same user.
Also note that just running killall sshd is not a solution as it will kill all other ssh connections not just this one.
This question is not a duplicate of many similar questions, because all of their accepted answers I have found requires root priviledges, or just kills all ssh connections.
The host «myhost» is running Ubuntu 12.04.5.
Edit: Discussion summary as requested by @Jakuje:
@Patrick suggested an approach to use setuid or to modify /etc/sudoers to allow the user to run the script with root priviledges without having full sudo. Although, for setuid we’d need to write a binary instead of the script. However, allowing the user to run the script with root priviledges could be a potential security risk. And still this solution does not cover the case the user has no root access at all, so he cannot modify /etc/sudoers . If @Patrick writes this as an answer I’ll definitely upvote it, but I won’t mark it accepted, yet.
@EricRenouf found out that sshd does chown the socket to the user so the user can’t use /proc/*/fd to find the process that has the socket. Which is probably why neither lsof nor netstat show it.
As @EricRenouf found there is probably no way to get sshd PID by the opened socket port number nor inode. But I’m curious if there isn’t any other trick how to find this sshd PID or how to tell it to close the connection. Maybe somehow directly with sshd.
Источник
How do I exit an SSH connection?
I’m connecting to a server via SSH to send a message to a socket server using a command like:
After the connection is established and I write the message and send it I can’t exit the text mode. I’m only allowed to enter more text and that’s it.
Is there a command or a key combination that allows me to return to command mode?
7 Answers 7
How do I exit an SSH connection?
- closing the shell session will usually exit, for example:
- with the shell builtin command, exit , followed by Enter , or
- Ctrl — d , (end-of-file)
- in the case where you have a bad connection and the shell is unresponsive, hit the Enter key, then type
. and ssh should immediately close and return you to your command prompt.
The first option should be intuitive, but how do we know the latter option?
We could learn this information from a careful reading of the man page.
gives us the SSH documentation, which has the following section on escape characters:
There is nothing special about exit to ssh, it’s just a way to exit the shell, which results in closing the ssh session:
Citing and quoting reference sources is to provide further evidence for what would otherwise be a perhaps demonstrable assertion of fact, as well as inform the user where more relevant information may be stored.
You want to know that you’re doing semantically the correct thing, as well as knowing that it works.
You don’t want to learn to invoke as a feature something that is documented as a bug and then later «fixed.» Doing the semantically correct thing will continue to be supported.
Источник