Kill process that is taking specific port - bash

Is is possible to programatically select process that is taking a specific port (:3000 for example) and kill it ?
I do that by hand now by using
netstat -tp
and then I would check pid of a process and kill it using kill command.
I want to write a shell script that would do that automatically.

Depending on your system, your fuser command may be able to do this:
fuser -k [-<SIGNAL>] <port>/<proto>
fuser -n <proto> -k [-<SIGNAL>] <port>
Examples :
fuser -k 12345/tcp
fuser -n udp -k -KILL 23456
On the command line, you may also want to execute fuser -v <port>/<proto> first, to see what you are going to kill.

Related

How to ssh to a server and get CPU and memory details?

I am writing a shell script where i want to ssh to a server and get the cpu and memory details data of that displayed as a result. I’m using the help of top command here.
Script line:
ssh -q user#host -n “cd; top -n 1 | egrep ‘Cpu|Mem|Swap’”
But the result is
TERM environment variable is not set.
I had checked the same in the server by entering set | grep TERM and got result as TERM=xterm
Please someone help me on this. Many thanks.
Try using the top -b flag:
ssh -q user#host -n "cd; top -bn 1 | egrep 'Cpu|Mem|Swap'"
This tells top to run non-interactively, and is intended for this sort of use.
top need an environment. You have to add the parameter -t to get the result:
ssh -t user#host -n "top -n 1 | egrep 'Cpu|Mem|Swap'"
Got it..!! Need to make a small modification for the below script line.
ssh -t user#host -n "top -n 1 | egrep 'Cpu|Mem|Swap'"
Instead of -t we need to give -tt. It worked for me.
To execute command top after ssh’ing. It requires a tty to run. Using -tt it will enable a force pseudo-tty allocation.
Thanks stony for providing me a close enough answer!! :)

Bash script upd error

I execute my bash script PLCCheck as process
./PLCCheck &
PLCCheck
while read -r line
do
...
def_host=192.168.100.110
def_port=6002
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "OKConnection" | netcat -u -c $HOST $PORT
done < <(netcat -u -l -p 6001)
It listens on UDP Port 6001.
When I want to execute my second bash script SQLCheck as process that listens on UDP Port 4001
./SQLCheck &
SQLCheck
while read -r line
do
...
def_host=192.168.100.110
def_port=6002
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "OPENEF1" | netcat -u -c $HOST $PORT
done < <(nc -l -p 4001)
I got this error:
Error: Couldn't setup listening socket (err=-3)
Port 6001 and 4001 are open in the iptables and both scripts work as a single process. Why do I get this error?
I have checked the man page of nc. I think it is used on a wrong way:
-l Used to specify that nc should listen for an incoming connection rather
than initiate a connection to a remote host. It is an error to use this
option in conjunction with the -p, -s, or -z options. Additionally,
any timeouts specified with the -w option are ignored.
...
-p source_port
Specifies the source port nc should use, subject to privilege restrictions
and availability. It is an error to use this option in conjunction with the
-l option.
According to this one should not use -l option with -p option!
Try to use without -p, just nc -l 4001. Maybe this is the error...

How can I kill whatever process is using port 8080 so that I can vagrant up? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 11 months ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
On MacOSX, I'm using Packer to build a Vagrant box so I need to continually bring it up and tear it down. I'm attempting to 'vagrant up', and receive the standard error because the port is in use:
"Vagrant cannot forward the specified ports on this VM, since they would collide with some other application that is already listening on these ports. The forwarded port to 8080 is already in use on the host machine."
The solution seems simple enough: I just need to identify the process that is holding port 8080 open and kill that process, right?. It's not that easy.
If I run the command:
nmap localhost -p 8080
I receive the following output:
PORT STATE SERVICE
8080/tcp open http-proxy
If I run the following command:
top -o prt
The highest port in use in 1360
If I run the following command:
netstat -tulpn | grep :8080
I receive:
netstat: n: unknown or uninstrumented protocol
If I run the following command:
lsof -i :8080
I receive no output
If I restart my computer, the port is now available and I can now 'vagrant up'.
How can I kill whatever process is using port 8080 so that I can vagrant up without restarting my computer?
This might help
lsof -n -i4TCP:8080
The PID is the second field in the output.
Or try:
lsof -i -P
Fast and quick solution:
lsof -n -i4TCP:8080
PID is the second field. Then, kill that process:
kill -9 PID
Less fast but permanent solution
Go to /usr/local/bin/ (Can use command+shift+g in finder)
Make a file named stop. Paste the below code in it:
#!/bin/bash
touch temp.text
lsof -n -i4TCP:$1 | awk '{print $2}' > temp.text
pidToStop=`(sed '2q;d' temp.text)`
> temp.text
if [[ -n $pidToStop ]]
then
kill -9 $pidToStop
echo "Congrates!! $1 is stopped."
else
echo "Sorry nothing running on above port"
fi
rm temp.text
Save this file.
Make the file executable chmod 755 stop
Now, go to terminal and write stop 8888 (or any port)
In case above-accepted answer did not work, try below solution.
You can use it for port 8080 or for any other ports.
sudo lsof -i tcp:3000
Replace 3000 with whichever port you want. Run below command to kill that process.
sudo kill -9 PID
PID is process ID you want to kill.
Below is the output of commands on mac Terminal.
Use the following command:
lsof -n -i4TCP:8080 | awk '{print$2}' | tail -1 | xargs kill -9
The process id of port 8080 will be picked and killed forcefully using kill -9.
I needed to kill processes on different ports so I created a bash script:
killPort() {
PID=$(echo $(lsof -n -i4TCP:$1) | awk 'NR==1{print $11}')
kill -9 $PID
}
Just add that to your .bashrc and run it like this:
killPort 8080
You can pass whatever port number you wish
To script this:
pid=$(lsof -ti tcp:8080)
if [[ $pid ]]; then
kill -9 $pid
fi
The -t argument makes the output of lsof "terse" which means that it only returns the PID.
sudo lsof -i:8080
By running the above command you can see what are all the jobs running.
kill -9 <PID Number>
Enter the PID (process identification number), so this will terminate/kill the instance.
I needed to run this command
sudo lsof -i :80 # checks port 8080
Then i got
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
acwebseca 312 root 36u IPv4 0x34ae935da20560c1 0t0 TCP 192.168.1.3:50585->104.25.53.12:http (ESTABLISHED)
show which service is using the PID
ps -ef 312
Then I got this
UID PID PPID C STIME TTY TIME CMD
0 312 58 0 9:32PM ?? 0:02.70 /opt/cisco/anyconnect/bin/acwebsecagent -console
To uninstall cisco web security agent run
sudo /opt/cisco/anyconnect/bin/websecurity_uninstall.sh
credits to: http://tobyaw.livejournal.com/315396.html
It can be Cisco AnyConnect.
Check if /Library/LaunchDaemons/com.cisco.anyconnect.vpnagentd.plist exists. Then unload it with launchctl and delete from /Library/LaunchDaemons
You can also use the Activity Monitor to identify and quit the process using the port.
Run: nmap -p 8080 localhost (Install nmap with MacPorts or Homebrew if you don't have it on your system yet)
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00034s latency).
Other addresses for localhost (not scanned): ::1
PORT STATE SERVICE
8080/tcp open http-proxy
Run: ps -ef | grep http-proxy
UID PID PPID C STIME TTY TIME CMD
640 99335 88310 0 12:26pm ttys002 0:00.01 grep http-proxy"
Run: ps -ef 640 (replace 501 with your UID)
/System/Library/PrivateFrameworks/PerformanceAnalysis.framework/Versions/A/XPCServices/com.apple.PerformanceAnalysis.animationperfd.xpc/Contents/MacOS/com.apple.PerformanceAnalysis.animationperfd
Port 8080 on mac osx is used by something installed with XCode SDK
try netstat
netstat -vanp tcp | grep 3000
if your netstat doesn't support -p , use lsof
sudo lsof -i tcp:3000
For Centos 7 use
netstat -vanp --tcp | grep 3000
After referring to the solution of #voutasaurus. I wrote this utility to simplify the process of killing all the processes that are running on the port.
killProcessesUsing3000 () {
pid=$(lsof -ti :3000) # The -t argument makes the output of lsof "terse" (Brief) which means that it only returns the PID.
# PID contains process processes that run on the 3000 port. In new lines if they are multiples
for num ($=pid) {
echo $num
kill -9 $num
}
}
#Alias
alias kill3000="killProcessesUsing3000"
For me this worked
Open your mac terminal
kill $(lsof -t -i:8080)
Explanation:
lsof -t returns the PID and passes that to kill.
I tried many of the above and they didn't work for me.
After many hours, I found this one liner:
# kill 8080
alias nuke88="lsof -i tcp:8080 | grep LISTEN | awk '{print \$2}' | xargs kill"
# kill 3000
alias nuke3k="lsof -i tcp:3000 | grep LISTEN | awk '{print \$2}' | xargs kill"

Kill all processes running on port 8080 on Mavericks

I'm getting a "socket.error: No socket could be created" when running a web.py script.
Is there a way to kill all processes on running on port 8080 (or any other port I wish) with a single line in Terminal on OSX Mavericks?
It's a single line, but you'd need to put it into a shell alias or shell script in order to make it easy to use:
$ kill $(lsof -i tcp:8080 | tail -n +2 | awk '{ print $2 }')
If you want to see and kill processes that don't belong to you, then sudo needs to get involved:
$ sudo kill $(sudo lsof -i tcp:8080 | tail -n +2 | awk '{ print $2 }')
The best way to kill all proccesses running on port 8080 in ubuntu is:
sudo fuser -k 8080/tcp

How to make an Echo server with Bash?

How to write a echo server bash script using tools like nc, echo, xargs, etc capable of simultaneously processing requests from multiple clients each with durable connection?
The best that I've came up so far is
nc -l -p 2000 -c 'xargs -n1 echo'
but it only allows a single connection.
If you use ncat instead of nc your command line works fine with multiple connections but (as you pointed out) without -p.
ncat -l 2000 -k -c 'xargs -n1 echo'
ncat is available at http://nmap.org/ncat/.
P.S. with the original the Hobbit's netcat (nc) the -c flag is not supported.
Update: -k (--keep-open) is now required to handle multiple connections.
Here are some examples. ncat simple services
TCP echo server
ncat -l 2000 --keep-open --exec "/bin/cat"
UDP echo server
ncat -l 2000 --keep-open --udp --exec "/bin/cat"
In case ncat is not an option, socat will also work:
socat TCP4-LISTEN:2000,fork EXEC:cat
The fork is necessary so multiple connections can be accepted. Adding reuseaddr to TCP4-LISTEN may be convenient.
netcat solution pre-installed in Ubunutu
The netcat pre-installed in Ubuntu 16.04 comes from netcat-openbsd, and has no -c option, but the manual gives a solution:
sudo mknod -m 777 fifo p
cat fifo | netcat -l -k localhost 8000 > fifo
Then client example:
echo abc | netcat localhost 8000
TODO: how to modify the input string value? The following does not return any reply:
cat fifo | tr 'a' 'b' | netcat -l -k localhost 8000 > fifo
The remote shell example however works:
cat fifo | /bin/sh -i 2>&1 | netcat -l -k localhost 8000 > fifo
I don't know how to deal with concurrent requests simply however.
what about...
#! /bin/sh
while :; do
/bin/nc.traditional -k -l -p 3342 -c 'xargs -n1 echo'
done

Resources