Home > Back-end >  bash code to first ping internet and if fails then reboot modem automatically
bash code to first ping internet and if fails then reboot modem automatically

Time:11-12

I am completely new to bash scripting. Searching and found the bash code to reboot my modem via telnet. Now I want that the code first check the internet connectivity then if ping fails run the rest of the script to reboot the modem. here is the code to reboot modem via telnet (first you have to install expect )

 set  timeout 60
    set user  xxxxx
    set  password  xxxxx
    spawn /usr/bin/telnet 192.168.1.1
    expect  "Username:"  {send  "$user\r"}
     expect  "Password:" {send "$password\r"}
    expect "*"  {send "reboot\r"}
    interact 

CodePudding user response:

Use run command as test condition for ping check:

if ping -q -c 1 192.8.8.8; then
    echo "OK"
else
    echo "Fail"
fi

CodePudding user response:

You have to using shebang "#!/usr/bin/expect" instead "!/bin/bash" or do like this:

#!/bin/bash

SRV_ADDR="example.com"
SRV_PORT="80"

if ping -q -c 1 192.8.8.8; then
    echo "OK"
else
    echo "Fail"
    expect -c "
    spawn telnet ${SRV_ADDR} ${SRV_PORT}
    expect \"Escape character is '^]'.\"
    send \"HEAD http://www.example.com/ HTTP/1.0\n\n\"
    interact
    "
fi

In your case it might be:

#!/bin/bash

USER="xxxxx"
PASSWORD="xxxxx"

if ping -q -c 1 192.8.8.8; then
    echo "OK"
else
    echo "Fail"

    expect -c "
    spawn telnet 192.168.1.1

    expect \"Username:\"
    send \"${USER}\n\"

    expect \"Password:\"
    send \"${PASSWORD}\n\"

    expect \"reboot\n\"
    interact
    "
fi
  • Related