Unable to kill remote processes with ssh

737 views Asked by At

I need to kill remote processes with a shell script as follows:

#!/bin/bash

ip="172.24.63.41"
user="mag"
timeout 10s ssh -q $user@$ip exit
if [ $? -eq 124 ]
then
    echo "can not connect to $ip, timeout out."
else
    echo "connected, executing commands"
    scp a.txt $user@$ip://home/mag
    ssh -o ConnectTimeout=10 $user@$ip > /dev/null 2>&1 << remoteCmd

    touch b.txt
    jobPid=`jps -l | grep jobserver | awk '{print $1}'`
    if [ ! $jobPid == "" ]; then
        kill -9 $jobPid
    fi
    exit

remoteCmd

echo "commands executed."
fi

After executed it I found the scp and touch clauses had been executed, but the kill clause had not been executed successful and the process is still there. If I run clauses from "jobPid= ..." to "fi" on remote machine the process can be killed. How to fix it?

2

There are 2 answers

1
Ben Davis On

Your script needs root access (WHICH IS NEVER A GOOD IDEA). Or make sure your program which is running, is running under your webuser/group

0
user1803467 On

I put a script on the remote machine which can find and kill the process, then I ran the script on local machine which execute the script on the remote machine with ssh. The script is as follows:

Local script:

#!/bin/bash
ip="172.24.63.41"
user="mag"

timeout 10s ssh -q $user@$ip exit
if [ $? -eq 124 ]
then
    echo "can not connect to $ip, timeout out."
else
    echo "connected, executing commands"
    ssh -q $user@$ip "/home/mag/local.sh"
    echo "commands executed."
fi

remote script:

#!/bin/bash
jobPid=`jps -l | grep jobserver | awk '{print $1}'`
if [ ! $jobPid == "" ]; then
    kill -9 $jobPid
fi