Killing process on remote server

Hi guys,

I am trying to write a script that logs into a remote server as root and greps a particular process, awks its PID and then xargs kill -9 .

This is the actual command :

for i in `cat nodes.txt`
do
ssh root@$i 'ps -ef | grep puppet | grep -v grep | awk "{print $2}" |  xargs kill -9 '
done

It is not working as expected.

When I try to do ;

jan@server1 ~/scripts $ ssh root@server2 'ps -ef | grep puppet | grep -v grep |awk "{print $2}" '

I get :

root     10090 10089  0 Nov01 ?        00:00:00 /opt/puppet/bin/ruby /opt/puppet/bin/puppet agent --onetime --ignorecache --no-daemonize --no-usecacheonfailure --detailed-exitcodes --no-splay

It does not seem to be awking the PID # .

Does any one know the issue with the Syntax ?

Regards

awk's program text definitely needs to be within single quotes, try

ssh root@server2 "ps -ef | grep puppet | grep -v grep |awk '{print $2}' "

Seems like the same result.

jan@server1 ~ $ ssh root@server2 "ps -ef | grep puppet | grep -v grep |awk '{print $2}' "
root     10090 10089  0 Nov01 ?        00:00:00 /opt/puppet/bin/ruby /opt/puppet/bin/puppet agent --onetime --ignorecache --no-daemonize --no-usecacheonfailure --detailed-exitcodes --no-splay

Regards

Try:

$ ssh root@server2 "ps -ef | grep puppet | grep -v grep |awk '{print \$2}' "

Or:

$ ssh root@server2 <<"EOF"
ps -ef | grep puppet | grep -v grep |awk '{print $2}'
EOF

man pkill

Hopefully there's never a user "puppet" on any of those machines...

$ ssh root@server2 "ps -ef | grep puppet | grep -v grep |awk '{print \$2}' "

This worked perfectly fine. Thank you !

You should also try and avoid using kill -9 unless it is a last resort as this signal doesn't allow the process any opportunity to cleanup/save open files/flush buffers and the like.

Best practice is to use kill -15 which is basically a "request" for the process to close. If the process doesn't respond to this "request" in a timely manor then you can assume it is "stuck" and use kill -9 .

Cool ! Thanks for the tip. Will keep that in mind :slight_smile: