Send Email when IP Address Changes

I have a ubuntu linux box in my office that I occasionally access from home. But unfortunately its IP address is constantly changing due to the dynamic IP allocation policy. Here’s how I set up a “daemon” that will send myself an email upon the change of the machine’s IP address.

1. Setup Gmail and sSMTP

This time we are using sSMTP because it’s easy, and Gmail because it’s free.

I would prefer to create a new Gmail account specific only for this purpose. Use your creativity to create long and obfuscated password, e.g. with mkpasswd -m sha-512 yOuRp4ssW0rD you can get a long string which is should be very nice for password.

Next, install sSMTP and its mail “client”:

sudo apt-get install ssmtp mailutils

Then edit the config file at /etc/ssmtp/ssmtp.conf:

sSMTP is not a daemon, so don’t worry about starting the service or such.

Next, test your setup:

echo "test message" | mail -s "testing ssmtp"

2. The Script

This time we use Bash, because you might not realize that you’re already fluent with Bash.

# check and send ip address to email

MYIP=`ifconfig eth0 | grep 'inet addr'| awk '{print $2}' | cut -d ':' -f 2`;


if [[ ${MYIP} != ${LASTIP} ]]
        echo "New IP = ${MYIP}"
        echo "sending email.."
        echo -e "Hello\n\nTimestamp = ${TIME}\nIP = ${MYIP}\n\nBye" | \
                /usr/bin/mail -s "[INFO] New IP";
        echo ${MYIP} > ${LASTIPFILE};
        echo "no IP change!"

Save this anywhere in your home folder. I personally have my own /home/username/bin/ to keep my small scripts and tools, and I have it in the system path ($PATH).

This script will save your current eth0‘s IP address to the hidden file .last_ip_addr. The next time this script is called, it will check the last IP address, if it’s different then it will notify to the given email address.

3. Cron
To make this run periodically, add the script as a cron job. More detail on cron you can STFG (Search The Fine Google).

crontab -e

Then add this to run the script every 30 minutes

*/30 * * * * /home/username/bin/


How To Change/Override Linux Password from other Linux PC

Or if you have linux running on an SD card (e.g. Raspberry Pi) and you want to change the password from another your Linux PC, here’s how to do it.

1. Mount the target system on your linux PC. If it’s a Raspberry Pi SD card, simply plug it in. Now let’s say the mount point is /media/stick, and inside that folder you will find system folder such as /etc, /dev, /proc, and others.

2. Information of user and passwords in most linux systems are kept in a text file, consecutively /etc/passwd and /etc/shadow. What we need to change is the latter. Open the shadow file (use sudo cat /etc/shadow), and see the entry for the user whom you want to change the password. The entry contains 9 fields, separated by colon (“:”). More detail on this type man shadow on terminal. Our interest lies on the second field, which is the encrypted password field. This field has format of following:


Now look into the format of your shadow file, if the id is 6, most likely SHA-512 encryption is used. The other possibilities are MD5 (id 1) and SHA-256 (id 5).

3. We will use mkpasswd, a front-end for crypt, the function for linux password encryption. To create a new password with SHA-512 encryption, do this:

mkpasswd -m sha-512 <password> <salt>

You can pick anything for the password, but for salt you need to give 8-16 random sequence of characters. If salt is empty, mkpasswd will generate a random salt, hence everytime you call mkpasswd it will give different result. For shadow, make sure you give in your salt. For example:

ariandy@linux:~$ mkpasswd -m sha-512 mypassword OhIuVG9LLE79.5XV

Now put this output in the second field of /etc/shadow file. Note that hashed password contains no colon, because colon is the delimiter between fields in shadow.


Running roscore and Launching ROS nodes as Background Process

I access my ROS running robot wirelessly using secure shell (SSH). To run my program, I have to first run all the startup scripts such as roscore and my robot’s driver. It’s kind of tedious to open a lot of shells just to keep this services on. And I can’t simply run this on background by using & operator because sometimes I need to check the node’s output.

So to keep it simple and neat, I made simple script to run roscore and robot driver on background, but still be able to check the outputs of this two (e.g. error messages).

First thing first, I like to have my own bin folder, to keep my own scripts.

cd ~
mkdir bin
echo "export PATH=$PATH:/home/ariandy/bin" >> ~/.bashrc
source ~/.bashrc

Then all this scripts will be kept inside this folder. If you need to run roscore and some nodes as a startup script, it will be better if you keep this scripts in /usr/local/bin/ folder.

# file:

source /opt/ros/fuerte/setup.bash
export ROS_PACKAGE_PATH=$ROS_PACKAGE_PATH:/home/ariandy/youbot_driver:/home/ariandy/applications:/home/ariandy/ros_stacks


This is for my node:

# file:

source /opt/ros/fuerte/setup.bash
export ROS_PACKAGE_PATH=$ROS_PACKAGE_PATH:/home/ariandy/youbot_driver:/home/ariandy/applications:/home/ariandy/ros_stacks

# this is my driver
roslaunch youbot_oodl youbot_oodl_driver.launch
# or your own node/launch script
#roslaunch {your_package} {your_thing}

The main tool for our topic is linux’ “screen“. Install it first if you don’t have it.

# file:

echo "running roscore daemon.."
screen -dmS roscore
sleep 2
echo "running youbot oodl daemon"
screen -dmS oodl
echo "done. view with screen -ls"

The format is screen -dmS [any_name] [your_script]. The -dm argument will tell screen to run this session as a daemon. Then we use -S argument to give the session a name, so it will be easier for later. Please note that if your_script is not located on system path folder (e.g. /usr/bin/, /usr/local/bin/, etc.), you have to give the full path for the screen argument.

roscore needs some time (1-2 seconds) to reach its full operational state. That is why I give 2 seconds delay (with sleep 2) before running my node.

With this done, then we can run the things on the background:

running roscore daemon..
running youbot oodl daemon
done. view with screen -ls

To view what are the running sessions, call screen -ls

There are screens on:
	9285.oodl	(05/08/2013 05:01:50 PM)	(Detached)
	9224.roscore	(05/08/2013 05:01:49 PM)	(Detached)
2 Sockets in /var/run/screen/S-ariandy.

The format is [pid].[name]. Use this name if you want to go to each session: screen -r name.

When we’re inside the screen session, Ctrl-C will send a signal to the program we are running inside screen, makes it quitting and then the screen session closes. We don’t want this. What we want is to go back to our original shell session, and put the screen session back as background process. We do that by using key combination Ctrl-A-D, that is while holding Ctrl, press A, then press D.

Forking Own Repo on Github

In some cases I need to develop a new project which is based my other project. Some people suggest to do branching but that was not exactly what I needed, because I need to have a new name.

So, after reading several sources (this and this), this is how I fork my own repo (please note that I did this under linux):

git clone your_new_repo
cd your_new_repo/

Now edit the Git configuration file (your_new_repo/.git/config) using your favorite editor, and find this lines:

[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url =

Then update the url by replacing “your_old_repo” with “your_new_repo“, so it will look like this:

url =

After that:

git push origin master

WiFi Access Point with TP-Link TL-WN722n on Ubuntu 12.04

My system’s configuration:
– Ubuntu 12.04 Precise Pangolin
– TP-Link TL-WN722n USB WiFi Dongle

– Slow network performance, getting only 3-10Mbit/s
– With N-Mode activated, connection drops after a while



1. Network configuration

First edit /etc/network/interfaces, remove anything related to wlan0 (or whatever your device’s name) and add this lines to set the IP address of the wlan device as static:

auto wlan0
iface wlan0 inet static

Although the configuration is already set, but in my system somehow it fails to set the IP address. So to make sure the setting will work, add ifup wlan0 inside /etc/rc.local file just before the exit 0:

#!/bin/sh -e
# rc.local


ifup wlan0

exit 0

2. hostapd installation

hostapd is the daemon who is responsible for broadcasting the access point and managing the connections. Rather than using hostapd package provided by Ubuntu repository, I would prefer to get the latest revision of hostapd from the developer’s git, then compile it manually. I do this because I want to enable the WiFi N-mode support.

But, installation from source will only give hostapd binaries, while we need several config files to run hostapd automatically as a service. I am no linux/Debian expert so I will just install hostapd from the repository, just to get the service configuration at /etc/default/, /etc/init.d/, and other places, then uninstall or remove the hostapd binaries.

git clone git://
cd hostap/hostapd

Then inside this folder, copy the defconfig file into a new file named .config, then open it using your favorite editor. For my setup I only need to activate (by uncommenting) the nl80211 driver and the N-Mode:


Before installing hostapd, we need to install some dependencies:

sudo apt-get install libnl1 libnl1-dev

Then after that, compile and install hostapd:

sudo make install

The resulting binaries are hostapd and hostapd_cli located by default at /usr/local/bin/.

Now we can do a test run. Edit the config file /etc/hostapd/hostapd.conf:


# to enable N-Mode
# UPDATE: N-Mode is still problematic

# config for WPA security

Make sure you don’t have trailing whitespaces, because hostapd is very sensitive. Now run hostapd:

sudo hostapd -dd /etc/hostapd/hostapd.conf

If nl80211 driver fails to start, quite possibly because NetworkManager is still managing the wireless network. Turn off the wlan management from NetworkManager by doing this on terminal (ref.):

sudo nmcli nm wifi off
sudo rfkill unblock wlan

If no problem exist, the output would be somehow like this:

random: Trying to read entropy from /dev/random
Configuration file: /etc/hostapd/hostapd.conf
nl80211: interface wlan0 in phy phy0
rfkill: initial event: idx=0 type=1 op=0 soft=0 hard=0
nl80211: Using driver-based off-channel TX
nl80211: Add own interface ifindex 4
nl80211: Set mode ifindex 4 iftype 3 (AP)
nl80211: Setup AP - device_ap_sme=0 use_monitor=1
nl80211: Create interface iftype 6 (MONITOR)
nl80211: New interface mon.wlan0 created: ifindex=7
nl80211: Add own interface ifindex 7
BSS count 1, BSSID mask 00:00:00:00:00:00 (0 bits)
nl80211: Regulatory information - country=CN
nl80211: 2402-2482 @ 40 MHz
nl80211: 5735-5835 @ 40 MHz
nl80211: Added 802.11b mode based on 802.11g information
Allowed channel: mode=1 chan=1 freq=2412 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=2 freq=2417 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=3 freq=2422 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=4 freq=2427 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=5 freq=2432 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=6 freq=2437 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=7 freq=2442 MHz max_tx_power=20 dBm
Allowed channel: mode=1 chan=8 freq=2447 MHz max_tx_power=20 dBm


nl80211: ifindex=4
nl80211: beacon_int=100
nl80211: dtim_period=2
nl80211: ssid - hexdump_ascii(len=8):
     59 6f 75 42 6f 74 41 50                           MyAccessPoint        
nl80211: hidden SSID not in use
nl80211: privacy=1
nl80211: auth_algs=0x1
nl80211: wpa_version=0x2
nl80211: key_mgmt_suites=0x2
nl80211: pairwise_ciphers=0x10
nl80211: group_cipher=0x10
wlan0: Event RX_MGMT (20) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event TX_STATUS (18) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received

This lines

wlan0: Event TX_STATUS (18) received
wlan0: Event TX_STATUS (18) received
wlan0: Event RX_MGMT (20) received
wlan0: Event RX_MGMT (20) received

Will show up when another PC/client is probing or scanning our Access Point. This is a good sign. Now quit the test run by pressing Ctrl-C

The next step to configure the Ubuntu services so hostapd could start automatically upon booting. First, edit /etc/init.d/hostapd file, and make sure the variables are correct:


Second, edit /etc/default/hostapd

DAEMON_OPTS="-dd -t";

And now we can manage the hostapd through Ubuntu’s service, and it will run automatically upon booting.

sudo service hostapd restart

For more information about managing the service, this could be a good reading.

3. DHCP and DNS

For DHCP purpose we are going to use dnsmasq because of the simplicity of configuration. Please note that dnsmasq might be not suitable for big network.

But one thing worth noting is that Ubuntu 12.04 (Network-Manager) is using dnsmasq as DNS resolver. We have to disable it so we can use dnsmasq as our DHCP and “DNS” server. To do this, edit /etc/NetworkManager/NetworkManager.conf file and put a # (comment sign) in front of dns=dnsmasq so it will look like this:


For more information about this, check this out.

Now we can configure dnsmasq to fit our need

sudo apt-get -y install dnsmasq

It will create default complete config file /etc/dnsmasq.conf, which is very useful for reference. For the sake of readability let’s just rename that file and make a new empty config file:

cd /etc/
sudo mv dnsmasq.conf dnsmasq.conf.orig
sudo touch dnsmasq.conf

Then edit the newly created file, and fill that with this basic configuration:


Now we’re done. Restart the server/PC and make sure everything works. We can check the log at /var/log/syslog anytime to see our DHCP server in action.

Sometimes I got problem that dnsmasq is not running automatically upon booting, this could be because the runlevel of dnsmasq is called before the networking devices are up. The easiest hack is to put the service restart command in the /etc/rc.local:

#!/bin/sh -e
# rc.local


ifup wlan0

sleep 5
service dnsmasq restart

exit 0

Raspberry Pi Backup and Restore from Linux

0. Preparation

Before backing up the SD Card of Raspberry Pi, do clean up the system first to remove unneeded files such as package source codes and apt-get caches. You might be surprized by how much apt-get is keeping cache of downloaded packages. It was nearly 600MB for me. Cleaning this up would give you smaller backup image.

df -h
sudo apt-get clean
df -h

See how much space you free’d after cleaning apt-get’s cache.

I like to keep a piece of information, that tells me that the system is in the state of just being restored. I do that by either editing the MOTD (Message of The Day) or making an empty file on my home folder “THIS_IS_JUST_RESTORED”.

To back up the SD Card, first plug the SD Card into the SD Card reader of your laptop/PC that runs Linux. I use Ubuntu 12.04 Precise Pangolin. Then get any files that you need to copy, after that unmount the SD Card. Default Raspbian installation has 2 partitions made on the SD Card, so do not forget to unmount both. To check which folder is mounted to which device, use df -h and see the lines that start with /dev/mmcblk0p1 and /dev/mmcblk0p2. Then unmount the corresponding folders:

sudo umount /media/first_sd_partition
sudo umount /media/second_sd_partition

1. Backup

To back up the SD card, what we are about to do is making an image of the device, in this case both of the SD card partitions. For Linux, we have dd. I personally use dcfldd, an enhanced version of dd. It gives progress percentage, and also multiple on-the-fly hash calculation. To install dcfldd, in ubuntu simply:

sudo apt-get install dcfldd

If you want the backed up image to be as small as possible, you have to compress the image of the SD card. In Linux it is possible to compress an image which is currently being backed up (on-the-fly compression). With this you can save your hard disk space, because if you’re making an image without on-the-fly compression, you will require at least the same size as the SD card. If your have 8GB SD card, although only used partially, the resulting image from dd or dcfldd will be around 8GB in size.

To backup with on-the-fly compression:

sudo dcfldd bs=4M if=/dev/mmcblk0 hash=sha1 hashlog=./image.img.sha1sum | gzip > image.img.gz
sudo sync

And we’re done.

Everytime after you run dd or dcfldd, do not forget to call sudo sync to flush system buffers. I forgot to do this once and my system goes all crazy and weird.

If you want to do it the long way, you can do backup without compression:

sudo dcfldd bs=4M if=/dev/mmcblk0 of=./image.img hash=sha1 hashlog=./image.img.sha1sum
sudo sync

Then if you realize that it takes too much space, you can compress it anytime with gzip:

gzip image.img

Please note that it will take a while, since we’re dealing with gigabytes of data.

I also like to watch the image file grow in real time, so I do this:

watch ls -lh image.img*

2. Restore

If you have your image file already compressed, you can either uncompress and then restore, or uncompress while restore.

I find uncompressing and restoring in the same time (on-the-fly) is the most efficient way:

gunzip -c image.img.gz | sudo dcfldd bs=4M of=/dev/mmcblk0 hash=sha1 hashlog=./hash.log
sudo sync

Again, do not forget to flush the system buffer by calling sudo sync.

This hash thing, is for making sure that the backed up and restored image are consistent, not broken in any way which might happen during transfer/copying or upload. After the process finished, compare both of the hashes (image.img.sha1sum and hash.log) and make sure they are identical. You don’t need to read both files manually, just tell linux to do it:

diff -sq image.img.sha1sum hash.log

This will tell you either both files are identical or not.

If you are bored and have a lot of free space in your hard disk, you can do the restoring process in the long way by first uncompressing the image, then write it to the SD card:

gunzip image.img.gz
sudo dcfldd bs=4M if=./image.img of=/dev/mmcblk0 hash=sha1 hashlog=./hash.log
sudo sync

Streaming OpenCV Output Through HTTP/Network with MJPEG

If you want to stream your OpenCV output image to another device which connected to the same network, one way is to write the OpenCV output as MJPEG file, then stream this file through HTTP.

Please note that:
– This might be not the best way (correct me if I’m wrong)
– OpenCV 2.3 cv::VideoWriter has memory leak bug

0. OpenCV Stuff
I assume you already have your OpenCV libraries installed, because several of OpenCV’s dependencies are also MJPEG-Streamer’s, such as libv4l-dev and libjpeg-dev. And make sure your OpenCV application works (it writes the mjpeg file)

1. Install MJPEG-Streamer
Install the dependencies first

sudo apt-get install imagemagick

Then get the latest MJPEG-Streamer from the repository:

git clone
cd mjpg-streamer/mjpg-streamer
make USE_LIBV4L2=true clean all
sudo make DESTDIR=/usr/local install

Then set the environment variable LD_LIBRARY_PATH if you haven’t, either in /etc/bash.bashrc or your own ~/.bashrc, add this line:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

2. Into The Main Show
First fire up your OpenCV application, this is my application, simple background subtraction and writes the output into mjpg file.

git clone
cd bgsubtract/
make bgsubtract2

Prepare the folder to put the mjpg file into, for example in my home folder:

mkdir /home/ariandy/mjpg

Then run the application:

./bgsubtract2 /home/ariandy/mjpg/out.mjpg -bgs

Leave it running in one terminal, and open another terminal to test the MJPEG-Streamer:

mjpeg_streamer -i " -f /home/ariandy/mjpg" -o " -w /usr/local/www"

The command above is the most basic setting to get the streaming to work. By default, the web server is listening to port 8080. If you want to use port 80, you have to run the command as root (or with sudo).

The default www root of MJPEG-Streamer is located at /usr/local/www. There you can find the demo pages, from which you can get the idea of several ways to display the stream: either direct stream (supported by most Grade-A Desktop Browsers (Sorry, IE!)), using Java MJPEG viewer (cambozola), javascript, etc.

3. Viewing The Stream
On the client, simply point the browser to the server’s IP address with corresponding port (8080). e.g. server’s IP address is, then to access it from the client, point to If you want to omit the :8080 part, then you have to run the server on port 80 (HTTP), as following:

sudo mjpeg_streamer -i " -f /home/ariandy/mjpg" -o " -w /usr/local/www -p 80"

I tried this with Google Chrome, Firefox, Android Browser, and Firefox for Android.


Making Raspberry Pi SD Card Backup in Linux

$ sudo dd if=/dev/mmcblk0 of=/path/to/image/file.img bs=4M

/dev/mmcblk0 argument depends on your system. In some system this argument could be /dev/sdX where X is the “device number” that points to the SD card. What is X could be known from:

$ sudo fdisk -l

Make sure you point dd to the device (e.g. /dev/mmcblk0, /dev/sdd), not the partition (e.g. /dev/mmcblk0p1, /dev/sdd1).

Making an image of 8GB SD card will take a long time, and dd won’t give any progress update whatsoever. It’s done, when it says it’s done (Walter White, Breaking Bad. LOL). It took 10 minutes (14.3MB/s) with my laptop. The only way to know the progress is by opening other terminal and check what is the size of the image file. The final size of the image file is same as the size of your SD card. OR you can use one front-end (?) of dd, namely dcfldd.

Before unplugging the SD card don’t forget to flush the buffer/cache:

$ sudo sync

Calculate the SHA1Sum of the image for future purposes. For huge file like this there’s a chance that it will get damaged when you do a lot of moving and transfer.

$ sha1sum file.img >> file.img.sha1sum

This will save the sha1sum into a file named file.img.sha1sum. After this you can compress it, transfer it, anything. Then, before restoring this image back into SD card, calculate the SHA1 once again and compare it to the original SHA1.

To compress the image use this:

$ cd /path/to/image
$ gzip file.img

This will “throw” the empty bits of the image and squeeze the file only with bits that actually contains data.

Restoring The Image

To restore the image first decompress the file

$ gunzip file.img.gz

then use dd

$ sudo dd if=/path/to/image/file.img of=/dev/mmcblk0 bs=4M

don’t forget to flush the cache by

$ sudo sync

– sha1sum checking

How To Disable Ubuntu 12.04 Precise Pangolin Login Sound

One thing I hate from this release is that there is no easy way to turn off the annoying login sound. Hello ubuntu developer? Is it hard to make a tick box in the settings to enable/disable system sounds?

Anyway, while we’re waiting for the developers to fix this issue, we can work this thing out by renaming or removing the sound file of that login sound. Fire up Terminal, then:
$ cd /usr/share/sounds/ubuntu/stereo
$ sudo mv system-ready.ogg system-ready-OLD.ogg

With this, the system won’t be able to find the login sound file, hence it won’t play any login sound.

We can also use this trick to change the login sound with your own sound file, but first we have to convert our sound file into OGG format. The easiest way is using ffmpeg in terminal:
$ ffmpeg -i cool_sound.mp3 system-ready.ogg

Then copy the newly created system-ready.ogg into the directory /usr/share/sounds/ubuntu/stereo.

VLC’s Dynamic Range Compression Starter Settings


Here’s the Dynamic Range Compression settings to make your movie more fluid, no sudden loud sound but still audible dialogs.

RMS/Peak 0
Attack 50 ms
Release 300 ms
Threshold -20 dB
Ratio 20.0 : 1
Knee Radius 1.0 dB
Makeup Gain 12.0 dB

We can’t change the settings with exact values, so just move the slider at least close to the values.

Slider can be precisely moved by pressing keyboard arrow up and down after clicking on  the slider. Thanks, Austin!