perl one-liners to search and kill process remotely

A

alex922

Hi, I've been trying to get used to using perl one-liners. So far so
good, except, I can't seem to use perl one-liners to search and kill
processes remotely. For example, lets say I run the 'top' command on
Machine A.

I then run the command to seach and try to kill the process.

ssh user@host ps -fe | grep top | perl -ne 'split /\s+/; kill -9 $_[1]'

however, I get the message,

kill: 26475: No such process

but when I login to the remote machine, it does indeed have that
process.

Any help would be great!

Thanks!
Alex
 
J

John W. Krahn

Christian said:
Hi, I've been trying to get used to using perl one-liners. So far so
good, except, I can't seem to use perl one-liners to search and kill
processes remotely. For example, lets say I run the 'top' command on
Machine A.

I then run the command to seach and try to kill the process.

ssh user@host ps -fe | grep top | perl -ne 'split /\s+/; kill -9 $_[1]'

however, I get the message,

kill: 26475: No such process

That's correct, as you are executing the part
"| grep top | perl -ne 'split /\s+/; kill -9 $_[1]'"
at the local machine. To run it on the remote machine, you have to
enclose the whole line in quotes. With *nix operating systems you
always have to have in mind that the first thing after entering a
command is your local shell trying to parse it, looking for pipe
symbols and command delimiters.

ssh user@host "ps -fe | grep top |
perl -ne 'split /\s+/; kill -9 \$_[1]'"
should work. Notice that you will have to escape dollar variables,
as the remote shell will otherwise try to expand them (e.g. with $_
being the last command executed in the bash shell).

Also, Perl's kill function is a bit different then kill(1):

perldoc -f kill
kill SIGNAL, LIST
[snip]
Unlike in the shell, if SIGNAL is negative, it kills process groups
instead of processes. (On System V, a negative PROCESS number will
also kill process groups, but that’s not portable.) That means you
usually want to use positive not negative signals. You may also use a
signal name in quotes.


And you can simplify your one-liner to:

ps -fe | perl -ane'/top/ && kill 9, $F[1]'



John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top