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>