Wednesday, 18 March 2015

MySQL Cross database foregin keys

Here is a small query to display all foreign keys across different databases. May come in very handy when deciding which database to restore first :)

USE information_schema;


Thursday, 12 March 2015

Last modified date/time for CakePHP projects

What is the last modification date of a CakePHP project? To answer that you would probably have to ask what is the latest date and time that any file was modified in your CakePHP project sub-folders. These sub-folders are usually Model, View, Controller, webroot and perhaps Vendor or Console.

In order to solve this in Linux, I crafted the following bash script:


BASE_PATH="/var/www/html/MyProject/app"           # replace with your own
SUB_COMPONENTS="Model View Controller webroot"    # add folders as needed

  RESULT=`find $SUB_PATH -type f -exec stat --format '%z' "{}" \; | sort -r | head --bytes=16`
  echo $RESULT
 done | sort -r | head --lines=1 )

exit 0

the idea is to get all files in each of the paths, contained in the $SUB_COMPONENTS variable, using the find command. Then execute stat to retrieve the last modification datetime, sort the results in reverse order and finally use head to retrieve the first 16 characters which make up the first YYYY-mm-dd HH:ii characters of the timestamp.

The entire result of the for loop is then fed to sort once more to create the list with the highest time stamp being first. Finally we use head again to throw away all output lines apart from the first.

An example of using this in CakePHP controller code would be something like:

    const LAST_MODIFIED_COMMAND = '/opt/bin/cakeLastModified';


    public function about()
        $this->set('lastModified', exec(self::LAST_MODIFIED_COMMAND));

... and then display the value of the $lastModified variable in the corresponding about view.

Note: Once again, I would like to give credit to the good people at for providing answers to all the minor problems that made this one up. So this code would not be here if l0b0 had not provided such a concise and clear answer to Sorting in shell script and if How to recursively find and list the latest modified files in a directory with subdirectories and times? did not have a working answer.

Saturday, 14 February 2015

Java: Read String from console

Once again, I was out there trying to find the neatest solution for reading a string from the IDE console. It turns out that the shortest piece of code that one can write to achieve this would be :



     public static String getString() throws IOException
        try (BufferedReader br = new BufferedReader(new InputStreamReader( {;
            return br.readLine();

Wednesday, 15 October 2014

Listbox mnipulation with jQuery

This is my easy to paste reference code for list-box manipulation using jQuery. By the way, the HTML <input "type"="select"> element, will create what desktop programmers usually refer as a combo-box. To make the input display as a list box, we need to specify an additional size="N" attribute where N refers to the number of visible items of the list.

So, suppose that we have a select input somewhere in an HTML page and that we need to add a button that removes the selected item from the input's options list.

       // remove the selected item from the list box
            jQuery("#myListBox option:selected").remove();
            return false;

By the same token, we can also create an other button that empties the entire options list

        // remove all items from list box
            // check that there is something to remove
            if (jQuery("#myListBox option").length == 0)
                return false;

            // verify that user really wants to do this
            if (!confirm(''))
                return false;

            // empty list box
            jQuery("#myListBox option").remove();
            return false;

Finally, to add a new item at the end of the options box we can use a code fragment that looks more or less like this:

                    var newOptionhtml ='<option value="'
                        + '">'
                        + ' </option>';


Needles to say that all the above have been collected from various Stack Overflow questions and answers.

Saturday, 13 September 2014

GNOME3: How to enable desktop icons and right click menu

This is the third time I am looking this up, so I am making a quick howto note here.

So in order to enable desktop icons on a newly installed gnome3 desktop perform the following steps:

  1. Open the dconf-editor program.
  2. Locate the page following path org → gnome → desktop → background
  3. Check the Show desktop icons option.

Monday, 14 July 2014

CakePHP Find out the link that brough us to the current page

Most web applications today have some kind of menu build with anchor tags. The problem that the following script -- courtesy of my friend Anestis from -- solves, is how to determine the actual link that was used to bring the user to the currently displayed page.

To use it, place it inside a script tag towards the end of your app/Views/Layout/default.ctp file (just before the closing body tag, will do just fine) and a little bit of CSS code in your appropriate style file (again app/webroot/css/cake.generic.css is a good candidate).

The CSS code is pretty easy : {
    background-color: yellow; // add anything you like

and the javascript :

        <script type="text/javascript">
            // add the "active" class to the navigation link that brought us to this page
            jQuery( function() {
                // retrieve the relative url of the current page
                var curUrl = "<?php echo (Router::url( NULL, FALSE)); ?>";
                // in a cake application a relative URL is usually like
                // /application/controller/action/param1/param2 ...
                // so what we really need is the first three pieses of the URL
                var tokens = curUrl.split("/").slice(0,4);
                curUrl = tokens.join("/");
                // if there is any pagination information then the word "index" also appears in the URL
                // in this case we need to remove it, so it can match generated URL
                var indexIndex = curUrl.indexOf('index');
                if ( indexIndex > -1)
                    curUrl = curUrl.substring( 0, indexIndex - 1);

                // for each page anchor tag
                $('a').each( function() {
                    // retrieve the arnchor's target
                    var ref = $(this).attr("href");
                    // so if that anchor points to the current page
                    if(ref === curUrl){



Sunday, 18 May 2014

How to remove a particular host key from SSH's ./ssh/known_hosts file

I will leave the sed solution for the real gurus. As far as I am concerned the easy way to get the job down is use the ssh-keygen -R your_host command.

If you are working in a environment with a DNS suffix, then you will probably need a second invocation like: ssh-keygen -R your_host.your_domain.

Friday, 4 April 2014

Setting up Environment variables before Apache starts

That was the third time I had to look this up, so I am putting it down for reference.

On Red Hat machines, apachectl sources /etc/sysconfig/httpd, so any variables you set there will be available to the apache runtime environment. Debian based systems use /etc/apache2/envvars for the same purpose.

Thursday, 3 April 2014

Linux (EL6) Required packages for installing the 64 bit Oracle 12c Client

The Oracle documentation has a list of the packages required in order to install the database client software for Enterprise Linux 6.

Since the minimum versions requirements are satisfied on an updated EL6 system, all one has to do is just copy and paste the names into a single yum command in order to complete the step. Did it once this morning and I hope that if I ever have to repeat it, I will just copy and paste the following:

yum -y install binutils compat-libcap1 compat-libstdc++-33.i686 compat-libstdc++-33.x86_64 \
gcc gcc-c++ glibc.i686 glibc.x86_64 glibc-devel.x86_64 glibc-devel.i686 \
ksh libgcc.i686 libgcc.x86_64 \
libstdc++.x86_64 libstdc++.i686 libstdc++-devel.x86_64 libstdc++-devel.i686 \
libaio.x86_64 libaio.i686 libaio-devel.x86_64 libaio-devel.i686 \
libXext.x86_64 libXext.i686 libXtst.x86_64 libXtst.i686 \
libX11.x86_64 libX11.i686 \
libXau.x86_64 libXau.i686 \
libxcb.x86_64 libxcb.i686 \
libXi.x86_64 libXi.i686 \
make sysstat

PS: If not running this as root, remember to prefix this with sudo :)

Thursday, 20 March 2014

CakePHP-2 and AJAX The dependent list boxes problem (remake)


Back in 2010, I had written a post regarding the case of dependent list boxes in a CakePHP view. Back at those days CakePHP was at version 1.2 and support for Javascript and AJAX was very limited. Today I shall revise this using JQuery and JSON encoding which will make things simpler and easier to understand, implement and maintain.

The long story short

Suppose you have a page with two list boxes. One contains a standard set of values while the second one's list of values must be dynamically updated depending on the actual selected value of the first.

In our (sort of) real life example we have a list of commissions (aka production orders) that produce a series of products of varying lengths. The list of lengths that each commission is allowed to produce is available via a detail table and our goal is write an addProduct action and view that allows the user to specify the commission based on which the actual product was produced and the actual length of the product that should be one of the assigned commission lengths. The Product model has a commission_id and an actual_length fields. So each time the commission combo box changes the actual length field input options should also change in order to contain the commissions list of allowed lengths.

Getting Started

To begin with our tutorial make sure that your standard layout references the jQuery library. The easiest was to do this would be to open APP/View/Layout/default.ctp and make sure that a line like

<script src=""></script>

can be found somewhere in your html's head section.

The next thing that needs to be done is to add the RequestHandler component in our AppController. Add or modify your existing source so it looks more or less like this.

class AppController extends Controller {
    public $components = array(


Next we need to inform our routing system that it should also parse json URLs. So the line


should be added to the APP/Config/routes.php file right below the other Router::xxx() commands.

Create the AJAX method and view to return the JSON encoded list of lengths

The next thing to do is create the action that will return the list of lengths to be sent back to the view given commission id. The best place to put it will be the commissions controller. The code for the function looks a lot like the one baked by view. We just need to make sure that the data returned "contain" the correct detail information

    public function getRequestedLengths($id)
        if (!$this->Commission->exists($id)) 
            throw new NotFoundException(__('Invalid record'));
        $options = array(
            'conditions' => array(
                'Commission.' . $this->Commission->primaryKey => $id
            'contain' => array(
        $this->set('commission', $this->Commission->find('first', $options));

The view for the method should be placed in: APP/View/Commissions/json/get_requested_lengths.ctp.

 * Create and echo a json encoded list of the allowed lengths
$output = array();
if (!empty($commission['CommissionProduct']))
    foreach ($commission['CommissionProduct'] as $commissionProduct)
        $output[] = $commissionProduct['actual_length'];

echo json_encode($output);

So now if we point our browser towards http://yourserver/projectPath/Commissions/getRequestedLengths/7.json, we will receive a response with a JSON array containing all allowed lengths for commission id 7. The actual response will be something like ["45900","23400"].

Building the addProduct view

So far we have the mechanism to retrieve the required data. The final step will be to use it in the actual add product view, the PHP part of which should look more or less like this:

<div class="products form">
    <?php echo $this->Form->create('Product'); ?>
            <legend>Add Product</legend>
            <?php echo $this->Form->input('commission_id', array('empty' => __('Please select a commission'))); ?>
            <?php echo $this->Form->input('operator_id'); ?>
            <?php echo $this->Form->input('shift'); ?>
                echo $this->Form->input(
                    'type' => 'select',
                    'options' => $statusList
            <?php echo $this->Form->input('actual_length', array('type' => 'select')); ?>
            <?php echo $this->Form->input('gross_weight'); ?>
    <?php echo $this->Form->end('Save'); ?>

The final part will be the adding of Javascript code to make our form responsive.

<script type="text/javascript">
    var commissionsCombo;
    var allowedLengthsCombo;

    jQuery(function() {
        commissionsCombo = jQuery('#ProductCommissionId');
        allowedLengthsCombo = jQuery('#ProductActualLength');

        commissionsCombo.change( function() {
            var selectedCommission = this.value;  // or $(this).val()
            // build the url that contained the selected commission code
            var ajaxUrl =
                    '<?php echo Router::url(array('controller' => 'Commissions', 'action' => 'getRequestedLengths', 'admin' => FALSE), TRUE)?>'
                    + '/'
                    + selectedCommission
                    + '.json';

            // do a "synchronous" AJAX call
                    async: false,
                    cache: false,
                    url: ajaxUrl,
                    success: function(response) {
                        // remove all options from the allowed metres per bobbin

                        // add all returned values
                        for (var i = 0; i < response.length; i++) {
                            var currentKey = response[i];
                            var currentKeyDescr = response[i] + ' metres';
                            var optionText = '<option value="'
                                    + currentKey
                                    + '">'
                                    + currentKeyDescr
                                    + '</option>';

As a last statement The code for manipulating the select input options comes from the very consise post from

Thursday, 13 March 2014

CentOS 6.5 does not like my handware or their combionation

Spent the whole morning trying to install CentOS 6.5 on a relatively new machine using a Gigabyte GA-B85-HD3 motherboard, with a NVIDIA GeForce GT 620. The message I got was that the hardware (or a combination of what) I 'm using is incompatible with CentOS.

As I had Fedora 20 already running on this very machine, I figured that the problem was related to UEFI and wasted a lot of time trying to the get rid of the EFI partition on the Linux disk. Eventually after updating the BIOS and trying all sorts of magic. I disabled the on board Intel graphics adapter and everything worked like a charm.

Friday, 31 January 2014

CakePHP 2.x: Saving paging data in the session

Quite some time ago I wrote a blog post about saving CakePHP 1.x paging data in the session so that they can be available at next page visit. The basic idea was that you could store the page, sort and direction named parameters in the session and restore them back when no paging parameters were available.

When I tried applying the same technique in CakePHP 2.x, I run into a very serious obstacle and that was the fact that the Paginator::numbers() function does not anymore include the page:1 named parameter when creating the link for the first (or previous) page. This created a phenomenon that when someone visited a page without any paging parameters, it was impossible to know whether they were there because of a link to the first page or as a result of a redirect from somewhere else, in which case the session had to be checked and paging data to be restored.

The thing had been puzzling me for some days now. I tried different remedies without any luck or results until I cried for help at It was there that Ilie Pandia shook things a bit and then I managed, thanks to his advice, to create the following component that mimics the original Cake 1.x PaginationRecallComponent by mattc found in the Bakery, from which I borrowed the name and structure.

This version is new (March-2015) and hopefully includes the bug-fixes pointed out by all comments. The test where made using CakePHP version 2.6.3.

App::uses('Component', 'Controller');

 * Pagination Recall CakePHP Component
 * CakePHP 2.x version Copyright (c) 2014-2015 Thanassis Bakalidis
 * @author  Thanassis Bakalidis
 * @version  2.1
 * @license  MIT
 * @property SessionComponent $Sesion Session handler to save paging data into
class PaginationRecallComponent extends Component {
    const PREV_DATA_KEY = 'Paginaion-PrevData';

    public $components = ['Session'];
    private $_controller = NULL;
    private $_action = NULL;
    private $_previousUrl;

    public function initialize(\Controller $controller)
        $this->_controller = $controller;
        $this->_action = $controller->params['action'];

    public function startup(Controller $controller)
        $sessionKey = "Pagination.{$this->_controller->name}.{$this->_action}";

        // extract paging data from the request parameters
        $pagingParams = $this->_extractPagingParams();

        // if paging data exist write them in the session
        if (!empty($pagingParams)) {
            $this->Session->write( $sessionKey, $pagingParams);

        // no paging data.
        // construct the previous URL
        $this->_previousUrl = $this->Session->check(self::PREV_DATA_KEY)
            ? $this->Session->read(self::PREV_DATA_KEY)
            : [
                'controller' => '',
                'action' => ''

        // and check if the current page is the same as the previous
        if ($this->_previousUrl['controller'] === $this->_controller->name &&
            $this->_previousUrl['action'] === $this->_action) {
            // in this case we have a link from our own paging::numbers() function
            // to move to page 1 pf the current page, delete any paging data

        // we are coming from a different page so if we have any session data
        if ($this->Session->check($sessionKey))
            // then restore and use them
            $this->_controller->request->params['named'] = array_merge(

    public function shutdown(\Controller $controller)
        // save the current controller and action for the next time
                'controller' => $this->_controller->name,
                'action' => $this->_action

    private function _extractPagingParams()
        $pagingParams = $this->_controller->request->params['named'];
        $vars = ['page', 'sort', 'direction'];
        $keys = array_keys($pagingParams);
        $count = count($keys);

        for ($i = 0; $i < $count; $i++)
            if (!in_array($keys[$i], $vars))

        return $pagingParams;

Sunday, 12 January 2014

Enable MP3 on Fedora 20

A very short how to enable mp3 playback on your brand new fedora installation.

  1. Enable PRM Fusion repository.
  2. Install the vlc phonon-backend. (Fedora comes with GStreamer).
    . yum install phonon-backend-vlc
  3. Goto system settings → Multimedia → Audio and Video Settings. Select the backend tab. There should be two entries there: GStreamer and VLC. Select the VLC entry and click the Prefer buttom below the list. Finally click Apply. The final result should be something like this:
  4. Log out and back in for the changes to take effect.

After that you can play and kind of context directly from Dolphin, you can install additional music players like amarok, or vlc and enjoy the full music, audio and video experence.

yum install vlc
yum install amarok amarok-doc

Thursday, 7 November 2013

CakePHP New application database config (never forget the enconding)

Today I will put down the way to begin a new web application project using CakePHP.

The first part is database creation. Database charset must be utf-8 and collation: utf8_unicode_ci. The difference between general and unicode collations is explained in an excellent manner in this post on

Next, when you start a new CakePHP project the database config class looks like this

public $default = array(
  'datasource' => 'Database/Mysql',
  'persistent' => false,
  'host' => 'localhost',
  'login' => 'user',
  'password' => 'password',
  'database' => 'test_database_name',
  'prefix' => '',
  // 'encoding' => 'utf8',

My lesson today is: Before changing anything else, uncomment the last line!.

... in case you do not then Unicode (Greek in my case) text will still appear correctly in the web application, but phpMyAdmin and sqldump will display garbage. In addition searches with non-latin text will always fail. To make matters worse when I discovered the case of the problem, I realised that I would have to re-enter all my test data.

Friday, 1 November 2013

SchemaSync: An effective and simple way to synchronize MySQL databases

I have spend the last couple of days trying to find out a solution for migrating changes from a development database to the productive. I was looking for a clean, simple and reliable solution that (ideally) runs on Linux.

My first attempt was to to use the official MySQL mysqldiff command. It turned out that in my case, the only suggestion I got was to recreate indexes and drop primary keys every time there was a record number mismatch between tables. I also run into Windows GUI's with a 30 day evaluation period and a cost ranging from $90-$150.

My lack changes when I run into Schema Sync written in Python by Mitch Matuson. The page has everything you need and the setup (if you already have python) takes less that a minute.

Quoting from the utility's examples page, Sync the production db with the changes from the development db

 schemasync mysql://user:pass@dev-host:3306/dev_db mysql://user:pass@prod-host:3306/production_db

This will give you two files in your home directory, one to do the patching and one to revert back the changes if requested. A excellent piece of work, that I am very happy to use. Thumbs up for mr Matuson.

Saturday, 19 October 2013

Netbeans 7.x and Debian

Switched my laptop from Fedora 19 to Debian 7.1 for some peace, quiet and stability. It appears that the latest transitions to kernel 3.11 and the issues with the nvidia drivers were too much for it. So here I am, enjoying the Debian way of life without yum and gstreamer.

A goodie available only to Debian and Ubuntu users is the Oracle Java PPA available through this link. Andrew at webupd8,org has set up a PPA that downloads and installs the latest Oracle Java packages keeping your computer up to date along with the rest of normal updates.

So now it's Netbeans turn to get installed. I prefer to download the Java SE version and then manually add the PHP and CakePHP plugins that I require for my everyday use.

The first time I tried to install the normal way I ended up with an Exception: java.lang.NoClassDefFoundError thrown from the UncaughtExceptionHandler in thread "main". A little bit of digging revealed that that one way to install netbeans is to use the --silent installer option. The will install netbeans to the default /usr/local/netbeans-7.x location which is perfectly all right. After that you can run it from your desktop Development menu. So to start the installer just become root and type:

root@nb-thanassis:/home/thanassis/Downloads/Netbeans# ./ --silent

in a similar manner, in order to uninstall netbeans from your system, go to the installation directory and type

root@nb-thanassis:/usr/local/netbeans-7.4# ./  --slinent

There is one small thing that I noticed. in order for all this to work you must cd to the same directory as the installer script before issueing any commands. In my case -- hence the blog post -- all other attempts failed.


Monday, 7 October 2013

CakePHP locking tables

Here are my two cents on the issue.

The code below is a function from a behaviour that tries to create an additional unique key on a field named code, by counting the number of records created this year. The important part in the locking procedure is that we must specify the AS clause in the LOCK TABLES statement or otherwise the $model->find() function will not work complaining that the table is locked.

    public function getNextCode(&$model)
        $thisYear = date('Y');
        $dbo = $model->getDataSource();
            sprintf('LOCK TABLES %s AS %s WRITE;',
        $recordsThisYear = $model->find(
                'recursive' => -1,
                'conditions' => array(
                    $model->alias .'.code LIKE' => $thisYear.'%'
        $dbo->execute('UNLOCK TABLES');
        return sprintf('%d-%06d', $thisYear, $recordsThisYear + 1);

The original idea for the post and function cake from a doWeb posting available through here.

Friday, 14 June 2013

Using a raspberrypi as an sftp server

Following a previous post regarding how to use your raspberry-pi device as a file server, we are going to continue amd set up sftp service on the same pi device, so that it may be accessible over WAN.

The complete guide comes from a Mark Van den Borre posting available through this link.In our case however the steps are fewer, since raspberry has already the openssh server set up and running and if you have followed from the previous port we already have a user (bill) and a group (microsoft) to use for sftp service.

To get started let;s give our friend Bill a password:

pi@xena ~ $ sudo passwd bill 
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully

Next step will be to prevent Bill from interactively logging in. The usual remedy to this problem to use the sftp server as a login shell. After the post is over bill will not be able to access our pi from ssh either

pi@xena ~ $ sudo chsh bill 
Changing the login shell for bill
Enter the new value, or press ENTER for the default
        Login Shell [/usr/lib/tftp-server]: /usr/lib/sftp-server
pi@xena ~ $ 

Now for the sftp configuration itself. (Copying, pasting and adjusting from Mark's post we have something like this:) Open the default OpenSSH server configuration for editing:

pi@xena ~ $ sudo vi /etc/ssh/sshd_config

: and change the default sftp server from:

Subsystem sftp /usr/lib/openssh/sftp-server


Subsystem sftp internal-sftp

Some users can only use sftp, but not other OpenSSH features like remote login. Let's create a rule for that group of users. Add the following section to the bottom of /etc/ssh/sshd_config:

Match group microsoft
ChrootDirectory /mnt/SFTP-Data
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp

Thursday, 23 May 2013

CakePHP and AJAX submitting a form with jQuery

A couple of years back I wrote an article about how to handle the dependent drop down lists problem using CakePHP's Ajax facilities. Today i will put down a trivial example of how to submit a CakePHP created form using jQuery as a small reference that can be easily pasted.

Let me remind you of the CakePHP ajax way. You start by creating a controller method that will "return" the ajax content. For our trivial example, the following controller will be more than enough.

class AjaxController extends AppController {
   var $name = 'Ajax';
   var $uses = NULL;

   public function helloAjax()
       // result can be anything coming from $this->data
       $result =  'Hello Dolly!';
       $this->set("result", $result);

The corresponding view file view/ajax/hello_ajax.ctp should contain just the following:

<?php echo $result; ?>

Setting up our Ajax call is now as easy as, creating a link or a button that will invoke the asynchronous call and then setting the id of the field that will receive the result. A typical setup would be that the link looks something like this :

<a href="#" id="performAjaxLink">Do Ajax </a>

And then the target field can be created using:

<?php echo $this->Form->input('your_field', array('id' => 'resultField')); ?>

Finally a little script at the end of the file ...

                    async: true,
                    cache: false,
                    url: '<?php echo Router::Url(array('controller' => 'ajax','admin' => FALSE, 'action' => 'helloAjax'), TRUE); ?>',
                    success: function(response) {
                return false;

The jQuery Ajax API is available here.

Wednesday, 10 April 2013

Using a raspberry-pi as a UPS server with nut

In this post we will try to install the Network UPS tools on a Raspberry-Pi device, attach a USB connected UPS and use it as a UPS server that will allow all machines sharing the same UPS to shut-down correctly when the UPS runs out of power. Our server will look after two clients; one running EL5 and the other openSUSE 11.4.

At the end of the post we will demonstrate how easy it is to set up your clients once the server is up and running and provide additional instructions for setting up the client software on Fedora 18 and EL6.

Update 2014-02-02: Meanwhile things here at the office have changed. The openSUSE machine is now gone and has been replaced by one running Debian 7. I have now revised the client setup guides for Fedora and EL5, 6 and I also have added one for Debian. The openSUSE "howto" is left as is but I can no longer verify if it works or not :) ..

Server Setup

Before we begin I would like to confess that my first attempt to install a no-name made in China UPS resulted to total failure, so eventually I got an expensive APC BackUPS Pro, that worked without any problems from the beginning, so unless your UPS is one supported by the UPS network tools project drivers, don't even try to follow the tutorial.

A second remark, is that if you are following the tutorial as the standard pi user you will need to prefix almost all commands with sudo. To become root on a standard Raspbian and follow along, you will need to issue sudo su-. (Thanks Derek for pointing it out)

root@raspbx:~# apt-get install nut-client nut-server
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
Suggested packages:
  nut-cgi nut-snmp nut-dev nut-xml
The following NEW packages will be installed:
  libupsclient1 nut-client nut-server
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,583 kB of archives.
After this operation, 3,217 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 wheezy/main libupsclient1 armhf 2.6.4-2.3 [106 kB]
Get:2 wheezy/main nut-client armhf 2.6.4-2.3 [191 kB]
Get:3 wheezy/main nut-server armhf 2.6.4-2.3 [1,286 kB]
Fetched 1,583 kB in 2s (562 kB/s)     
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package libupsclient1.
(Reading database ... 37855 files and directories currently installed.)
Unpacking libupsclient1 (from .../libupsclient1_2.6.4-2.3_armhf.deb) ...
Selecting previously unselected package nut-client.
Unpacking nut-client (from .../nut-client_2.6.4-2.3_armhf.deb) ...
Selecting previously unselected package nut-server.
Unpacking nut-server (from .../nut-server_2.6.4-2.3_armhf.deb) ...
Processing triggers for man-db ...
Setting up libupsclient1 (2.6.4-2.3) ...
Setting up nut-client (2.6.4-2.3) ...
[info] nut-client disabled, please adjust the configuration to your needs.
[info] Then set MODE to a suitable value in /etc/nut/nut.conf to enable it.
Setting up nut-server (2.6.4-2.3) ...
[info] nut-server disabled, please adjust the configuration to your needs.
[info] Then set MODE to a suitable value in /etc/nut/nut.conf to enable it.

Don't worry about the nut-server information we shall deal with it later on. Now an optional step that will allow us to to use the lsusb utility will be to install the usbutils package, assuming that it is not already there. So:

root@raspbx:~# apt-get install usbutils

.. and then -- blame me for my Windows habits, I firmly suggest a reboot. When the system is back on, we will make sure that out USB device is nιcely plugged in...

root@raspbx:~# lsusb
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp. 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. 
Bus 001 Device 004: ID 051d:0002 American Power Conversion Uninterruptible Power Supply

Our UPS is there so let's set up the driver for the nut server. Open file /etc/nut/ups.conf and append the following lines at the end.

        driver = usbhid-ups
        port = auto
        desc = "APC Back UPS Pro 1200VA supporting the two network servers"

You can name your ups anything you like, as far as the driver is concerned my advice is to browse through the official Network UPS Tools drivers list.

Setting up the UPS name and driver is not enough. I have not tested this on any other Debian box, but on raspberry-pi we need an extra step in order to create the /var/run/nut folder and set correct permissions to it.

root@raspbx:~# mkdir /var/run/nut
root@raspbx:~# chown root.nut /var/run/nut/
root@raspbx:~# chmod 770 /var/run/nut/

Now we are ready to test the UPS driver.

root@raspbx:~# upsdrvctl start
Network UPS Tools - UPS driver controller 2.6.4
Network UPS Tools - Generic HID driver 0.37 (2.6.4)
USB communication driver 0.31
Using subdriver: APC HID 0.95

Our next step will be to configure upsd and upsmon. The network UPS tools design dictates that upsd communicates with the UPS driver that we just started and upsmon communicates with upsd and actually shuts down the machine in the event of a power failure. By providing this extra level of indirection, nut allows for multiple instances of upsmon to run on different machines. That way they can allow share the same physical UPS and this is what we said that we are going to demonstrate in this posting.

So to enable accessing the upsd via the network, edit the file /etc/nut/upsd.conf and place the following LISTEN directives.

LISTEN 3493, is my pi's IP address -- replace that with your own. Next, we will need to add some kind of security and the next file that we will need to tamper with will be the /etc/nut/upsd.users. Edit it with your text editor and set up the following users

        password = myadmpass
        actions = SET
        instcmds = ALL

# --- Configuring for a user who can execute tests only
        password  = pass  
        instcmds  = test.battery.start
        instcmds  = test.battery.stop

# --- Configuring for upsmon
# To add a user for your upsmon, use this example:
        password  = local_pass
        upsmon master
        password  = remote_pass
        upsmon slave

Finally the local UPS monitor daemon will need to specify the UPS to monitor and the user credentials from upsd.users file. Open the /etc/nut/upsmon.conf file, locate the monitor section and add the following line:

MONITOR apc1200@localhost 1 upsmon_local local_pass master 

The number 1 after the ups name and host is the power value. The man page for upsd states clearly that:

The "current overall power value" is the sum of all UPSes that are currently able to supply power to the system hosting upsmon. Any UPS that is either on line or just on battery contributes to this number. If a UPS is critical (on battery and low battery) or has been put into "forced shutdown" mode, it no longer contributes.
A "power value" on a MONITOR line in the config file is the number of power supplies that the UPS runs on the current system.

Final steps: Open the /etc/nut/nut.conf file and change the value of Mode to netserver -- making sure that there are no spaces between each side of the = sign. (See NOTE at end of file) and issue the following commands:

root@raspbx:/etc/nut# service nut-server start
[ ok ] Starting NUT - power devices information server and drivers:  driver(s). upsd.
root@raspbx:/etc/nut# service nut-client start
[ ok ] Starting NUT - power device monitor and shutdown controller: nut-client.

As a last check, verify that both services will start automatically on system (using the update-rc.d command) reboot and yes, our server is ready! ...

root@raspbx:~# ps -ef | grep ups
nut       3275     1  0 Apr09 ?        00:08:24 /lib/nut/usbhid-ups -a apc1200
nut       3278     1  0 Apr09 ?        00:00:19 /sbin/upsd
root      3312     1  0 Apr09 ?        00:00:00 /sbin/upsmon
nut       3314  3312  0 Apr09 ?        00:00:09 /sbin/upsmon
root      4721  4711  0 18:44 pts/1    00:00:00 grep ups


Client setup requires more or less three things: One will be to edit the nut.conf file and set the mode variable value to netclient. Next will be to place the correct MONITOR line in the upsmon.conf file and the third will be to start the upsmon daemon.


Our first client is an openSUSE 11.4 machine that I keep saying that I must upgrade. To install nut on openSUSE we need to issue the following command as root.

zypper install nut

openSUSE nut stores the configuration files /etc/ups. By the way the file /usr/share/doc/packages/nut/README.SUSE offer excellent detailed and precise information on how to do things right. So to get things started:

  • Add the line MODE=netclient at the end of the /etc/ups/nut.conf file
  • Add MONITOR apc1200@asterisk "UPS supporting the main Servers" to /etc/hosts.conf
  • Comment out any reference to any UPS at the end of /etc/ups/ups.conf
  • Add MONITOR apc1200@asterisk 1 upsom_remote remote_pass slave
  • Start the service with etc/init.d/upsd start. (The reload option can be used to reread updated configuration files
  • Finally change the system config so that the service starts every time you start your system using the following command: chkconfig upsd on

Reboot and verify :

atlas:~ # ps -ef | grep ups
root      2958     1  0 18:06 ?        00:00:00 /usr/sbin/cupsd -C /etc/cups/cupsd.conf
root      3374     1  0 18:06 ?        00:00:00 /usr/sbin/upsmon
upsd      3376  3374  0 18:06 ?        00:00:00 /usr/sbin/upsmon
root      4776  4732  0 18:13 pts/0    00:00:00 grep ups

You might probably want to test the configuration and whether the upsmon daemon can shut-down your server, so go ahead and ...

atlas:~ # upsmon -c fsd
Network UPS Tools upsmon 2.6.0
Broadcast Message from upsd@atlas                                              
        (somewhere) at 13:57 ...                                               
Executing automatic power-fail shutdown                                        

Broadcast message from root@atlas (Wed Apr 10 13:57:06 2013):

The system is going down for system halt NOW!


Perhaps the easiest setup is on a Debian system. You only need four steps:

  1. Install just the client: sudo apt-get install nut-client.
  2. Edit the file/etc/nut/nut.conf and set the mode to netclient. MODE=netclient (mind that there must be no spaces around the equals sign).
  3. Add the monitor MONITOR apc900@xena 1 upsom_remote remote_pass slave command in the /etc/nut/upsmon.conf.
  4. Restart the nut-client service
    service nut-client restart
  5. Update the system to start the service automatically update-rc.d nut-client defaults

Fedora and CentOS versions 5 & 6

Fedora also stores the nut related data in /etc/ups. Again here we need to perform the three steps we mentioned before, but this time we will need to start the upsmon daemon by hand. So to set up our fedora box as a network client:

  • Install the software using yum install nut-client
  • Add MONITOR apc1200@asterisk 1 upsom_remote remote_pass slave
  • Add /usr/sbin/upsmon start in /etc/rc.d/rc.local to verify that the monitor program will start again after reboot.
    Note: On my Fedora 20 system the file was not present so I had to create it, turn it into a shell script by adding !/bin/sh at the first line and make it executable.


[thanassis@skymnos ~]$ ps -ef | grep upsmon
root      1898     1  0 17:37 ?        00:00:00 /usr/sbin/upsmon start
nut       1900  1898  0 17:37 ?        00:00:00 /usr/sbin/upsmon start
500       2142  2118  0 17:38 pts/0    00:00:00 grep upsmon

NUT Monitor

A very good GUI based tool to help test the ups servers. It can be easily installed using the package manager of your distribution -- just search for the nut-monitor package and after you install and run it, it looks like this:


Winnut is a Windows client, that runs as a 32bit service on Windows 7. The project has not been updated since February 24, 2011. I did install the software on a Windows machine but have not been able to do any serious testing. The program's configuration follows the same rules as the Linux clients. The only thing you have to is click the edit configuration file button

and then add the correct MONITOR Line in the upsmon.conf file that will appear loaded into notepad. On 64bit systems you will also need to change the line

NOTIFYCMD "\"c:\\Program Files\\WinNUT\\alertPopup.exe\""


NOTIFYCMD "\"c:\\Program Files (x86)\\WinNUT\\alertPopup.exe\""