Telnet Bash Script (Connection closed by foreign host.)

Hello Everyone,

My following script is giving me problems, when the SIP trunk goes down and the telnet session is started and just when the command is about to complete the connection is closed then script restarts.

I have noticed that as soon the script types in "sys re" or "sys rebo" or "sys reb" the connection is closed.

#!/bin/bash
typeset -i interval=5
run=true
trunk=vonage
reboot=0
while [[ "$run" == "true" ]]; do
checktrunk=$(asterisk -rx "sip show peer $trunk" | grep -c "Status.*OK")
if [[ $checktrunk -eq 0 ]]; then
echo "$(date): SIP trunk registration failed."
sleep 2
{
sleep 2
echo admin
sleep 2
echo password
sleep 2
echo sys reboot
echo exit
} | telnet 192.168.1.1 
(( reboot +=1 ))
if (( reboot == 3 )); then
echo "$(date): Maximum 3 retries failed. Next retry after 10 mins."
sleep 600
reboot=0
fi
else
echo "$(date): SIP trunk registration OK."
fi
sleep 5
done
exit 1

Hope someone helps over this issue. Thanks!

I remember having had a similar problem. This helped:

{echo open 192.168.1.1 
sleep 2
echo admin
sleep 2
echo password
sleep 2
echo sys reboot
echo exit } | telnet 

Hi RudiC, you again mate! :slight_smile:

Lemme quickly try your given solution.

---------- Post updated at 11:24 AM ---------- Previous update was at 11:15 AM ----------

:frowning: :frowning: :frowning: No luck :frowning:

Sat Aug  2 17:22:52 GMT-1 2014: SIP trunk registration failed.
telnet> Trying 192.168.1.1...
Connected to 192.168.1.1 (192.168.1.1).
Escape character is '^]'.


Account:admin

Password: ***********

User login successful, expired time is "Unlimited".


Type ? for command help

World> show aConnection closed by foreign host.

Try reducing the sleep periods to 1 sec, and add a sleep after the exit command.

1 Like

Lovely, it works! :smiley:

But I have no clue as to why would it work with sleep duration reduced.

echo open 192.168.1.1 
sleep 1
echo admin
sleep 1
echo pass
sleep 0
echo show adsl
echo exit
sleep 1 

Actually, I think it was the final sleep n that made it work, not the reduction from 2 to 1. The stdout of your brace expression { ... } was closed before all commands had executed on the router, making it drop the connection.

1 Like

absolutely right, just tried it without the sleep in the end and it would not work. amazing!!

Thanks