Script to monitor internet connection

April 21st, 2015

The internet often drops at work, so to compile a csv report of the outage time and for how long I wrote this script, which maybe of use to someone.

Simply create the script, with execution rights (sudo chmod a+x) and call the script with the first argument as a resource e.g google and the second argument as the output filename e.g ./monitor.sh google.co.uk myFile

Code below:

#!/bin/bash

resource=$1
outfile=$2
dwnTmp=".dwnLock";
upTmp=".upLock";

# NEED A RESOURCE
if [[ -z "$resource" ]]; then
      	echo "You must define a resource as the first parameter e.g google.co.uk";
	exit; 
fi
####

# NEED A FILENAME
if [[ -z "$outfile" ]]; then
      	echo "You must define an output file as the second parameter";
	exit; 
fi
####

### REMOVE LOCKS
if [ -f "$dwnTmp" ]; then
        rm $dwnTmp;
fi
if [ -f "$upTmp" ]; then
        rm $upTmp;
fi
#################

echo "Logging connectivity of http://$resource/ to $outfile.csv CTRL+C to exit"

# LOOP
count=0
while [ 1=1 ]; do

        let count+=1
        
        time=$(date +"%T")
        timeSec=$(date +%s)
        duration=0
        
        # log
        wget -q --tries=1 --timeout=10 --spider "http://$resource/"
        if [[ $? -eq 0 ]]; then
                if [ ! -f "$upTmp" ]; then
                
                        echo $timeSec > $upTmp;
                        
                        if [ -f "$dwnTmp" ]; then
                                duration=$(($timeSec-`cat $dwnTmp`))
                                rm $dwnTmp;
                                
                        fi
                        
                        echo -ne CHECK $count: AVAIL     '\r'
                        echo "$count,$time,Up after being down for $(($duration / 60)) minutes and $(($duration % 60)) seconds" >> "$outfile.csv"

                fi
        else
                if [ ! -f "$dwnTmp" ]; then
                
                        echo $timeSec > $dwnTmp;
                        
                        if [ -f "$upTmp" ]; then
                                duration=$(($timeSec-`cat $upTmp`))
                                rm $upTmp;
                        fi
                        echo -ne CHECK $count: ERROR   '\r'
                        echo "$count,$time,Down after being up for $(($duration / 60)) minutes and $(($duration % 60)) seconds" >> "$outfile.csv"
                fi
        fi
done
#####

VN:F [1.9.9_1125]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.9_1125]
Rating: +1 (from 1 vote)
2,309 views

Desktop tidy

December 3rd, 2014

A cluttered desktop can be a problem, typically people use the desktop becuase they know the location of the files should they have downloaded them from somewhere, and need to reuse them quickly.

I have written a script that runs on Linux that cleans the desktop up on a daily basis, by moving all the files into a folder with an easily readable date name within an archive folder, so that your desktop remains clean and ordered, and you also do not lose your files.

The beauty of this is that you can configure your applications to point at the desktop, safe in the knowledge that all the clutter from today will be gone tomorrow, and placed neatly within a folder with the date so you can find it, when somebody says “I sent it to you Tuesday”

Just run the script below and it will automatically install, any clutter on the Desktop will archive to folder with yesterday’s date found within the Archive folder located on the Desktop.

You can download it here after unzipping, simply install using terminal with:

sudo chmod a+x desktop-tidy-install.sh
sudo ./desktop-tidy-install.sh

The source code is below:

#!/bin/bash
########################
#
#
# Install script
# For Desktop tidy, compat with any distro running Gnome 3, tested on fedora 20
#
# Adrian callaghan 02-12-2014
#
#
########################


########################
# are you capable?
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
	echo "You must run this install script with super user privileges, use either sudo or become root with su -"
	exit;
fi


########################
# enviroment
user=$SUDO_USER;
userhome="/home/$user";
scriptPath="/usr/local/bin/dt.sh";
autostartFile="dt.desktop";
desktop="$userhome/Desktop";
archive="$desktop/Archived";


########################
# reinstall?
if [ -f "$scriptPath" ] || [ -f "$autostartPath" ]; then
	echo "Removing previous install"
	if [ -f "$scriptPath" ]; then
		rm "$scriptPath"
	fi
	if [ -f "$autostartPath" ]; then
		rm "$autostartPath"
	fi
fi



########################
# create archive folder if none exists, permissions follow later
if [ ! -d "$archive" ]; then
	mkdir "$archive"
fi



########################
# create script
echo "#!/bin/bash" > $scriptPath;
echo "archive=$archive" >> $scriptPath;
echo "desktop=$desktop" >> $scriptPath;
echo 'curr_archive="$archive/$(date +"%d-%B-%Y" -d "1 day ago")";

# if has not been archived yet, archive
if [ ! -d "$curr_archive" ]; then

	mkdir "$curr_archive";

 	for file in $desktop/*; do
		if [ "$file" != "$archive" ]; then
			mv "$file" "$curr_archive"
		fi
	done
fi
' >> $scriptPath;
chmod 755 $scriptPath
chown "$user:$user" $scriptPath



########################
# Add autostart
if [ ! -d "$userhome/.config" ]; then
	mkdir "$userhome/.config"
fi
if [ ! -d "$userhome/.config/autostart" ]; then
	mkdir "$userhome/.config/autostart"
fi
echo "[Desktop Entry]
Name=DeskTidy
GenericName=Creates a daily desktop
Comment=Allows the user to have a clean desktop daily and keep the all the files in an ordered fashion
Exec=$scriptPath
Terminal=true
Type=Application
X-GNOME-Autostart-enabled=true
" > "$userhome/.config/autostart/$autostartFile";
chmod 755 "$userhome/.config/autostart/$autostartFile"
chown "$user:$user" "$userhome/.config/autostart/$autostartFile"



#########################
# Trigger script!
#
source "$scriptPath"
chmod "1775" "-R" "$archive"
chown "root:$user" "-R" "$archive"


#########################
# FEEDBACK
echo "!! Desktop Tidy successfully installed !!"
echo "When you login a desktop will be created based on todays date"
echo "Should you wish to retrieve an old file, archives can be found at $archive and are named by date"
VN:F [1.9.9_1125]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.9_1125]
Rating: +1 (from 1 vote)
3,479 views

Bash script to create virtual hosting in Fedora

August 15th, 2014

I am often needing to add a script to create virtual hosting, below is one I have written for fedora (that can be altered for any distro) that creates the necessary folder structure, vhost host entries and restarts Apache.

#!/bin/bash
 
#################################
# SETTINGS LOCATIONS
WWW_ROOT='/var/www' # no trailing slash
DOC_ROOT='httd_docs' # no trailing slash
 
# SETTINGS TEMPLATE FILE
INDEX_MSG='HOSTING READY FOR <DN>' # <DN> WILL BE REPLACED WITH THE DOMAIN
INDEX_FILE='index.html'
 
# SETTINGS DIRECTORY PERMISSIONS
DIR_OWNER='apache'
DIR_GROUP='apache'
DIR_MOD='770'
 
# APACHE (FEDORA)
APACHE_RELOAD='service httpd restart' # cmd to reload/restart apache
APACHE_CONF_LOCATION='/etc/httpd/conf/httpd.conf' # no trailing slash
APACHE_CONF_TEMPLATE="
# <FQDN>
<VirtualHost *:80>
    ServerAdmin webmaster@<DN>
    ServerName <FQDN>
    ServerAlias <DN>
 
    DocumentRoot <DN_ROOT>
    ErrorLog /var/log/httpd/<DN_SLUG>-apache-error_log
    CustomLog /var/log/httpd/<DN_SLUG>-access_log common
</VirtualHost>"; # <DN> WILL BE REPLACED WITH THE DOMAIN, FQDN WITH THE FQDN, DN_SLUG WITH THE DOMAIN SLUG AND DN_ROOT WITH DOCUMENT ROOT
 
# HOSTS FILE
HOSTS_FILE='/etc/hosts'
#################################
 
 
#################################
# FUNCTIONS
function notice() {
        echo "============================================================================================================"
        echo $1
        echo "============================================================================================================"
}
 
function slugify(){
	echo $* | sed 's/^dl-*//ig' | tr '[:punct:]' '-' | tr '[:upper:]' '[:lower:]' | tr -s '[:blank:]' '[\-*]'
}
#################################
 
 
 
#################################
# START
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
	notice "You must be root to run this script"
else
	# GET DN AND FQDN
	notice "Please enter the domain name"
	read DN
	DN="${DN/#\www./}"
	FQDN="www.$DN"
 
	# BEGIN 
	host $DN 2>&1 > /dev/null
	if [ ! $? -eq 0 ]; then
		echo "$DN is not valid domain"
	else
		DN_SLUG=$(slugify "$DN");
		if [ -d "$WWW_ROOT/$DN_SLUG" ]; then
			notice "$DN already exists in $WWW_ROOT/$DN_SLUG"
		else	
			# MAIN STRUCTURE
			mkdir "$WWW_ROOT/$DN_SLUG"
			mkdir "$WWW_ROOT/$DN_SLUG/$DOC_ROOT"
			echo "${INDEX_MSG//<DN>/$FQDN}" > "$WWW_ROOT/$DN_SLUG/$DOC_ROOT/$INDEX_FILE"
 
			# OWNERSHIP
			chown -R "$DIR_OWNER:$DIR_GROUP" "$WWW_ROOT/$DN_SLUG"
			chmod -R "$DIR_MOD" "$WWW_ROOT/$DN_SLUG"
 
			# QUICK LOOK UP LOCALLY
			HOSTS_FILE_BK="$(date +$HOSTS_FILE-%d%m%Y_%R.bak)";
			cp "$HOSTS_FILE" "$HOSTS_FILE_BK";
			if [ ! -f "$HOSTS_FILE_BK" ]; then
				notice "Failed to create host file backup at $HOSTS_FILE_BK"
			else 
 
				echo "# ${FQDN}" >> "$HOSTS_FILE";
				echo 127.0.0.1   ${DN} >> "$HOSTS_FILE";
				echo 127.0.0.1   ${FQDN} >> ""$HOSTS_FILE"";
 
				# APACHE ENTRIES
				APACHE_TEMPLATE="${APACHE_CONF_TEMPLATE//<DN>/$DN}";
				APACHE_TEMPLATE="${APACHE_TEMPLATE//<FQDN>/$FQDN}";
				APACHE_TEMPLATE="${APACHE_TEMPLATE//<DN_ROOT>/$WWW_ROOT/$DN_SLUG/$DOC_ROOT/}";
				APACHE_TEMPLATE="${APACHE_TEMPLATE//<DN_SLUG>/$DN_SLUG}";
				APACHE_CONF_LOCATION_BK="$(date +$APACHE_CONF_LOCATION-%d%m%Y_%R.bak)";
				cp "$APACHE_CONF_LOCATION" "$APACHE_CONF_LOCATION_BK";
				if [ -f "$APACHE_CONF_LOCATION_BK" ]; then
					echo "$APACHE_TEMPLATE" >> $APACHE_CONF_LOCATION;
					$APACHE_RELOAD;
					notice "$DN created at $WWW_ROOT/$DN_SLUG (apache bkup file found at $APACHE_CONF_LOCATION_BK)"
				else
					notice "Failed to create Apache config backup at $APACHE_CONF_LOCATION_BK"
				fi	
			fi
		fi
	fi
 
fi
read STOP
exit;
################################
VN:F [1.9.9_1125]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.9_1125]
Rating: 0 (from 0 votes)
16,188 views

Remote controlling Tivo

October 21st, 2012

I was interested in what my ethernet port was doing on my virgin media TIVO box, so I ran some tests and found I could control my TIVO box from my laptop, here are my findings.

First, I went into the Tivo boxes settings on screen and enabled network access.

Next, I logged into my home hub/router to find out what IP address it had been allocated
http://192.168.100.1/ and clicked devices.

Once I had its IP address, (192.168.0.7) I scanned its ports and found the following services:

adrian@adrian-laptop:~$ nmap 192.168.0.7
 
Starting Nmap 5.00 ( http://nmap.org ) at 2012-10-21 10:37 BST
Interesting ports on 192.168.0.7:
Not shown: 997 filtered ports
PORT     STATE SERVICE
443/tcp  open  https
2190/tcp open  unknown
2191/tcp open  unknown
 
Nmap done: 1 IP address (1 host up) scanned in 5.50 seconds

The obvious one that stands out is port 443, so visiting https://192.168.0.7/ shows a web server requesting login, I found that the username is tivo and the password is your media key found in settings > mediakey.

Once logged in, a list of recorded programmes will be displayed but however streaming and downloading are disabled :(.

I tried for sometime to circumvent the streaming restriction using various techniques the closest I came was with VLC and special plugins http://tivo-vlc.sourceforge.net/notes.php#install, but so far I haven’t been able to achieve this.

I looked into what the box is, and it turns out its fundamentally Linux box with a glossy coat, with some features disabled (like streaming something to do with UK copyright laws).

Along the way I found I could telnet to port 31339 on the box

telnet 192.168.0.7 31339

which responded with

CH_STATUS 0213 RECORDING

This is the status of the two tuners, and what they are doing, you can now use commands like:

Code:

KEYBOARD (Dunno what this does)

TELEPORT <PLACE>- e.g TIVO, LIVETV, GUIDE, and NOWPLAYING.

SETCH <CHANNEL> - Change channel. If the current tuner is recording a program, it will change the other tuner. If both tuners are recording, the TiVo will respond with "CH_FAILED RECORDING <Title>. Using this command while Tivo is replaying will give "CH_FAILED NO_LIVE".

FORCECH <CHANNEL> - This command will force the current tuner to the tune the desired channel regardless of what it's doing. If a recording is being recorded it will cancel the recording and change the channel without confirmation.

Also a complete set of IRCODE’s exist

Code:

IRCODE <COMMAND>

a quick google and I found the following IRCODE commands that seem to work.

UP
DOWN
LEFT
RIGHT
SELECT
TIVO
LIVETV
THUMBSUP
THUMBSDOWN
CHANNELUP
CHANNELDOWN
RECORD
DISPLAY
DIRECTV
NUM0
NUM1
NUM2
NUM3
NUM4
NUM5
NUM6
NUM7
NUM8
NUM9
ENTER
CLEAR
PLAY
PAUSE
SLOW
FORWARD
REVERSE
STANDBY
NOWSHOWING
REPLAY
ADVANCE
DELIMITER
GUIDE

Typing these commands into the telnet session, made the tivo box change channel etc…. cool!

To exit the telnet session press

Code:

CTRL + ]

thats right, control and right square bracket!!, then type quit at the prompt

I was able to source a nice GUI that can automate these commands https://github.com/wmcbrine/tivoremote

So, as long as you have Python installed (Mac & linux users by default), just running the script produces a nice GUI that can manage your Tivo box from your laptop.

I also found, if your interested in developing apps for it, its SDK is written for AS3 and can be found here http://developer.tivo.com/

VN:D [1.9.9_1125]
Rating: 8.1/10 (9 votes cast)
VN:D [1.9.9_1125]
Rating: +3 (from 5 votes)
35,650 views