Get a command output in a shell script - linux

I am trying to make a shell script that automatically kills the process that is running in a given port, on a Ubuntu 14.10 dedicated server.
As far as I know, using fuser -n tcp {port-number} gives the PID of the process running in that port, example: http://prntscr.com/81whib
Also, I know that kill -9 {PID} kills the process with such PID.
How could I make a shell script that gets the output of the command fuser -n tcp {port-number} and uses it in the command kill -9 {PID} ?
Thanks for the help.

You can manipulate the output of fuser using awk (sample using port 139):
pid=$(fuser -n tcp 139 | awk '{print $1}')
echo $pid
# kill -9 $pid , etc

The following script will allow you to pass in a port (e.g. ./killProcess 25565) and will kill the process so long as a PID exists.
#!/bin/bash
PID=$(fuser -n tcp $1 | awk '{print $2}')
if [ ! -z "$PID" ]; then
kill -9 $PID
else
echo "No process is running on port $1"
fi

Related

Don't kill created processes, which created by ps - linux

give some advice, please.
I am trying to kill processes remotely (ssh to hostname), find some processes and kill them. But I have a condition: Do not kill java process, sshd and gnome.
Here is example (I just do echo except kill):
#/bin/sh -x.
HOSTFILE=$1
vars=`cat $HOSTFILE`
for i in $vars; do
ssh "$i" /bin/bash <<'EOF'
echo $(hostname)
ps aux | grep -e '^sys_ctl'| grep -v "java" | grep -v "sshd" | \
grep -v "gnome" | awk '{print $2$11}'| for i in `xargs echo`; do echo $i; done;
EOF
done
The result is:
host1:
21707/bin/bash
21717ps
21718grep
21722awk
21723/bin/bash
21724xargs
host2:
15241/bin/bash
15251ps
15252grep
15256awk
15257/bin/bash
15258xargs
89740-bash
98467sleep
98469sleep
98471sleep
98472sleep
98474sleep
98475sleep
I want to kill (output), only sleep processes, not grep,awk,bash,xargs,ps
Can you suggest something elegant?
why not just : kill $(pgrep -f sleep)
or : pkill -f sleep

linux program does not start after sh gets killed

I need to start a program, which uses a serial port from within a bash script. The matter is that prior to doing that I need to kill "-sh" process in order to release the serial port occupied by it (I use a serial console and this is the only way to communicate with Linux). When I kill "-sh" my program doesn't start, however the bash script continues to execute. If I don't kill "-sh" my program normally starts. See code below for details:
#!/bin/bash
SH_PID=`ps -o comm,pid | egrep -e '^sh' | awk -F " " '{print $2}'`
kill -9 $SH_PID
myprog #start my program
while true
do
sleep 10
echo "script is running..." > /dev/ttyS0
done
Any thoughts?
What if you kill your shell after running your program in background:
#!/bin/bash
SH_PID=`ps -o comm,pid | egrep -e '^sh' | awk -F " " '{print $2}'`
nohup myprog & #start my program in background
kill --HUP $SH_PID
while true
do
sleep 10
echo "script is running..." > /dev/ttyS0
done

terminate infinite loop initiated in remote server when exiting bash script

Script which executes commands in infinite loop in background
<SOMETHING ELSE AT START OF SCRIPT>
cmd='while true;
do
ps aux | head;
sleep 1;
done > $FILE'
ssh root#$SERVER $cmd &
...
...
<SOME OTHER TASKS>
...
...
( at the end of this script, how to kill the above snippet executing in remote server)
[ kindly note i dont want to wait as the while loop is infinite ]
Read and tried some posts from stackoverflow, but could not find exact solution for this problem.
Rather than an infinite loop, use a sentinel file:
cmd='while [ -r /tmp/somefile];
do
# stuff
done > $FILE'
ssh root#$SERVER touch /tmp/somefile
ssh root#$SERVER $cmd &
# do other stuff
ssh root#$SERVER rm -f /tmp/somefile
This follows your current practice of putting the remote command in a variable, but the arguments against that cited elsewhere should be considered.
If you want to kill the ssh process running in background at the end of your script, just do:
kill $!
I assume this is the only (or the last) process you started in background.
Try following sequence
CTRL+Z
fg
CTRL+C
or
jobs
kill %jobspec
To kill everything belonging to user logged in you could try:
whois=`w|grep $user|awk '{print $2}'`;user=root; ssh $user#server -C "ps auwx|grep $whois|awk '{print \$2}'"
This will list all the processes owned by the user you just logged in as - just add |xargs kill -9
whois=`w|grep $user|awk '{print $2}'`;user=root; ssh $user#server -C "ps auwx|grep $whois|awk '{print \$2}'|xargs kill -9 "
whois=`w|grep $user|awk '{print $2}'`;user=root; ssh $user#server -C "ps auwx|grep $whois|awk '{print \$2}'|awk '{print "kill -9 " $1}'|/bin/sh "

shell script to kill the process listening on port 3000? [duplicate]

This question already has answers here:
How to kill a process running on particular port in Linux?
(34 answers)
Closed 4 years ago.
I want to define a bash alias named kill3000 to automate the following task:
$ lsof -i:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ruby 13402 zero 4u IPv4 2847851 0t0 TCP *:3000 (LISTEN)
$ kill -9 13402
alias kill3000="fuser -k -n tcp 3000"
Try this:
kill -9 $(lsof -i:3000 -t)
The -t flag is what you want: it displays PID, and nothing else.
Update
In case the process is not found and you don't want to see error message:
kill -9 $(lsof -i:3000 -t) 2> /dev/null
Assuming you are running bash.
Update
Basile's suggestion is excellent: we should first try to terminate the process normally will kill -TERM, if failed, then kill -KILL (AKA kill -9):
pid=$(lsof -i:3000 -t); kill -TERM $pid || kill -KILL $pid
You might want to make this a bash function.
Another option using using the original lsof command:
lsof -n -i:3000 | grep LISTEN | awk '{ print $2 }' | uniq | xargs kill -9
If you want to use this in a shell script, you could add the -r flag to xargs to handle the case where no process is listening:
... | xargs -r kill -9
fuser -k 3000/tcp should also work
How about
alias kill3000="lsof -i:3000 | grep LISTEN | awk '{print $2}' | xargs kill -9"
fuser -n tcp 3000
Will yield the output of
3000/tcp: <$pid>
So you could do:
fuser -n tcp 3000 | awk '{ print $2 }' | xargs -r kill

How can I kill a process by name instead of PID, on Linux? [duplicate]

This question already has answers here:
Find and kill a process in one line using bash and regex
(30 answers)
Closed 1 year ago.
Sometimes when I try to start Firefox it says "a Firefox process is already running". So I have to do this:
jeremy#jeremy-desktop:~$ ps aux | grep firefox
jeremy 7451 25.0 27.4 170536 65680 ? Sl 22:39 1:18 /usr/lib/firefox-3.0.1/firefox
jeremy 7578 0.0 0.3 3004 768 pts/0 S+ 22:44 0:00 grep firefox
jeremy#jeremy-desktop:~$ kill 7451
What I'd like is a command that would do all that for me. It would take an input string and grep for it (or whatever) in the list of processes, and would kill all the processes in the output:
jeremy#jeremy-desktop:~$ killbyname firefox
I tried doing it in PHP but exec('ps aux') seems to only show processes that have been executed with exec() in the PHP script itself (so the only process it shows is itself.)
pkill firefox
More information: http://linux.about.com/library/cmd/blcmdl1_pkill.htm
Also possible to use:
pkill -f "Process name"
For me, it worked up perfectly. It was what I have been looking for.
pkill doesn't work with name without the flag.
When -f is set, the full command line is used for pattern matching.
You can kill processes by name with killall <name>
killall sends a signal to all
processes running any of the specified
commands. If no signal name is
specified, SIGTERM is sent.
Signals can be specified either by
name (e.g. -HUP or -SIGHUP ) or by number (e.g.
-1) or by option -s.
If the command name is not regular
expression (option -r) and contains a
slash (/), processes executing that
particular file will be selected for
killing, independent of their name.
But if you don't see the process with ps aux, you probably won't have the right to kill it ...
A bit longer alternative:
kill `pidof firefox`
The easiest way to do is first check you are getting right process IDs with:
pgrep -f [part_of_a_command]
If the result is as expected. Go with:
pkill -f [part_of_a_command]
If processes get stuck and are unable to accomplish the request you can use kill.
kill -9 $(pgrep -f [part_of_a_command])
If you want to be on the safe side and only terminate processes that you initially started add -u along with your username
pkill -f [part_of_a_command] -u [username]
Kill all processes having snippet in startup path. You can kill all apps started from some directory by for putting /directory/ as a snippet. This is quite usefull when you start several components for the same application from the same app directory.
ps ax | grep <snippet> | grep -v grep | awk '{print $1}' | xargs kill
* I would prefer pgrep if available
Strange, but I haven't seen the solution like this:
kill -9 `pidof firefox`
it can also kill multiple processes (multiple pids) like:
kill -9 `pgrep firefox`
I prefer pidof since it has single line output:
> pgrep firefox
6316
6565
> pidof firefox
6565 6316
Using killall command:
killall processname
Use -9 or -KILL to forcefully kill the program (the options are similar to the kill command).
On Mac I could not find the pgrep and pkill neither was killall working so wrote a simple one liner script:-
export pid=`ps | grep process_name | awk 'NR==1{print $1}' | cut -d' ' -f1`;kill $pid
If there's an easier way of doing this then please share.
To kill with grep:
kill -9 `pgrep myprocess`
more correct would be:
export pid=`ps aux | grep process_name | awk 'NR==1{print $2}' | cut -d' ' -f1`;kill -9 $pid
I normally use the killall command.
Check this link for details of this command.
I was asking myself the same question but the problem with the current answers is that they don't safe check the processes to be killed so... it could lead to terrible mistakes :)... especially if several processes matches the pattern.
As a disclaimer, I'm not a sh pro and there is certainly room for improvement.
So I wrote a little sh script :
#!/bin/sh
killables=$(ps aux | grep $1 | grep -v mykill | grep -v grep)
if [ ! "${killables}" = "" ]
then
echo "You are going to kill some process:"
echo "${killables}"
else
echo "No process with the pattern $1 found."
return
fi
echo -n "Is it ok?(Y/N)"
read input
if [ "$input" = "Y" ]
then
for pid in $(echo "${killables}" | awk '{print $2}')
do
echo killing $pid "..."
kill $pid
echo $pid killed
done
fi
kill -9 $(ps aux | grep -e myprocessname| awk '{ print $2 }')
If you run GNOME, you can use the system monitor (System->Administration->System Monitor) to kill processes as you would under Windows. KDE will have something similar.
The default kill command accepts command names as an alternative to PID. See kill (1). An often occurring trouble is that bash provides its own kill which accepts job numbers, like kill %1, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the bash version by calling
enable -n kill
For more info see kill and enable entries in bash (1).
ps aux | grep processname | cut -d' ' -f7 | xargs kill -9 $
awk oneliner, which parses the header of ps output, so you don't need to care about column numbers (but column names). Support regex. For example, to kill all processes, which executable name (without path) contains word "firefox" try
ps -fe | awk 'NR==1{for (i=1; i<=NF; i++) {if ($i=="COMMAND") Ncmd=i; else if ($i=="PID") Npid=i} if (!Ncmd || !Npid) {print "wrong or no header" > "/dev/stderr"; exit} }$Ncmd~"/"name"$"{print "killing "$Ncmd" with PID " $Npid; system("kill "$Npid)}' name=.*firefox.*

Resources