- Shell linux how to close port code example
- Close established TCP connection on Linux
- How to kill a single TCP connection in Linux?
- Killing tcp connection in linux
- How to open serial port in linux without changing any pin?
- Рабочий метод разрыва конкретного активного соединения из командной строки linux (drop/kill/cut/close ESTABLISHED connection)
- Close established TCP connection on Linux
- 2 Answers 2
Shell linux how to close port code example
If you want to deal only with hanged connections (the other side is dead), there are various timeouts (TCP keepalive for example), which should automatically close such connections if configured properly on the system. The already mentioned method learns the SEQ number by passively sniffing on the network and waiting for valid packets of this connection to arrive.
Close established TCP connection on Linux
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:
netstat -anp | grep 22 output: tcp 0 0 192.168.0.82:22 192.168.0.77:33597 VERBUNDEN 25258/0 iptables -A INPUT -j DROP -s 192.168.0.77 (to prevent reconnect) perl killcx.pl 192.168.0.77:33597 (to kill the tcp connection)
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:
apt-get install libnetpacket-perl libnet-pcap-perl libnet-rawip-perl wget http://killcx.sourceforge.net/killcx.txt -O killcx.pl
however, would be good to have an easier solution.
tcpkill wont work, since it will only kill any new connection, it doesnt kill existing ESTABLISHED connections
heres how you remove an Established TCP connection
- find the PID of the process and the IP of the client connecting, lets say you are on serverA and someone is connecting from serverB root@A> netstat -tulpan | grep ssh | grep serverB
should see something like,
tcp 0 0 : : ESTABLISHED 221955/sshd
- use lsof utility to get the File Descriptor of this connection using the parent PID root@A> lsof -np 221995 | grep serverB IP
should see something like this
sshd 221955 17u IPv4 2857516568 0t0 TCP :->: (ESTABLISHED)
get the File Descriptor number (4th column) = 17u
- use GDB to shut down this connection, w/out killing sshd root@A> gdb -p 211955 —batch -ex ‘call shutdown(17u, 2)’
should see something similar,
0x00007f0b138c0b40 in __read_nocancel () from /usr/lib64/libc.so.6 $1 = 0 [Inferior 1 (process 211955) detached]
that TCP connection should now be closed
How to kill a process running on particular port in Linux?, I tried to close the tomcat using ./shutdown.sh from tomcat /bin directory. But found that the server was not closed properly. And thus I was unable to restart My tomcat is running on port 8080.. I want to kill the tomcat process running on 8080.I first want to have the list of processes running on a specific port (8080) in order to select which process to kill. Code samplestopProcessByPortNumber() «portStrLine=»$(netstat -ano | findstr LISTENING | findstr $port)»processId=»$(grep -oP ‘(\d+)(. *\d)’
How to kill a single TCP connection in Linux?
- Attach with gdb and call close() on the fd. You can map from addr/port to inode number via /proc/net/tcp and from inode number to FD inside the process with ls -la /proc/$pid/fd.
- Spoof a RST packet. You’ll need to generate it locally and guess the SEQ number somehow.
- Maybe setup an iptables rule to generate a RST on the next packet.
- Write a kernel module.
There doesn’t seem to be a well supported way to do this. It is likely that processes will crash if their FDs are unexpectedly closed anyway.
On linux kernel >= 4.9 you can use the ss command from iproute2 with key -K
ss -K dst client1.something dport = 49987
the kernel have to be compiled with CONFIG_INET_DIAG_DESTROY option enabled.
You can’t kill a single connection of a process.
But you could block it with iptables. So the connection can’t provide or receive data and the client will run in a timeout.
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 …
Killing tcp connection in linux
On linux kernel >= 4.9 you can use the ss command from iproute2 with key -K
ss -K dst 192.168.1.214 dport = 49029
the kernel have to be compiled with CONFIG_INET_DIAG_DESTROY option enabled.
Originally from: http://rtomaszewski.blogspot.sk/2012/11/how-to-forcibly-kill-established-tcp.html
To «kill» a socket, you must send a TCP reset packet. To send it (and be accepted by the other side), you must know the actual TCP sequence number.
1) The already mentioned tcpkill method learns the SEQ number by passively sniffing on the network and waiting for valid packets of this connection to arrive. Then it uses the learned SEQ number to send RSET packets to both sides. However if the connection is idle/hanged and no data flows, it won’t do anything and will wait forever.
2) Another method uses perl script called killcx (link to Sourceforge). This actively sends spoofed SYN packets and learns the SEQ number from the answer. It then sends RSET packets the same way as tcpkill .
Alternatively approach (based on what you want to achieve) is to use gdb debugger to attach to a process owning this socket/connection and issue close() syscall on its behalf — as detailed in this answer.
If you want to deal only with hanged connections (the other side is dead), there are various timeouts (TCP keepalive for example), which should automatically close such connections if configured properly on the system.
tcpkill might do it for you. In Ubuntu it is in the dsniff package.
$ sudo tcpkill -i wlan0 host 192.168.1.214
(or some other tcpdump like expression for what connection to kill).
How to kill a single TCP connection in Linux?, Attach with gdb and call close() on the fd. You can map from addr/port to inode number via /proc/net/tcp and from inode number to FD inside the process with ls -la /proc How do I prompt for Yes/No/Cancel input in a Linux shell script? 2066. How do I profile C++ code running on Linux? 1831. Who is listening …
How to open serial port in linux without changing any pin?
I have no idea why you’d want to do this, but this can be done pretty easily by modifying the linux kernel driver for your serial console so it doesn’t toggle RTS. For example, for the 8250-series driver in drivers/tty/serial/8250/ you could change every write to the MCR register (UART_MCR) to ensure that bit 1 (mask is UART_MCR_RTS) is never set.
Since it’s abstracted away in userspace, you’re out of luck if you want to do this without modifying the kernel driver.
Having the same problem, I’d give it a try by patching the ftdi_sio kernel driver. You just need to uncomment a small piece of code in ftdi_dtr_rts() like this:
static void ftdi_dtr_rts(struct usb_serial_port *port, int on) < . /* drop RTS and DTR */ if (on) set_mctrl(port, TIOCM_DTR /*| TIOCM_RTS*/); //and the RTS handshake line is not longer changed upon open() call. Note, that the uart than might not longer working with RTS/CTS hardware handshake, as long as your modified kernel driver is loaded. But you can still control the state of the RTS handshake line manually by calling e.g.:
int opins = TIOCM_RTS; ioctl(tty_fd, TIOCMBIC, &opins);
I'd tested this with the Ctrl+A+G command of picocom 2.3a, running Kubuntu 16.04 64 bit and Ftdi FT2232H based usb uart adapter.
You might find more details on this topic here.
A change in the DTR pin can be (eventually) avoided using the command line
This has the effect of making DTR turn on; and subsequently when the port is opened and closed, DTR is not affected.
And there is code there to do the same thing from python via termios , this can be done before opening the port via pyserial:
import termios path = '/dev/ttyACM0' # Disable reset after hangup with open(path) as f: attrs = termios.tcgetattr(f) attrs[2] = attrs[2] & ~termios.HUPCL termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
The OP was running this on a Raspberry Pi, but I just tried it on Linux Mint on x86_64, it worked. I don't know how RTS is affected.
The reason I find this useful, is for communication with an Arduino Nano - which has a USB-> serial chip on board - and normally the Arduino gets reset every time you open the serial port from linux (rising edge of DTR causes reset). For some applications, this is not a problem, but it's clearly useful to avoid this for other applications, and it's not so easy to remove that tiny capacitor from the Arduino which connects DTR to reset.
You will still get a single reset when the stty command is executed (after plugging in the USB cable). But at least you can then keep opening and closing the serial port after that without further resets.
Command line - How to close an open port in Ubuntu?, 6k 13 136 249. Add a comment. 32. for closing open port in ubuntu you can use below command. sudo kill $ (sudo lsof -t -i:3000) in place of 3000 you can specify your port number. lsof command will give information about file opened by process. -t : This flag specifies that lsof should produce terse output with …
Рабочий метод разрыва конкретного активного соединения из командной строки linux (drop/kill/cut/close ESTABLISHED connection)
Иногда бывает необходимо принудительно разорвать активное соединение. Самый распространенный способ:
Проблема в том, что один воркер может одновременно обслуживать несколько соединений, поэтому правильнее будет убить соединение а не воркер. Для этого на многих форумах рекомендуют использовать 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 !Для его работы требуется целый набор библиотек.
apt-get install \
libpcap0.8 \
libpcap-dev \
libnet-pcap-perl \
libyaml-perl \
libyaml-dev \
libyaml-0-1 \
-ycpan -i \
Net::RawIP \
NetPacket::EthernetClose 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
tcpkill: kills the process, not good for me iptables: does not close the established connection, but prevent further connections.
Attach to the process with a debugger, then call shutdown() followed by close() , or just close() , on the appropriate file descriptor. Then hope the process can handle that.
2 Answers 2
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:
netstat -anp | grep 22 output: tcp 0 0 192.168.0.82:22 192.168.0.77:33597 VERBUNDEN 25258/0 iptables -A INPUT -j DROP -s 192.168.0.77 (to prevent reconnect) perl killcx.pl 192.168.0.77:33597 (to kill the tcp connection)
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:
apt-get install libnetpacket-perl libnet-pcap-perl libnet-rawip-perl wget http://killcx.sourceforge.net/killcx.txt -O killcx.pl
however, would be good to have an easier solution.