Friday, February 10, 2017

MongoDB shell - query collections with special characters

From time to time I found in MongoDB collections that have characters that get interpreted by the mongo shell in a different way and you can't use it as is.

Some example: If your collection name is Items:SubItems and you try to query as you would normally do


mongos> db.Items:SubItems.findOne()
2017-02-10T14:11:17.305+0000 E QUERY    SyntaxError: Unexpected token :

The 'fix' is to use a special javascript notation - so this will work
mongos> db['Items:SubItems'].stats()
{
... 
}

This is called 'Square bracket notation' in javascript.
See Property_accessors for more info.

Tuesday, December 6, 2016

Password recovery on Zabbix server UI

In case you need it ...

Obtain access to the database for read/write (for mysql this is what you need)

update zabbix.users set passwd=md5('mynewpassword') where alias='Admin';

Wednesday, November 16, 2016

Netcat HTTP server

Netcat is a very versatile program used for network communications - the place to find it is .

Often I need to test different programs with a dummy HTTP server, so using netcat for this is very easy.

Lt's say you want to respond with HTTP code 200 ... this is what you do with netcat into a shell


 nc -k  -lp 9000 -c 'echo "HTTP/1.1 200 OK\nContent-Length:0\nContent-Type: text/html; charset=utf-8"' -vvv -o session.txt

To explain the switches used:
  • -k accept multiple connections, won't stop netcat after first connection(default)
  • -l listen TCP on the all interfaces
  • -p the port number to bind
  • -c 'echo "HTTP/1.1 200 OK\nContent-Length:0\nContent-Type: text/html; charset=utf-8"' is the most interesting one ... this responds back to the client with a minimal http header and sets code 200 OK
  • -vvv verbosity level
  • -o session.txt netcat will write into this file all the input and output
Now you have a dummy http server running on port 9000 that will answer 200 OK ALL the time :)

Monday, March 28, 2016

Backups with Duplicity and Dropbox

Dropbox is a very popular service for file storage, the way the service works will synchronize by default
all your files across your devices. This is important to know since you will be backing up data into
Dropbox and you don't want to download the backups on every device you have connected.

What we want to do is to backup files, encrypt them and send them to Dropbox.
All this is achieved with Duplicity.

This is the setup

  • Linux OS, any distro will work I guess but I tried on Ubuntu 14.04 LTS
  • Dropbox account (going pro or business is recommended since backups will typical grow over 2GB basic account)

To encrypt files you will need GPG, in case you don't have a key on your system
we need to do a bit of work, if you do have a gpg key you can skip the next section.

GPG Setup

In this section will create GPG public key/private keys that will be used to encrypt the data you backup to Dropbox.


# install
$ sudo apt-get install gnupg
#
# check if you have any keys
#
$ gpg --list-keys
# if this is empty than you need to create a set of keys
# follow the wizard to create keys
#
$ gpg --gen-key
gpg (GnuPG) 1.4.16; Copyright (C) 2013 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

gpg: keyring `/home/yourname/.gnupg/secring.gpg' created
Please select what kind of key you want:
   (1) RSA and RSA (default)
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048) 
Requested keysize is 2048 bits
Please specify how long the key should be valid.
         0 = key does not expire
        = key expires in n days
      w = key expires in n weeks
      m = key expires in n months
      y = key expires in n years
Key is valid for? (0) 
Key does not expire at all
Is this correct? (y/N) y

You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
    "Heinrich Heine (Der Dichter) "

Real name: Your Name
Email address: yourname@gmail.com
Comment: 
You selected this USER-ID:
    "Your Name "

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.


....+++++
..+++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
+++++

gpg: checking the trustdb
....

#
#
# At this point the keys are created and saved into your keyring
# list keys
#
#
$ gpg --list-keys
/home/yourname/.gnupg/pubring.gpg
--------------------------------
pub   2048R/999B4B79 2016-03-26
            ^^^^^^^^ /used by duplicity
uid                  Your Name 
sub   2048R/99917D12 2016-03-26 

# Note 999B4B79 which is your keyid

Duplicity install

$ sudo apt-get install duplicity

After installation if you are on Ubuntu 14.04 LTS you will need to apply this patch
http://bazaar.launchpad.net/~ed.so/duplicity/fix.dpbx/revision/965#duplicity/backends/dpbxbackend.py
to /usr/lib/python2.7/dist-packages/duplicity/backends/dpbxbackend.py
If you don't know how to apply the patch is simpler to open the file at line 75 and write the following

 72 def command(login_required=True):
 73     """a decorator for handling authentication and exceptions"""
 74     def decorate(f):
 75         def wrapper(self, *args):
 76             from dropbox import rest  ## line to add
 77             if login_required and not self.sess.is_linked():
 78               log.FatalError("dpbx Cannot login: check your credentials",log.ErrorCode.dpbx_nologin)

Dropbox and duplicity setup

You need to have an account first. Open your browser and login.

Backups with duplicity and dropbox

Since this is the first time you run it need to make a authorization token, this is done as follow


$ duplicity --encrypt-key 999B4B79 full SOURCE dpbx:///
------------------------------------------------------------------------
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=TOKEN_HERE
Please authorize in the browser. After you're done, press enter.

Now into your browser authorize the application. This will create an access token into dropbox.
You can see the apps you have going to Security
Should see under Apps linked backend for duplicity
In case you need to know what token is in use you can see it onto you system ~/.dropbox.token_store.txt


Local and Remote metadata are synchronized, no sync needed.
Last full backup date: none
GnuPG passphrase: 
Retype passphrase to confirm: 
--------------[ Backup Statistics ]--------------
StartTime 1459031263.59 (Sat Mar 26 18:27:43 2016)
EndTime 1459031263.73 (Sat Mar 26 18:27:43 2016)
ElapsedTime 0.14 (0.14 seconds)
SourceFiles 2
SourceFileSize 1732720 (1.65 MB)
NewFiles 2
NewFileSize 1732720 (1.65 MB)
DeletedFiles 0
ChangedFiles 0
ChangedFileSize 0 (0 bytes)
ChangedDeltaSize 0 (0 bytes)
DeltaEntries 2
RawDeltaSize 1728624 (1.65 MB)
TotalDestinationSizeChange 388658 (380 KB)
Errors 0
-------------------------------------------------

Backups

When the first full backup finished you can start making incremental backups, list the backups etc.
# list the backup files
duplicity --encrypt-key 999B4B79 list-current-files dpbx:///
#

## Make an incremental backup

duplicity --encrypt-key 999B4B79 incr SOURCE dpbx:///
.....
.....
.....

duplicity --encrypt-key 999B4B79 list-current-files dpbx:///

Troubleshooting

During a backup if you see something like

Attempt 1 failed. NameError: global name 'rest' is not defined
Attempt 2 failed. NameError: global name 'rest' is not defined

See the note about Ubuntu 14.04 because you need to patch the dpbxbackend.py file

Notes

If you use multiple computers and don't want to download from dropbox all
the backups you need to enable selective sync and exclude the Apps/duplicity
folder from Dropbox.
I haven't used duplicity for long time and heard some mix opinions, some say is excellent and some
say has some design flows (didn't checked) where your full backup will be taken after a while even if
you just do incremental. Remains to be seen.
I guess if this doesn't work well I would look into Borg Backup which seems to be the best these days since
has dedup built in and many other features. One thing that doesn't though is many backends as duplicity which
can use pretty much all cloud storage solutions around :).

Wednesday, January 13, 2016

Sublime Text X11 Forward - linux headless

On a newer editors (compared with Vim or Emacs) is Sublime Text.
Has many useful features and is quite popular these days, combined with the vintage_keys enabled (vim emulation) is
quite interesting.

This post shows what I did to have sublime text 3 working on a remote headless linux server, I used CentOS 7.1 installed with the group Base.

Since sublime text needs a display to run you will need to install a few packages.

sudo yum install gtk2
sudo yum install pango
sudo yum install gtk2-devel
sudo yum install dejavu-sans-fonts # or the font of your choice
sudo yum install xorg-x11-xauth

After all these packages are installed the ssh server (sshd for CentOS) needs to have the following settings.

# /etc/ssh/sshd_config

X11Forwarding yes
X11DisplayOffset 10
TCPKeepAlive yes
X11UseLocalhost yes
Restart sshd in case you changed your config file
sudo systemctl restart sshd

I used putty on a windows box so I had to make a small hack.

cd  $HOWE
touch .Xauthority  # empty file
Windows based
Configure putty to enable X11 Forwarding and connect to your server.
One more thing to mention is that if you use Windows than you will need to install a program Xming
After you download run the installer and start the Xming server.
Linux
You will need to run a X server - doesn't matter which one and have X11 forward it into the agent.
# when connect add the -X
ssh -X my_host_with_sublime_installed
# Or you enabled X11Forward into your .ssh/config
# something like this will do
Host *
   ForwardX11 yes


In case that sublime text is not installed, download from their site (is always nice to have a license too), extract
the files, typically you would have a directory called sublime_text_3.
# check first that the display is forward it
$ echo $DISPLAY
localhost:10.0
$ cd  sublime_text_3
$  ./sublime_text --wait
# 
At this point onto your local screen(display) you should see a window pop up with sublime text.

Saturday, August 22, 2015

Vagrant with libvirt(KVM) Ubuntu14

Vagrant doesn't have an official provider for libvirt but there is a plugin that allows to run via libvirt KVM on Linux.

First you would think why not VirtualBox/VmWare etc. - simply because KVM is built in and is very lightweight(especially if you run it on your laptop). Also if you have pre-made virtual machines with kvm you can easily package them as Vagrant boxes.

This is what you need to get started on Ubuntu 14.

Obtain package (could be a different version) wget https://dl.bintray.com/mitchellh/vagrant/vagrant_1.7.4_x86_64.deb
Install package

$ sudo dpkg -i vagrant_1.7.4_x86_64.deb

Install kvm, virt-manager, libvirt and ruby-dev

$ sudo apt-get install ruby-dev
$ sudo apt-get install kvm virt-manager
$ sudo apt-get install libvirt-dev

Remove just in case ruby-libvirt as we need a specific version

$ sudo apt-get remove ruby-libvirt
Instal from gem
$ sudo gem install ruby-libvirt -v '0.5.2'

Install the plugin

$ sudo vagrant plugin install vagrant-libvirt
_Note_: Installed the plugin 'vagrant-libvirt (0.0.30)'!

Thursday, December 18, 2014

Supervisor (python supervisord) email alerts

The program supervisor written in python is used to supervise long running processes. In case that a long running process will stop (crash) supervisor will detect it and will restart it, you will get entries into the log files however unless you have a log aggregation tool or you login into the server or have some other monitoring tool you will not know that your process has crashed.

However there is hope :) - you can setup an event listener into supervisor which can email you in case that a process has exit. To do so you will need to install a python package superlance This is how the setup is done.

# install superlance
$ sudo pip install superlance  # if you don't have pip install try easy_install 

# configure supervisor to send events to crashmail

$ sudo vim /etc/supervisor/supervisord.conf  # change according to your setup

[eventlistener:crashmail]
command=crashmail -a -m root@localhost
events=PROCESS_STATE_EXITED

$ sudo supervisor stop && sudo supervisor start
# done :)

In the example above if a process will crash (exit) an event will be sent to crashmail which in turn will email to root@localhost - of course you can change the email address, crashmail uses actually sendmail to send email (postfix and qmail come with a sendmail like program so no worries).
Also the email alert will be sent out for any program that crashed but if you want to filter out you can choose just the program you want by specifying -p program_name instead if -a, for more info you can see Crashmail section on the superlance docs.