JavaDev
JavaDev

Reputation: 31

Can someone tell me why this shell script isn't working the way I want it to

ssh hostname ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs kill -KILL

When I run this I get the error message "kill: No such process"

But when I run this:

ssh hostname ps aux| egrep '.*python' | grep -v 'grep' |awk '{print $2}'| xargs echo

It correctly prints the pid. And also

ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}' | xargs kill -KILL

works correctly on the localhost.

Upvotes: 1

Views: 1936

Answers (4)

chrisaycock
chrisaycock

Reputation: 37928

As the others have pointed out, you can't just run a piped command through ssh without putting the command sequence in quotation marks.

But there's an even easier way to do what you want:

ssh hostname pkill python

The pkill command will handle all of the process grepping for you.

Upvotes: 1

phemmer
phemmer

Reputation: 8846

Your command is only running ps aux on the remote host, everything else gets executed locally.

change it to

ssh hostname "ps aux| egrep '.*python' | grep -v 'grep'| awk '{print \$2}'| xargs kill -KILL"

The usage of the quotes sends the entire command over to the remote host. And then you have to add the \ in front of the $2 because youre inside double quotes, and those single quotes are just characters at that point

Upvotes: 3

rvs
rvs

Reputation: 1301

It's because only first command (ps aux) is being provided to ssh as args. Try to use quotes: ssh hostname "ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs kill -KILL"

In this case "ps aux| egrep '.*python' | grep -v 'grep'| awk '{print $2}'| xargs kill -KILL" would be passed to ssh command as 2nd argument

Upvotes: 0

andrei1089
andrei1089

Reputation: 1108

It can't work that way, the output from ssh is processed on your local machine. So the call to kill will try to terminate a process on your machine, not on the remote machine.

You can try to use the expect tool to solve the problem.

Upvotes: 0

Related Questions