Giannis Pappas
Giannis Pappas

Reputation: 137

Can't kill process started by another ssh session in bash script

I'm writing a bash script where I need to login in a remote machine via ssh, start a process, end the ssh session, do some other things, and then login again via ssh to kill the process. But the process doesn't get killed. I have tried a lot of ways. Here is the part of the script that won't work:

ssh [email protected] &>/dev/null << EOF
tshark -i ens160 -w /home/localadmin/dns_traffic_61.pcap &>/dev/null &
EOF


ssh [email protected] &>/dev/null << EOF
kill $(pidof tshark)
EOF

I have also tried putting the tshark command in a script so I would kill the script like this:

ssh [email protected] &>/dev/null << EOF
sh tshark.sh &>/dev/null &
EOF

ssh [email protected] &>/dev/null << EOF
pid=$(ps -ef | grep tshark.sh | grep -v grep | awk '{print $2}')
kill $pid  
EOF

and this:

ps -ef | grep tshark.sh | grep -v grep | awk '{print $2}'|xargs kill

Nothing seems to work.

Note: When I connect via ssh manually I can kill the process, only the bash script can't.

Upvotes: 3

Views: 1439

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

use single quotes around end marker so that expansion doesn't occur in current shell but in remote

ssh [email protected] &>/dev/null << 'EOF'
kill $(pidof tshark)
EOF

compare

cat << EOF
$$
EOF

and

cat << 'EOF'
$$
EOF

Upvotes: 2

Related Questions