Category Archives: Uncategorized

April 2012 events – Nothing will happen (Belgrade) – Richard Stallman speech (Zagreb)

Nothing will happen in Belgrade 2012

In the next coming week a few events are taking place over Belgrade and Zagreb, as usual on the middle of april I will attend for nista neće dogoditi (Nothing will happen), an tech unconference for hackers from former Yugoslavian countries. This year the conference is hosted inside the newborn “Hacklab Belgrade” on April 21 and 22, I’m really  eager to visit the hackerspace and to see on what the crew is up to. Nothing will happen is an unique event, no schedule, no plan, but all of sudden things come together, and that is the moment  where to prove your hacker attitude. Hope to see you in Belgrade.

How to get to the Hacklab: http://oosm.org/content/lokacija

 Richard Stallman: For a Free Digital Society

On Monday, 23th April 2012 18:00, at the Zagreb Museum of Contemporary Art, Richard Stallman will deliver a speech  on the subject “For a Free Digital Society”.

“Activities directed at “including” more people in the use of digital technology are predicated on the assumption that such inclusion is invariably a good thing.  It appears so, when judged solely by immediate practical convenience.  However, if we also judge in terms of human rights, whether digital inclusion is good or bad depends on what kind of digital world we are to be included in.  If we wish to work towards digital inclusion as a goal, it behooves us to make sure it is the good kind.”

23th April 2012 18:00
Richard Stallman “For a Free Digital Society”
Location:
Museum of Contemporary Art
Av. Dubrovnik 17, 10000 Zagreb, Croatia
www.msu.hr

Addmission: Free – No registration required.

Event coordinator: Tomislav Medak, tom@mi2.hr

Dirt cheap USB Temperature Sensor with python SMS alerting system.


In the last few weeks I had to design an effective and cheap temperature monitoring system for the server room. After searching a bit on the web I found this USB Thermometer Temperature dongle on Ebay, only 10 bucks with free shipping. As soon the sensor arrived, I plugged it into one Ubuntu based server and surprisingly worked immediately, below you can see the dmesg output.

[12737.064004] usb 2-1.3: new low speed USB device using ehci_hcd and address 6
[12737.161227] usb 2-1.3: configuration #1 chosen from 1 choice
[12737.164379] input: RDing TEMPer1V1.1 as /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.3/2-1.3:1.0/input/input6

Along with monitoring the temperature I wanted to have an alarming system that sends alarm SMS message to mobile phones when the temperature has passed a certain threshold. So I subscribed to textmagic, an SMS gateway provider. Textmagic has a good set of API, and of course they have the python API which I used to write my Pytemp2sms.py script.

USB dongle software and settings.

wget http://www.isp-sl.com/pcsensor-0.0.1.tgz
tar xvfz pcsensor-0.0.1.tgz
cd pcsensor-0.0.1
cp 99-tempsensor.rules /etc/udev/rules.d/
cp pcsensor /usr/local/bin/

Reboot the server.

To test the dongle run the pcsensor command .
You must get this kind of output.

2012/04/11 14:30:50 Temperature 60.58F 15.88C

SMS alarm.

Textmagic python API installation.

https://code.google.com/p/textmagic-sms-api-python/wiki/UserManual


apt-get install python-setuptools
easy_install PyTextMagicSMS

Pytemp2sms script.

Script download: http://bailey.st/code/bitsofpy/Pytemp2sms/


#!/usr/bin/python
import sys
import subprocess
import fileinput
import textmagic.client

#Temperature threshold in C
threshold = 5
#Balance threshold
credits = 100
#TextMagic account details, before using textmagic service
#you need to register and obtain an API password
#(different from your login password)
#
#https://www.textmagic.com/app/wt/account/api/cmd/password
username = "yourusername"
password = "APIpassword"
#Owner of the Textmagic sms account.This number will receive
#the credit balance .
owner = "+44phonenumberoftheowneraccount"

'''License: This software is distributed under
   the terms  and  conditions  of GPL  - GNU
   General  Public  License.'''

def usage():

    print " ------------------------------------------"
    print "|              Pytemp2sms                  |"
    print "|                                          |"
    print "|Temperature Sensor with sms alert system. |"
    print "|                                          |"
    print "|www.bailey.st                             |"
    print "|phillip@bailey.st                         |"
    print " ------------------------------------------ "

    print "\n"
    print "Usage instructions:"
    print "\n"
    print "Pytemp2sms.py checktemp | checkbalance"
    print "\n"

def checktemp():

    output = subprocess.Popen(["/usr/local/bin/pcsensor"], stdout=subprocess.PIPE).communicate()[0]
    output2 = output.split()[4]
    temp = output2[:2]

    if int(temp) > threshold:

        for phonebook in fileinput.input("/usr/local/bin/phonebook.txt"):

            client = textmagic.client.TextMagicClient(username, password)
            client.send("WARNING - Server room temperature above threshold!!! PLEASE CHECK!!!", phonebook)

    else:
        sys.exit()

def checkbalance():

    client = textmagic.client.TextMagicClient(username, password)
    balance = client.account()['balance']
    print balance

    if balance < credits:
        client.send("WARNING - Textmagic credit balance below threshold, please top the account", owner)

    else:
            sys.exit()

if len(sys.argv) < 2:
    usage()
    sys.exit()

if "checktemp" in sys.argv[1]:
        checktemp()

if "checkbalance" in sys.argv[1]:
        checkbalance()

Phonebook file.

The file phonebook.txt must contain all the mobile numbers that need to receive the alarm sms. Please follow this syntax:

+44numberone
+44numbertwo
+44numberthree

Crontabs.


*/30 * * * * /usr/local/bin/Pytemp2sms.py checktemp >/dev/null 2>&1
*/60 * * * * /usr/local/bin/Pytemp2sms.py checkbalance >/dev/null 2>&1

WordPress and Nginx

Apache is like Microsoft Word, it has a million options but you only need six. Nginx does those six things, and it does five of them 50 times faster than Apache.

Chris Lea on nginx and WordPress.

Nginx is a lightweight Web server with a small memory footprint and exceptional flexibility, along with this features the Nginx design is focused to ensure the maximum security. The configuration may look non-intuitive and not so straightforward, but a strong community and an excellent documentation will clear all your doubts. In this how-to I’m going to share my experience on moving a few WordPress blogs from Apache to Nginx, one of the blog is served inside the root directory and the other one is served as WordPress sub directory.

Please note, this how to applies to Ubuntu 10.04 LTS.

php5-fpm installation and configuration.

In order to serve PHP dynamic content we need to install php5-fpm.


deb http://ppa.launchpad.net/brianmercer/php/ubuntu lucid main
deb-src http://ppa.launchpad.net/brianmercer/php/ubuntu lucid main

apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 8D0DC64F
apt-get update
apt-get  install  php5-fpm

Once php5-fpm is installed we need to create a configuration file www.conf ,
located into /etc/php5/fpm/pool.d/ . Please copy the following values into it.


[www]

user = www-data
group = www-data
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 10
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
chdir = /

Restart the php5-fpm service.

/etc/init.d/php5-fpm restart

Nginx installation and configuration.

apt-get  install nginx

It wise to disable the default site configuration.

unlink /etc/nginx/sites-enabled/default

Now, let’s begin to create our first site configuration, the one
installed inside the root directory and served as www.example1.com .

In /etc/nginx/sites-available/example1.com paste, wich example1.com
is your domain name.

Example NR.1


server {
        listen   80;
        server_name  example1.com;

        access_log  /var/log/nginx/example1.com.access.log;
        error_log  /var/log/nginx/example1.com.error.log;

        location / {
                root   /var/www/example1.com;
                index  index.php index.htm;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }

}

To enable example1.com please create a soft link to:

sudo ln -s /etc/nginx/sites-available/example1.com /etc/nginx/sites-enabled/example1.com

Restart Nginx with # /etc/init.d/nginx restart and point the browser to your domain name.

Example NR.2, with wordpress served as www.example2.com/blog

In /etc/nginx/sites-available/example2.com paste, wich example2.com
is your domain.


server {
    server_name     example2.com;
    index           index.php;
    root            /var/www/example2.com;

        access_log  /var/log/nginx/example2.com.access.log;
        error_log  /var/log/nginx/example2.com.error.log;

if (!-e $request_filename) {
rewrite ^.+/?(/ms-.*) $1 last;
rewrite ^/files/(.+) /wp-includes/ms-files.php?file=$1 last;
rewrite ^.+/?(/wp-.*) $1 last;
rewrite ^.+/?(/.*.php)$ $1 last;
rewrite ^(.+)$ /index.php?q=$1 last;
break;
}

    location ~ .php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
}
}

To enable example1.com please create a soft link to:

sudo ln -s /etc/nginx/sites-available/example2.com /etc/nginx/sites-enabled/example2.com

Please restart the Nginx server and test your new blog # /etc/init.d/nginx and point the browser to www.example2.com/blog

Zenoss over SSL with Nginx reverse proxy.

Zenoss is an enterprise infrastructure monitoring tool that can give in real time the big picture of networks, applications, hardware performances and issues running from a small business to a cloud service. While using it I found the lack of a decent SSL support running out off the box, in order to overcome this issue I decided to use Nginx as reverse proxy server to handle and deliver Zenoss with the SSL support. For this example I’m using Zenoss a debian Native Stack installed on Ubuntu server 10.04

Zenoss download:

http://community.zenoss.org/docs/DOC-3240?noregister

Preparing zenoss:

You need to locate the file zope.conf, which in this case is locate into /usr/local/zenoss/zenoss/etc/zope.conf , and find the line that contains “# ip-address 127.0.0.1″ and uncomment it as follows.

# ip-address 127.0.0.1

to

ip-address 127.0.0.1

After you are saved the zope.conf file you need to restart the Zope server as zenoss user.

su – zenoss

zopectl restart

Nginx

You need to install Nginx and the openssl utilities, create an ssl directory to store the certificates and create the certificates.


apt-get install nginx openssl

mkdir /etc/nginx/ssl

cd /etc/nginx/ssl

openssl req -new -x509 -days 365 -nodes -out zenoss.pem -keyout zenoss.key

zenoss.key zenoss.pem

rm /etc/nginx/sites-enabled/default

touch /etc/nginx/sites-enabled/default


server {
    listen 443 default ssl;
    server_name myserver;

      ssl on;
      ssl_certificate      /etc/nginx/ssl/zenoss.pem;
      ssl_certificate_key  /etc/nginx/ssl/zenoss.key;

location / {
        rewrite ^(.*)$ /VirtualHostBase/https/serveripaddress:443$1 break;
        proxy_pass http://127.0.0.1:8080;
    }
}

Restart Nginx before the login.

/etc/init.d/nginx restart

Restarting nginx: nginx.

At this point everything should work smoothly, now you can test your new Zenoss over SSL pointing the browser to https://serveripaddress

Bits of python: import a CSV file into a MySQL database.

This is my first blog post of the series “Bits of python”, a journey into the Python programming language done with simple examples. From time to time I’ll write about Python and Django and how they interact with Unix and Linux systems. All the scripts available are stripped versions of my daily work, mostly file parsers, databases administration and reporting tools. This first example is about how to import a CSV (Comma-separated values) files into a MySQL database and can be very handy when you work with spreadsheets and databases.

The python modules used in this example are, the CSV  and the python-mysqldb, the first is already present into python and for the second one you can install it just with apt-get install python-mysqldb.

The sample code consist in three files, presidents.csv, presidents.sql and importCSV.py, can be downloaded from here, once downloaded the archive can be unpacked with tar xvfz csvintomysql.tar.gz . Now it’s time to take a look to our file, let’s go into csvintomysql directory, cd csvintomysql.

The presidents.csv file is the list of all the presidents of the United States of America and it look like this (the list goes more long):

Presidency , President, Took office, Left office, Party, Home State

1,George Washington,1789-04-30,1797-03-04,Independent ,Virginia
2,John Adams,1797-03-04,1801-03-04,Federalist ,Massachusetts
3,Thomas Jefferson,1801-03-04,1809-03-04,Democratic-Republican ,Virginia
4,James Madison,1809-03-04,1817-03-04,Democratic-Republican ,Virginia
5,James Monroe,1817-03-04,1825-03-04,Democratic-Republican ,Virginia

As you can see there are several fields delimited by a comma that need to be exported and inserted into the Mysql database using the python CSV module.

The presidents.sql file is the series of MySQL instruction to create a database called csvdb and a table called presidents. In order to keep simple the creation of the database you need to log into MySQL as root and from the database prompt type:


mysql> source presidents.sql
Query OK, 1 row affected (0.00 sec)

Database changed
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.02 sec)

The importCSV.py is the Python script that parse and insert the CSV data into the database, the connection credential are already configured to connect to the database csvdb with csv as user and csv as password. Please note, if you want to modify the credential you need to change the settings in the first place, precisley in the presidents.sql file. Do not use this script in production environment!!!!! till you changed the Mysql login credential for the csv user.

#!/usr/bin/python
#simple python csv parser that export Comma
#Separated Value data into a MySQL database.
#phillip@bailey.st
import csv
import MySQLdb
# open the connection to the MySQL server.
# using MySQLdb
mydb = MySQLdb.connect(host='localhost',
    user='csv',
    passwd='csv',
    db='csvdb')
cursor = mydb.cursor()
# read the presidents.csv file using the python
# csv module http://docs.python.org/library/csv.html
csv_data = csv.reader(file('presidents.csv'))
# execute the for clicle and insert the csv into the
# database.
for row in csv_data:

    cursor.execute('INSERT INTO PRESIDENTS(PRESIDENCY ,PRESIDENT \
            ,TOOKOFFICE ,LEFTOFFICE ,PARTY ,HOMESTATE)' \
            'VALUES(%s, %s, %s, %s, %s, %s)',  row)
#close the connection to the database.
cursor.close()
print "Import to MySQL is over"

Line 5 and 6 are the import module declaration.

Line 9 to 12 are the MySQL connection credential.

Line 13 prepare the cursor to handle the connection.

Line 16 the csv.reader will read and parse the presidents.csv file.

Line 19 a for loop will be performed.

Line 21 will execute the insert into PRESIDENTS table query.

Line 25 will close the database connection.

You can run the script with:

root@:# python importCSV.py
Import to MySQL is over

After the

mysql> use csvdb;

select * from PRESIDENTS;


+----+---------------------+------------+-----------------------------+------------+------------+-------------------------------------------+---------------+
| id | cur_timestamp       | PRESIDENCY | PRESIDENT                   | TOOKOFFICE | LEFTOFFICE | PARTY                                     | HOMESTATE     |
+----+---------------------+------------+-----------------------------+------------+------------+-------------------------------------------+---------------+
|  1 | 2012-02-22 23:45:05 | 1          | George Washington           | 1789-04-30 | 1797-03-04 | Independent                               | Virginia      |
|  2 | 2012-02-22 23:45:05 | 2          | John Adams                  | 1797-03-04 | 1801-03-04 | Federalist                                | Massachusetts |
|  3 | 2012-02-22 23:45:05 | 3          | Thomas Jefferson            | 1801-03-04 | 1809-03-04 | Democratic-Republican                     | Virginia      |
|  4 | 2012-02-22 23:45:05 | 4          | James Madison               | 1809-03-04 | 1817-03-04 | Democratic-Republican                     | Virginia      |
|  5 | 2012-02-22 23:45:05 | 5          | James Monroe                | 1817-03-04 | 1825-03-04 | Democratic-Republican
+----+---------------------+------------+-----------------------------+------------+------------+-------------------------------------------+---------------+

I hope the example will be useful to understand how to work with spreadsheets and CSV data sets. If you have doubts or questions, please leave a comment on the post. All the code is freely available at http://bailey.st/code/bitsofpy/csvintomysql/

Best.