Reputation: 119
I have some code that tends to hang randomly inside it's 'for loop'. I'm looking for a solution that will automatically kill the ssh session's PID if it exists for 5 seconds. I'm killing the hung processes right now manually, but I want to put this in cron so automatic PID killing would be awesome.
for host in `cat $WORKDIR/linux_hosts.txt $WORKDIR/aix_hosts.txt`
do
ssh -o LogLevel=QUIET -o ConnectTimeout=2 -t $host "cat /etc/passwd" >> $FILEDIR/$host
done
Thanks for the help!
Upvotes: 0
Views: 981
Reputation: 531798
Run all the ssh
processes in the background, then wait 5 seconds. Once sleep
returns, use jobs -p
to get the process IDs of any background jobs still running, and kill them.
cat "$WORKDIR"/{linux_hosts.txt,aix_hosts.txt} | while read host; do
ssh -o LogLevel=QUIET -o ConnectTimeout=2 -t "$host" "cat /etc/passwd" >> "$FILEDIR/$host" &
done
sleep 5
kill $(jobs -p) 2>/dev/null
Upvotes: 2
Reputation: 1935
This will find and kill all ssh
process older than 5 minutes.
cd /proc
kill $(find $(pidof ssh) -maxdepth 0 -mmin +5)
Upvotes: 0