![]() |
Killing processes remotely using SSH
Hello list. I have a script that remotely deploys code then kills a process so it can re-init using the new code. Here's the command I'm trying to get working from the script:
ssh deployer@192.168.0.104 'ERPMPROC=`ps -ef | grep top | awk '{ print $2}' | head -1` && kill $ERPMPROC' In this case, just an example, it finds "top" and kills it. This command works locally (not using the ssh login part...), but when ssh'ing in from a remote machine, I get this error: awk '{ print $2}' | head -1` && echo $ERPMPROC' awk: cmd. line:2: (END OF FILE) awk: cmd. line:2: syntax error I'm sure the whole thing is failing because it only seems the first and second single quotes and ends the command at the second, instead of the fourth. I haven't had any luck in escaping the first set of single quotes. Any help is appreciated... |
Don't use a variable. I don't think you can set variables remotely. Try this:
ssh deployer@192.168.0.104 kill $(ps -ef | grep top | awk '{ print $2}' | head -1) |
Your grep command might catch more than you want, such as an argument containing "desktop". If you want to kill the top command you could:
Code:
kill $(ps -ef | awk '/ top$/{print $2}') |
Quote:
Code:
bash: line 0: kill: (8029) - No such processI tried using backticks instead of $() and this string simply getting the PID works: Code:
ssh deployer@192.168.0.104 ``ps -ef | grep top | awk '{ print $2}' | head -1``Code:
ssh deployer@192.168.0.104 sudo kill ``ps -ef | grep top | awk '{ print $2}' | head -1``Code:
ssh deployer@192.168.0.104 ``ps -ef | grep top | awk '{ print $2}' | head -1`` > process.pidfile |
Quote:
Code:
ssh deployer@192.168.0.104 $(ps -ef | awk '/ top$/{print $2}')Thanks again for the reply. |
I transposed those characters when I typed them in.
For gnu's version of ps, there is a -C option where you can select just the instance of the command. Also you can use the "killall" command to kill a process by name: I tried this out to quit a top process running. Keep in mind that killall will cause all instances of top to quit. ssh hpmedia "ps -C top && killall top || echo top isn't running" I think that this example is more readable then using awk to filter the output of ps. --- Sorry, I missed the last line on your response, and used "killall" again. |
Have you looked at pgrep or pkill?
e.g. 'pgrep -f $ERPMPROC' should return the PID of the currently running process. |
TRY:
for i in server1 server2 server 3 do pid=$(ssh $i ps -ef |grep top | awk '{ print $2 }' | head -1) echo $pid ssh $i kill $pid done |
| All times are GMT -5. The time now is 02:06 AM. |