Tag Archives: bash

Physically restart Sky router via Raspberry Pi

I have a Sky Hub router, the SR102 (black). Previously I had the white version as well.
Nice routers, pretty stable, but badly locked. You can change the SID of your wifi, change the password… not either sure if you can do a proper port forwarding. So… perfect for my mum, but a pain for whoever wants a little bit of extra control.

I had already an ASUS RT-N16 with DD-WRT firmware so I used the DMZ function on the Sky router to have some sort of “link” of the public IP of my broadband directly on the WAN interface of the router. In this way it’s like that is my ASUS router that does the connection and I can play as freely as I want, without caring much about the Sky router.

However, it happens that sometimes you need to give a full reboot to the main Sky router. And maybe do this automatically or via command line/script. And here it’s when things are getting more complicated.

The Sky Hub router allows you to reboot it via HTTP. Using the DMZ anyway will bypass the router itself and forward all the requests to the ASUS router. Also, I have never liked the idea to expose my router management page to the Internet, but I rather prefer to connect via SSH on a Raspberry Pi and issue commands from the terminal (telnet/ssh).

So, beside my multiple attempts to find a way to curl the button on the page, I had to find an alternative way to makes this happen. Of course, it didn’t help either to call the Sky Helpline asking if there was a remote possibility to have telnet enabled.

After a bit of talks on Facebook with some friends, here the solution: Remote Controlled Sockets with Pi-mote

Yes. If I can’t reboot from inside, let’s to that from outside!

The process was pretty straight forward.

First of all, I had to turn off my Raspberry Pi, and plug the “little green piece of board” as mentioned in here

After that, I’ve turned the pi on again, and installed the required packages. Happily I found that there is now the python library available for energenie, so I have installed them as well, making my life easier 🙂

apt-get install python-rpi.gpio python-pip
pip install energenie

Once done, I have created these two basic script and I have run one a time, to configure the socket plugs.

Make sure to plug the ONE SOCKET PLUG A TIME and run the relative script.

You can find more information in the previous PDF, but these sockets learn who they are based on which commands they are receiving during the learning mode (enabling keeping the green button pressed for about 5 seconds when switched off). So if you run the first script with both plugs connected and in learning mode, they will do exactly the same, and unless you want to control two sockets at the same time, better to follow the instructions 🙂

Script to configure the first socket:

from energenie import switch_on, switch_off
from time import sleep

# turn the first plug socket ON and then OFF
switch_on(1)
sleep(5)
switch_off(1)

 

Script to configure the second socket:

from energenie import switch_on, switch_off
from time import sleep

# turn the second plug socket ON and then OFF
switch_on(2)
sleep(5)
switch_off(2)

 

And now, my simple script to make… “the magic”: plugs.py

from energenie import switch_on, switch_off
from time import sleep
import sys

if len(sys.argv) == 1:
    print "Use:\n# python plug.py <plug_ID> <ON/OFF>\ne.g. # python plug.py 1 ON"
    exit(1)

else:
    plug = sys.argv[1]
    status = sys.argv[2]

if status.lower() == 'on':
   switch_on(int(plug))
else:
   switch_off(int(plug))

You can use this script to control any sockets (up to 4 – hardware limitation).

And here a bash wrapper (I’m not really good in python sorry) that calls plugs.py and restart the router: restart_sky_router

#!/bin/bash

# This script requires plug.py script

if [ "$EUID" -ne 0 ]
  then echo "Please run as root or use 'sudo'"
  exit
fi

echo "Switching OFF and then ON the physical socket"


# Uses ENERGENIE Radio controlled Sockets
python plug.py 1 off
sleep 10
python plug.py 1 on

 

Now, I can have my Nagios system to check for the speed as documented here and eventually issue restart_sky_router script to see if it fixes the issue. Or simply be able to have a command to integrate in your scripts!

 

Check Sky Hub speed script

Bash script that extract the router speed.

#!/bin/bash

# Broadband Speed within limits Download 14000 and Upload 750

ROUTER=<router_ip>
USER=<router_username>
PASS=<router_password>
# Download Link speed
DL=14000
# Upload Link speed
UL=750

SPEED=($(wget -qO- http://$ROUTER/sky_router_status.html --user=$USER --password=$PASS | awk -F "'" '$0 ~ /Modemstat\[0\]/  {print $2, $4}'))

if [[ ${SPEED[0]} -lt $DL || ${SPEED[1]} -lt $UL ]] ; then
  exit 2
else
  echo "Broadband Speed within limits Download ${SPEED[0]} and Upload ${SPEED[1]}"
  exit 0
fi

 

This can be integrated in Nagios to send an alert if the speed drops.

Rackspace – Cloud Sever autokill script

#!/bin/bash

# This script auto delete the current instance and ask the
# Autoscale Group to replace the node


###########################################################

CRED_FILE=/opt/autoscale/.credentials
AS_GRP_ID=a17b08b3-0c04-48e8-84a9-3070c29a27fa

###########################################################

# Gather info from credential file
USERNAME=$(grep username $CRED_FILE | awk -F= '{print $2}' | sed 's/ //g')
APIKEY=$(grep api_key $CRED_FILE | awk -F= '{print $2}' | sed 's/ //g')
REGION=$(grep region $CRED_FILE | awk -F= '{print $2}' | sed 's/ //g' | tr '[:upper:]' '[:lower:]')


SERVER_UID=$(xenstore-read name | sed 's/instance-//')

AUTH=$(
curl -sd \
"{
   \"auth\":
   {
        \"RAX-KSKEY:apiKeyCredentials\":
        {\"username\": \"$USERNAME\",
        \"apiKey\": \"$APIKEY\"}        }
}" \
-H 'Content-Type: application/json' \
'https://identity.api.rackspacecloud.com/v2.0/tokens' | python -m json.tool | grep -A 7 token | awk '/id/ { print $2 }' | tr -d '"' | tr -d ","
) 

TOKEN=$(echo $AUTH | awk '{print $1}')
ID=$(echo $AUTH | awk '{print $2}')


curl -sH "X-Auth-Token: $TOKEN" -H "Content-type: application/json" -X DELETE https://$REGION.autoscale.api.rackspacecloud.com/v1.0/$ID/groups/$AS_GRP_ID/servers/$SERVER_UID?replace=true

BASH conditional expressions

-a file

True if file exists.

-b file

True if file exists and is a block special file.

-c file

True if file exists and is a character special file.

-d file

True if file exists and is a directory.

-e file

True if file exists.

-f file

True if file exists and is a regular file.

-g file

True if file exists and its set-group-id bit is set.

-h file

True if file exists and is a symbolic link.

-k file

True if file exists and its “sticky” bit is set.

-p file

True if file exists and is a named pipe (FIFO).

-r file

True if file exists and is readable.

-s file

True if file exists and has a size greater than zero.

-t fd

True if file descriptor fd is open and refers to a terminal.

-u file

True if file exists and its set-user-id bit is set.

-w file

True if file exists and is writable.

-x file

True if file exists and is executable.

-G file

True if file exists and is owned by the effective group id.

-L file

True if file exists and is a symbolic link.

-N file

True if file exists and has been modified since it was last read.

-O file

True if file exists and is owned by the effective user id.

-S file

True if file exists and is a socket.

file1 -ef file2

True if file1 and file2 refer to the same device and inode numbers.

file1 -nt file2

True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not.

file1 -ot file2

True if file1 is older than file2, or if file2 exists and file1 does not.

-o optname

True if the shell option optname is enabled. The list of options appears in the description of the -o option to the set builtin (see The Set Builtin).

-v varname

True if the shell variable varname is set (has been assigned a value).

-R varname

True if the shell variable varname is set and is a name reference.

-z string

True if the length of string is zero.

-n stringstring

True if the length of string is non-zero.

string1 == string2string1 = string2

True if the strings are equal. When used with the [[ command, this performs pattern matching as described above (see Conditional Constructs).

=’ should be used with the test command for POSIX conformance.

string1 != string2

True if the strings are not equal.

string1 < string2

True if string1 sorts before string2 lexicographically.

string1 > string2

True if string1 sorts after string2 lexicographically.

arg1 OP arg2

OP is one of ‘-eq’, ‘-ne’, ‘-lt’, ‘-le’, ‘-gt’, or ‘-ge’. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively.  Arg1 and arg2 may be positive or negative integers.

 

 

Source http://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html

BASH – File test operators

(From man bash)

The test command sorts using ASCII ordering.

-a file
              True if file exists.
-b file
              True if file exists and is a block special file.
-c file
              True if file exists and is a character special file.
-d file
              True if file exists and is a directory.
-e file
              True if file exists.
-f file
              True if file exists and is a regular file.
-g file
              True if file exists and is set-group-id.
-h file
              True if file exists and is a symbolic link.
-k file
              True if file exists and its ``sticky'' bit is set.
-p file
              True if file exists and is a named pipe (FIFO).
-r file
              True if file exists and is readable.
-s file
              True if file exists and has a size greater than zero.
-t fd
              True if file descriptor fd is open and refers to a terminal.
-u file
              True if file exists and its set-user-id bit is set.
-w file
              True if file exists and is writable.
-x file
              True if file exists and is executable.
-G file
              True if file exists and is owned by the effective group id.
-L file
              True if file exists and is a symbolic link.
-N file
              True if file exists and has been modified since it was last read.
-O file
              True if file exists and is owned by the effective user id.
-S file
              True if file exists and is a socket.
file1 -ef file2
              True if file1 and file2 refer to the same device and inode numbers.
file1 -nt file2
              True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not.
file1 -ot file2
              True if file1 is older than file2, or if file2 exists and file1 does not.

Dynamic DNS update script

Below a script that I’ve created to update your Dynamic DNS service.

It has been tested on Raspian (Raspberry Pi), Ubuntu 18.04 and Debian 9.

It works with Internet.bs, No-ip.com and CloudFlare

https://bitbucket.org/thtieig/dynip_update/src/master/

Also, for who as a router running DD-WRT, here a quick article about how to set it up.

Enjoy! 😉

Mac/Linux – Terminal customisation .profile/.bashrc

For Mac, you need to create a .profile file in your home directory.

This is what I’ve done on mine…

For normal user:

user_bashrc

export PS1="\[\e[00;32m\]\u\[\e[0m\]\[\e[00;37m\]@\[\e[0m\]\[\e[01;37m\]\h\[\e[0m\]\[\e[00;37m\]:\[\e[0m\]\[\e[00;33m\]\w\[\e[0m\]\[\e[00;37m\] \[\e[0m\]\[\e[00;32m\]\\$\[\e[0m\]\[\e[00;37m\] \[\e[0m\]"
# Customisation of 'ls' command
export CLICOLOR=1
export LSCOLORS="ExGxBxDxCxEgEdxbxgxcxd"
alias ls='ls -GF'

 

For root:

root_bashrc

export PS1="\[\e[00;31m\]\u\[\e[0m\]\[\e[00;37m\]:\[\e[0m\]\[\e[00;33m\]\w\[\e[0m\]\[\e[00;37m\] \[\e[0m\]\[\e[00;31m\]\\$\[\e[0m\]\[\e[00;37m\] \[\e[0m\]"
# Customisation of 'ls' command
export CLICOLOR=1
export LSCOLORS="ExGxBxDxCxEgEdxbxgxcxd"
alias ls='ls -GF'

Sources:
http://bashrcgenerator.com/
http://geekology.co.za/article/2009/04/how-to-enable-terminals-directory-and-file-color-highlighting-in-mac-os-x
http://apple.stackexchange.com/questions/33677/how-can-i-configure-mac-terminal-to-have-color-ls-output
http://osxdaily.com/2013/02/05/improve-terminal-appearance-mac-os-x/

BASH: Current Script folder

#!/bin/bash
# Name: /tmp/demo.bash : 
# Purpose: Tell in what directory $0 is stored in
# Warning: Not tested for portability 
# ------------------------------------------------

## who am i? ##
_script="$(readlink -f ${BASH_SOURCE[0]})"

## Delete last component from $_script ##
_base="$(dirname $_script)"

## Okay, print it ##
echo "Script name : $_script"
echo "Current working dir : $PWD"
echo "Script location path (dir) : $_base"

Source