Linux close established connection

How to kill a TCP connection using netstat

Linux: How to kill a TCP connection using netstat?

You cannot kill a TCP connection using netstat utility. netstat is use for

  • Display network connections
  • Routing tables
  • Interface statistics
  • Masquerade connections
  • Multicast memberships
  • And much more

However Linux support two other commands or utility that can be used to kill a TCP connection.

tcpkill command

Use tcpkill command to kill specified in-progress TCP connections. It is useful for libnids-based applications which require a full TCP 3-whs for TCB creation.

Syntax:

Examples:

tcpkill -i eth0 port 21

(b) Kill all all packets arriving at or departing from host 192.168.1.2 (host12.nixcraft.com)

tcpkill host 192.168.1.2

tcpkill host host12.nixcraft.com

(c) To kill all IP packets between 192.168.1.2 and any host except 192.168.1.111, type the following:

tcpkill ip host 192.168.1.2 and not 192.168.1.111

Since tcpkill expressions are based upon tcpdump command’s filter expression, it is recommended that you read options with expression and examples.

cutter command

Cutter is an open source program that allows Linux firewall administrators to abort TCP/IP connections routed over Linux based firewall. It works on Linux router only. We have already covered examples of cutter here.

Источник

Рабочий метод разрыва конкретного активного соединения из командной строки linux (drop/kill/cut/close ESTABLISHED connection)

Иногда бывает необходимо принудительно разорвать активное соединение. Самый распространенный способ:

netstat -na
kill PID

Проблема в том, что один воркер может одновременно обслуживать несколько соединений, поэтому правильнее будет убить соединение а не воркер. Для этого на многих форумах рекомендуют использовать tcpkilll, cutter или awk+hping3. Однако, хоть эти утилиты и находятся в официальных репозиториях, мне не удалось заставить их разрывать соединения.

После продолжительных поисков был обнаружен perl скрипт killcx, разрывающий соединение по удаленному хосту и порту.

killcx 94.133.119.242:4403

[PARENT] checking connection with [94.133.119.242:4403]
[PARENT] found connection with [78.220.184.126:80] (ESTABLISHED)
[PARENT] forking child
[CHILD] interface not defined, will use [eth0]
[CHILD] setting up filter to sniff ACK on [eth0] for 5 seconds
[CHILD] hooked ACK from [77.220.184.126:80]
[CHILD] found AckNum [3091573605] and SeqNum [3105164779]
[CHILD] sending spoofed RST to [78.220.184.126:80] with SeqNum [3091573605]
[CHILD] sending RST to remote host as well with SeqNum [3105164779]
[CHILD] all done, sending USR1 signal to parent [13723] and exiting
[PARENT] received child signal, checking results.
=> success : connection has been closed !

Читайте также:  Изменение пароля root kali linux

Для его работы требуется целый набор библиотек.

apt-get install \
libpcap0.8 \
libpcap-dev \
libnet-pcap-perl \
libyaml-perl \
libyaml-dev \
libyaml-0-1 \
-y

cpan -i \
Net::RawIP \
NetPacket::Ethernet

Источник

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.

Читайте также:  Windows form chart control

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.

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!!

Источник

Close established TCP connection on Linux

I am not able to find an answer to a simple thing I will try to achive: once a tcp connection is established to my linux server, let’s say ssh / tcp 22 or x11 / tcp 6000 display -> how do I close this connection without killing the process (sshd / x11 display server). I saw also some suggestoin to use iptables, but it does not work for me, the connection is still visible in netstat -an. would be good if someone can point me to the right direction.

what I tried so far

Thanks in adavnce DJ

1 Answer 1

Ok, I found at least one solution (killcx) which is working. Maybe we will be able to find an easier solution. Also, i saw the comment from «zb» — thanks — which might also work, but I was not able to find a working syntax, since this tool seems to be really useful but complex. So here is an example how to work with the 1. solution which is working for me:

Читайте также:  Uxstyle windows 10 как пользоваться

killcx can be found here: http://killcx.sourceforge.net/ it «steals» the connection from the foreign host (192.168.0.77) and close it. So that solution is working fine, but to complex to setup quickly if you are under stress. Here are the required packages:

however, would be good to have an easier solution.

Not the answer you’re looking for? Browse other questions tagged linux sockets tcp 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.

Источник

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.

Источник

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