I love Free Software!

Pages

Funny Quotes to Think

When you say "I wrote a program that crashed Windows", people just stare at You blankly and say "Hey, I got those with the system, for free"

-Torvalds, Linus(1995-03-08)-

Wednesday, September 29, 2010

LDAP to CSV using perl



#!/usr/bin/perl
# This script will export LDAP entry in to a csv file. 
# Install Net:LDAP for running this script. 
# Feel free to contact me on praveen.velu84@yahoo.com

use Net::LDAP;

$ldap = Net::LDAP->new("localhost");
$ldap->bind("cn=admin,dc=example,dc=com", password=>"secret");

# Create a new file "ldapcsv.csv and pipe your query output to this file.  
$outputfile = "ldapcsv.csv";

# Create a new File Handler.
open (FH, ">$outputfile") or die "$!";

# Modify your search query and ldap connection details.
$mesg = $ldap->search(filter=>"(&(mail=*)(objectclass=*))", base=>"dc=example,dc=com");

@entries = $mesg->entries;
foreach $entry (@entries){
        @myuid = $entry->get( 'uid' );
        @givenName = $entry->get( 'givenName' );
        @sn = $entry->get( 'sn' );
        @userPassword = $entry->get( 'userPassword' );
        print "Exporting  @myuid[0] to csv file \n";
print FH "@myuid[0],@givenName[0],@sn[0],@userPassword[0]\n"
}

# Close the file handler.
close(FH);

Tuesday, September 7, 2010

Creating OpenVPN client certificates using perl script

How this perl scrip will work

1. Accept certificate name through stdin
2. Create vpn certificate
3. Copy certificate and client.ovpn to a temp directory
4. Modify certificate name in client.ovpn configuration
5. Create a zip file of VPN certificate file
6. Remove temp file after creating archive

How can I run this script

1. Configure your openvpn server. You can check below link for configure openvpn
2. Copy the script to a file create_vpn_cert.pl
3. Modify script based on your open vpn configuration
4. Modify the permission to execute script
# chmod +x  create_vpn_cert.pl
5. Execute the script
# perl create_vpn_cert.pl



#!/usr/bin/perl -w 
# This perl script is used to create open vpn certificates.
# Script prompt for certificate name. based on the input script will create certificates /tmp directory
 
use warnings;
use File::Copy;
use Archive::Zip;
use File::Path;
my $zip = Archive::Zip->new(); 

# OUTPUT DIRECTORY FOR ZIP FILE
$outputdir='/tmp/';

# DIRECTORY WHERE client.ovpn is available
$ovpn = '/usr/share/doc/openvpn/examples/sample-config-files/';
#DIRECTORY WHERE KEYS ARE STORED
$keys = '/etc/openvpn/easy-rsa/2.0/keys/'; 

#DIRECTORY WHERE build-key SCRIPT AVAILABLE
$scriptdir = '/etc/openvpn/easy-rsa/2.0/';

#Creating Certificate
print "Enter VPN Certificate name:";
$certname = <STDIN>;
chomp $certname;
print "Creating Certificate $certname";
system ("$scriptdir/build-key $certname");
 

# Copy certificate files to temp folder
mkdir("/tmp/$certname", 0775) || print $!;
copy("$ovpn/client.ovpn","/tmp/$certname") or die "Copy failed: $!\n";
copy("$keys/ca.crt","/tmp/$certname") or die "Copy failed ca.crt: $!\n";
copy("$keys/$certname.crt","/tmp/$certname") or die "Copy failed $certname.crt: $!\n";
copy("$keys/$certname.key","/tmp/$certname") or die "Copy failed $certname.key: $!\n"; 

# Modifying client.ovpn file
my $filein = "/tmp/$certname/client.ovpn";
my $filetemp = $filein.'_'.$$;
open (my $fh_in, "<", $filein) or die;
open (my $fh_out, ">$filetemp") or die;
while (<$fh_in>) { 
    my $x = $_;
    $x =~ s/cert client.crt/cert $certname.crt/g;
    $x =~ s/key client.key/key $certname.key/g;
    print $fh_out $x;
}
close ($filein);
close ($filetemp);
move("$filetemp","$filein");
# Creating archive
$zip->addTree( "/tmp/$certname" );
$zip->writeToFileNamed("/$outputdir/$certname.zip");
print "Created certficte for user in /$outputdir/$certname.zip \n";
 

# Removing tmp directory
rmtree("/tmp/$certname");
exit;

 

Thursday, August 12, 2010

Shell script to export roundcube address book to csv

Below shell script will convert roundcube address book to csv. I am using postgresql for roundcube database. ouput csv file can found in /tmp folder

#!/bin/bash
# Roundcube Address book must be stored in PostgreSQL database.
# This script is created by Praveen C. please feel free to contact me on praveen.velu84@yahoo.com-
# for any query. You can modify this script to suit your requirement

# Enter roundcube user_name. Script will query this user in DB and export Address book
USER="user_name"
 
# Export your roundcube database passwor. This password will be used for `psql` command
# This will help us to avoid psql prompt for password
export PGPASSWORD=password

#  Find the `user_id` of the user
echo "COPY(SELECT user_id from users where username='$USER') \
                   TO STDOUT" | psql -h localhost -U roundcube  \
                   -o /tmp/rc_query_id roundcube

# Read user_id stored in file rc_query_id file and store to variable _USER_ID
user_list=`cat /tmp/rc_query_id`
for id in $user_list; do
_USER_ID=$id
done

# Query user contacts in and sent output to csv.
echo "COPY (SELECT name,email,firstname,surname from contacts where user_id=$_USER_ID) \
                     TO STDOUT with CSV HEADER" | psql -h localhost -U roundcube \
                     -o /tmp/$USER.csv roundcube

Tuesday, August 3, 2010

PHP script to monitor your multiple ISP link connected to firewall


I have configured multiple ISP links in a linux firewall. But it is very difficult for users to understand which like is up or down. I decided to create a simple webpage which gives the status of each link in a  webpage. This will avoid the hassle of login to linux machine as a normal user and running commands with root privilage


You can use php and fping to check your ISP links status. Make sure that fping is installed in your firewall.
For a better appearance I am using images to show status of link
Image Courtesy:  Open ClipArt

Image which I used to show when a link is Active. Image name is  up.png

Image which I used to show when a link is down.  Image name is down.gif

I have copied both images in to folder img. Below is the php script. For checking the ping response I am using OpenDNS IP address as my destination server


<html><head><meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Link Monitor</title></head><body>
<?
// This is the remote host used for fping. Do not change. I am using OpenDNS IP
$remote_host = "208.67.222.222";
// Add you links in to array. Chang these IP address according to IP addres configured in your firewall. You can  one or more IP address in to array
$isps = array('111.222.333.444','555.666.777.888');
$status = array();

foreach ($isps as $isp) 
{
   $fping = `/usr/sbin/fping -u -S$isp $remote_host`;
   if ($fping == "")
   {
      array_push ($status , "up.png");
   }
   else
   {
      array_push ($status , "down.gif");
   }
}
?>
</br>
<table style="text-align: left; width: 1062px; height: 75px;" border="0" cellpadding="2" cellspacing="2">

<?
$count = 1;
foreach ($isps as $isp) {?>
<tr><td  width=20%><FONT COLOR=black FACE="Geneva, Arial" SIZE=5>Link  <?echo $count?></font></td><td  width=30%><FONT COLOR=Blue FACE="Geneva, Arial" SIZE=5><?echo array_pop($isps);?></font></td><td width=30%><IMG SRC="img/<?echo array_pop($status);?>" height="60" width="61"></td></tr>
<?$count ++;}?>
</table>
</body></html>

Saturday, July 10, 2010

Create a virtual HDD using qemu-img

When you create a virtual machine using KVM and virt-manager, virtual HDD will create in /var/lib/libvirt/images/ directory. Unfortunately I dont have enough  space in my / partition.
I faced difficulty in creating virtual HDD in other partion using virt-manager. To work around this issue, I used qemu-image. Using qemu-img you can create a new vitual HDD with any size on any of your partition

 # qemu-img create -f qcow debian.qcow 5G

This will create a Virtual HDD debain.qcow with size 5GB, later then you can select this HDD for installation using virt-manager

Create a shared network interface for KVM

KVM Virtual machines uses its own virtual network as the default network. If you want to access your virtual machine inside your LAN, you need to change your virtual network interface to shared network interface.

How to create shared interface ??
Configure your physical interface as a bridge in your machine (not in virtual machine). Then you can create a new network interface for you virtual machine with source interface as bridge

Here in my machine I have one interface eth0. I changed my physical interface to a bridge interface so that any of my virtual machine can share my physical interface for networking

edit your network configuration

 # vi /etc/network/interfaces

Change your configuration to make your interface eth0 as a bridge

auto eth0
iface eth0 inet manual

auto bro
iface br0 inet static
         address 192.168.1.10
         netmask 255.255.255.0
         gateway 192.168.1.1
         bridge-ports eth0
         bridge-stp on
         bridge-maxwait 0

This will create a bridge interface br0

Wednesday, July 7, 2010

Apache redirect webiste to another using mod_rewrite

In some situation you may need to redirect your website to another website.
For example I have two domains example.net and example.com. Since I don't have any web pages uploaded for example.net,  I just want to redirect example.net to my existing site example.com.

Create an Apache virtual host for example.net and redirect your website using mod_rewrite.

You can look apache site for more details about mod_rewrite module. Apache Rewrite Module

Here is my virtualhost configuration for example.net

<VirtualHost *:80>
    ServerAdmin admin@example.net
    DocumentRoot /var/www/example.net
    ServerName example.net
    ServerAlias www.example.net

<Directory /var/www/example.net>
Options +FollowSymLinks
RewriteEngine on
Redirect 301 / http://example.com/
RewriteCond %{HTTP_HOST} ^([^.:]+\.)*example\.net\.?(:[0-9]*)?$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
</Directory>
</VirtualHost>

Thursday, June 17, 2010

Mount samba share on Linux

This is the way to mount samba share in your linux machine
  • Install smbfs package
# aptitude install smbfs

  • Create a mount point to mount your samba share

# mkdir /mnt/smbshare
  • mount samba share using mount command
# mount -t smbfs -o username=user,password=pass //smbserver/share /mnt/smbshare

Here user is the samba user who have access to the share. pass is the password for user. smbserver is machine name where samba is configured. share is the shared directory in samba server.

  • Adding samba mount to fstab

We can add mount to fstab, so that system will mount samba share every time system reboot
similar fstab entry is like this

//smbserver/share  /mnt/smbshare  smbfs  defaults,user,noauto,username=user,password=pass  0  0

Saturday, May 29, 2010

Sync your samba password using roundcube password plugin

Why I require this patch ?

Roundcube password plugin does not sync samba password. This patch can sync your samba password using roundcube password plugin

Apply this patch at your own risk . Dont forget to use --dry-run option before running this patch

How  to apply patch ?

  • Download patch file from download link listed below.
  • Copy patch file to directory /usr/share/roundcube/plugins/password/drivers.
  • For a safer side take a backup of your original ldap.php file.

        # cp ldap.php ldap.php.org
  • Now patch your ldap.php file.  


        #  patch -p0 < rcldappasswd.patch  
 
Where can I download this patch ?

I have uploaded the patch in below location.

Download RCLdapPatch

Saturday, May 8, 2010

Configure Modem Dial-in Debian

Install ppp and mgetty

aptitude install ppp pppconfig mgetty

Configure ppp using pppconfig

create users in /etc/ppp/pap-secrets

# client        server  secret                  IP addresses
dial-in              *       dial-in                       *


Configure /etc/mgetty/mgetty.config. if your modem is connected to /dev/ttyS0. Comment below lines

port ttyS0
  debug 3
  data-only y


Configure /etc/mgetty/dialin.config
add below lines at end of file
all

Check following lines are uncommented in /etc/mgetty/login.config
/AutoPPP/ -     a_ppp   /usr/sbin/pppd auth -chap +pap login debug

Add below lines to /etc/inittab
s0:23:respawn:/sbin/mgetty ttyS0

Now dial from your windows machine. For authentication you can use user dial-in

Tuesday, March 30, 2010

Sending HTML mails using RT web interface

Request Tracker uses templates to send mails. For replying mails RT is using Correspondence template.
Change your Correspondence templates in such a way that it use Content-Type as text/html 

Correspondence template:

Content-Type: text/html
     RT-Attach-Message: yes

     {$Transaction->Content()}

Saturday, February 6, 2010

Show or Hide html DIV based on dropdown menu selection

Java script in html will help you to show or hide div section in html based on selected value in drop down menu
You can add controls to each div section to show and hide controls based on drop down value. Below html file will explain you in deep

We have two javascripts. start() will start when you load html form and disp_div() will show and hide div section depending on your drop down value

<html>
<head>
<script language=JavaScript>
function start()
{
        var f=document.getElementById("first");
        var s=document.getElementById("second");
        var l=document.getElementById("last");
        f.style.display = 'none';
        s.style.display = 'none';
        l.style.display = 'none';
}
function disp_div() {
       var word = document.myform.distro.selectedIndex;
       var selected_text = document.myform.distro.options[word].text;
       var f=document.getElementById("first");
       var s=document.getElementById("second");
       var l=document.getElementById("last");
        if (selected_text == 'Debian'){
                 f.style.display = 'block';
                 s.style.display = 'none';
                 l.style.display = 'none';
        }else if (selected_text == 'Ubuntu'){
                f.style.display = 'none';
                s.style.display = 'block';
                l.style.display = 'none';
        }else if (selected_text == "Windows"){
                f.style.display = 'none';
                s.style.display = 'none';
                l.style.display = 'block';
        }
}     
</script>

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>which distro you like</title>
</head>
<body bgcolor="#BDEDFF" onload="start()"><br>
<FORM NAME="myform" >
<br><font size="3" face="Times">
Select Your favourate Operating System   
<select name="distro" onchange="disp_div()">
<option value="debian">Debian</option>
<option value="ubuntu">Ubuntu</option>
<option value="win">Windows</option>
</select>
<br>
<div id="first">
<br>Avoid the Gates of Hell. Use Linux <br></div>
<div id="second">
<br>Ubuntu Linux IS user friendly... Linux for human beings <br></div>
<div id="last">
<br>Microsoft sells you Windows... Linux gives you the whole house <br></div>
</form>
</body>
</html>

Friday, January 29, 2010

Reset MySql Password

Follow below steps for reseting mysql password in Debian linux
  • Login to server as root
  • kill mysql server pid. In debain you can find pid file in /var/run/mysqld
kill `cat /var/run/mysqld/mysqld.pid`
  • Create a text file and add below sql statements to text file. Change 'password' to new password required
UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
FLUSH PRIVILEGES; 
  • Start mysql server with --init-file option 
mysqld_safe --init-file=/path/to/textfile &

Now login to mysql using new password

Friday, January 1, 2010

How to access any web application server running on different port with apache http (port 80)

Apache can handle any web server application which running on different port using its own http port
Apache uses mod_proxy to implement a proxy/cache for Apache. It implements proxying capability for FTP, CONNECT (for SSL), HTTP/0.9, HTTP/1.0, and (as of Apache 1.3.23) HTTP/1.1. The module can be configured to connect to other proxy modules for these and other protocols.

Imagine you have a webserver application running 5566. You need to access this application using apcache port 80. You can follow this steps
  • Install proxy modules for apache, if it is not installed  
# aptitude install libapache2-mod-proxy-html
  • Enable proxy modules for apache
Change to directory /etc/apache2/mods-available and enable module
 # a2enmod proxy

Reload apache service
# invoke-rc.d apache2 reload
  • Create a new apache virtual host to access web server application using mod_proxy
Here is I am including a virtualhost configuration to access a webserver  which running on port 5566 using apache port 80

<VirtualHost *:80>
         ServerName example.org
          ServerAlias www.example.org
          ProxyRequests Off
        <Proxy *>
          Order deny,allow
          Allow from all
        </Proxy>

          ProxyPass / http://localhost:5566/
          ProxyPassReverse / http://localhost:5566/
        <Location />
          Order allow,deny
          Allow from all
        </Location>
      </VirtualHost>