Sunday, August 30, 2009

Metaclass in Python

Here is a way to do this and subclass it.

class CustomMetaclass(type):
    def __init__(cls, name, bases, dct):
    print "Creating class %s using CustomMetaclass" % name
    super(CustomMetaclass, cls).__init__(name, bases, dct)

class BaseClass(object):
    __metaclass__ = CustomMetaclass

class Subclass1(BaseClass):

And now, an example that actually means something, this will automatically make the variables in the list "attributes" set on the class, and set to None.
def init_attributes(name, bases, dict):
    if 'attributes' in dict:
        for attr in dict['attributes']:
            dict[attr] = None
    return type(name, bases, dict)

class Initialised(object):
    __metaclass__ = init_attributes
    attributes = ['foo', 'bar', 'baz']

print 'foo =>',
# output=>
foo => None

Here is an even more concrete example, showing how you can subclass 'type' to make a metaclass that performs an action when the class is created. This is quite tricky:

class MetaSingleton(type):
    instance = None
    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)
        return cls.instance

class Foo(object):
    __metaclass__ == MetaSingleton

a = Foo()
b = Foo()
assert a is b

Monday, August 24, 2009

Anotherway of Application Status discovery

    print '---------------------- Application status ---------------------'
    for bean in mBeans:
        if server_name != bean.getObjectName().getLocation():
        components= bean.lookupComponents()
        for componentRTList in components:
            app = componentRTList.getParent().getName()

            if istate == 0:
            if istate == 1:
            if istate == 2:
            if istate == 3:

            print "%65s %65s %20s" % (str(componentRTList.getName()), app, istate)

    print "This Server has no Applications"

Tuesday, August 18, 2009

Short Notes on NFS

Network Files System NFS uses rpc portmap. It allocates random UDP port number to NFS server for I/O operation. Dont worry to set portmapper. It will work by default. In case you want to see if its working use command

ps -aux | grep portmap

To see port number assigned to various services by portmapper use command

rpcinfo -p

Various services need to be setup for NFS are NFS, netfs, amd and autofs. To check if NFS is installed use command

rpm -qa | grep nfs

To secure the NFS you would normally disable all unnecessary services in hosts.allow. A typical hosts.allow would look like below.

rpc.mountd:192.168.0 .

Now to export a particular directory open /etc/export file and write the following line


To export directory issue command

exportfs -a

It will update /var/lib/nfs/xtab. If you change /etc/exports and want immediate effect use

exportfs -r

Then no reboot is necessary.

On the client side use command

showmount --exports servername

amd and autofs are two automatic mounting systems. Use anyone if necessary.

UID and GID should be same across all client and servers. If /etc/export is changed issue command

exportfs -a
exportfs -r on client

To mount it in on client use command

mount servername:/home/use rname1 /home/username2

This mounts home directory of two users.

Help! I lost my root password

Move the system to runlevel one in grub;

At boot the grub menu will state "press e to edit";
press e;
and then choose the line with kernel on it;
press e;
to edit again and move to the end,
pressing the end key;
enter a space and the digit "1";
press enter
and then "b" to boot.
This will take you to a command prompt where you can unlock the account or change your password.

Configuring Kerberos Server

Ok. Guys, this is how I configure Kerberos 5

1) Files needed /etc/krb5.conf, /var/kerberos/krb5kd c/kdc.conf, /var/kerberos/krb5kd c/kadm5.acl

First add the realm to /etc/krb.cond
Then to /etc/krb.realms
Watchout there is a leading DOT there.

2) Log files are /var/log/kadmind.log , krb5kdc.log, /var/log/krb5libs.lo g

3) First we have to create a database file. Assume is realm. Issue the following command
kdb5_util create -s -r
This will create database /var/kerberos/krb5kd c/principal for the realm. Master ket name will be like K/, and it will prompt for a master password. Enter it. Now realm is created. The -s option creates the stash file which is needed by kerberos to authinticate itself at boot time

4) Now issue
kdb5_util stash
It will prompt for KDC database master key. Enter password correctly. Stash file is created. Now reboot and look at logs. It should show kadmind starting "krb5kdc settingup network" and lisitning on port 88 (kdc), 750 (admin server)

5) Now we need to add administrators to database as follows
This command takes us to a kadmin.local prompt. Do as follows
kadmin.local: addprinc root/admin@ENGINEER.NET.IN
This command will give us some warning. For the first time ignore it and give a password for this account. If correct password is added and shows principal created

6) Now we need to create special entries for kadmin/admin and kadmin/changepw. This is used by administrators so he need it on kadmin keytab. Give command as follows
kadmin.local: ktadd -k /var/kerberos/krb5kd c/kadm5.keytab

7) Now we are ready to start kerberos daemon on Master KDC and also kadmin daemon
/etc/init.d/krb5kdc restart
/etc/init.d/kadmind restart

8) To add a host first on the server go to kadmin and issue following command
addprinc -randkey host/pattabi.enginee
Then go to the workstation called pattabi andkadmin which can be had after kinit
ktadd -k /etc/krb5.keytab host/pattabi.enginee

Ok boys thats it for now

Fedora Based KVM

Do these on the Host Machine

1) Four files in /etc/X11/xdm/ need to modify: xdm-config, Xresources, Xaccess, and Xservers.

2) In xdm-config, DisplayManager.reque stPort is either commented out or set to the default (XDMCP) port, which is 177.

3) Xresources can be changed to value of your option. If you dont want to change leave it alone.

4) Xaccess file is how xdm determines access to the various hosts. The idea is that we want xdm to do two things. First, we want every host on the LAN to be allowed to choose from amongst all available X servers running on all other hosts. Second, we want to allow any host to be allowed to login to the current host as well as all the others. For the first, we make sure the following line is added to the Xaccess file:

* CHOOSER BROADCAST # xdm allows all hosts to ask for a list of available hosts

For the second, we add the following line to the Xaccess file:

* # xdm allows all hosts to login to this host

5) The final configuration change is to the Xservers file. Here, we do not want xdm to automatically start/use the local host's X server. If it does, it only allows us to login to the local host, whereas we want to choose which host we will use to login. Therefore, we comment out any local X servers configured in the Xservers file. If you have any X terminals or machines acting as dedicated X terminals, do not comment out those lines or the X terminals will not work.

6 If you want xdm to be run during all the runlevels that allow active network connections (usually 2-5). do this Add a line similar to the following to /etc/inittab:

xd:2345:respawn:/usr /X11R6/bin/xdm -nodaemon

Now we need to configure the Server

1) Now we decide if we want to start the X server manually from the command line, or have it started automatically for us at system boot. If we want to start it manually, we can either start the X server itself, or via the startx or xinit programs. We will do the former. Assuming Server name ullas :

X -indirect ullas

This starts the X server and has it send a query for any hosts that the xdm running on ullas finds available on the LAN. Xdm then responds with a list of hosts to choose for logging in. Starting the X server upon system startup only takes a little more work than doing so from the command line. On storch , a SYSV machine, the easiest way is to add a line to /etc/inittab as follows:

xs:5:respawn:/usr/X1 1R6/bin/X -indirect ullas

We also need to change the line that sets the default runlevel as follows (remembering that on this particular Unix implementation runlevel 5 is for a X windows environment upon startup).


That is it

Terminal Server Setup

This is a terminal setup for Fedora Core1

1) In /etc/init.d/xfs change
daemon xfs -droppriv -daemon
daemon xfs -droppriv -daemon -port 7100

2) Enable firewall for UDP Port 177 to Accept Traffic

3) In /etc/X11/fs/config comment out this

4) In /etc/x11/xdm/xdm-con fig comment out
! DisplayManager requestPort: 0

5) If using gdm in /etc/X11/xdm Xaccess Change
# * # any host can get a login window
* # any host can get a login window

6) In /etc/X11/gdm/gdm.con f

7) In /etc/X11/xdm/Xsetup_ 0 should be chmod 755

8) Edit XF86Config in /etc/X11
From FontPath "unix/:-1"
To FontPath "unix/:7100"

9) Now Reboot the server and in the command prompt type
xdm -nodaemon

10) Now you will get into X window Manager in Server

11) To get X Window manager on the client type below command at shell prompt. That is it. Finished.
X -broadcast

12) To connect from Windows machine install Cygwin. Then at command prompt of it type X server IP
X -query

13) To automatically login the client to xdm server use command below in inittab and at level 5
/usr/X11R6/bin/X -depth 16 -query

Sample Samba Primary Domain Controller

# Date: 16-04-2004
# Global parameters
# Notes on Mounting shares from other windows machine into linux /mnt
# Create a directory /mnt/muruga. It is good if you put the server name for mount
# Create a directory /mnt/muruga/sujatha. Its good if you put netbios name of machine you want to share
# In /etc/mtab put the following line given below
# //muruga/sujatha /mnt/muruga/sujatha smbfs 0 0
# In /etc/fstab put the following line given below
# //muruga/sujatha /mnt/muruga/sujatha smb username=padmaja,pas sword=pad, 0 0
# Now go to windows machine padmaja and make the c drive shareable with username and password as above.

# Did you know using the following line enables you to customise your configuration
# on a per machine basis. The %m gets replaced with the netbios name
# of the machine that is connecting
; include = /etc/smb.conf.%m

# Do you know that you can mount harddisk share of other clients into linux share
# smbmount //sujatha/c /mnt/samba/ -o username=ramesh
# The above command will mount sujatha named netbios machine with share c into /mnt/samba/. The user name is
# share user name and it will prompt for a password
# Normally you can put this fstab
#//MS-SERVER-NAME/MS -Windows-Share /home/linux-user-id/ MS-SERVER-NAME/MS-Wi ndows-Share smbfs credentials=/home/li nux-user-id/.smbpass word,workgroup=MS-WI NDOWS-DOMAIN,uid=lin ux-user-id,gid=linux -user-group-name 0 0

# Some samba test

# testprns: Test printer access in samba
# smbprint: Print drom samba to samba printers
# smbrun: Run external programs from server
# nmblookup -B muruga __SAMBA__. You should get back the IP address of your Samba server.
# nmblookup -B ACLIENT '*' You should get the PC's IP address back. If you do not then the client software on
# the PC isn't installed correctly, or isn't started, or you got the name of the PC wrong.
# nmblookup -d 2 '*' .A number of NetBIOS/TCP/IP hosts on the network should respond.

# To send a popup message to window
# smbclient -M sujatha
# Hello this is from me
# Ctrl + d

# -------------------- - Start: Fine Tuning

; Reduce the overhead that Samba uses to scan for timeouts
change notify timeout = 300
; Open files with no connections are closed after 15 minutes
deadtime = 15
; Files that have UNIX permissions that prohibit access are hidden from users
hide unreadable = yes
; The root user and the wheel group are not allowed access
invalid users = root @wheel
; We want a minimum level of logging
log level = 1
; Again, all our clients are Windows XP
; min protocol = NT1
; All our computers are Windows XP
; lanman auth = no
; We're (mostly) on a Local Area Network, so these settings are appropriate
; We allow clients to set their clock to ours using the NET TIME parameter
time server = yes
; Uncommenting this willtell Samba to use a separate log file for each machine
; that connects. Good for testing.
;log file = /var/log/samba/log.% m

# -------------------- -- End: Fine Tuning

# -------------------- -- Start: Netbios & Workgroup setup

; netbios name can be different from unix host name
netbios name = MURUGA
; workgroup in windows terminology means windows domain
workgroup = STRADE
server string = Samba %v File Server
; Allow traffic on network interface
interfaces =
; Winpopup message handler
message command = csh -c 'xedit %s;rm %s' &

# -------------------- -- End: Netbios & Workgroup setup

# -------------------- -- Start: Password Authintication
; Use password authintication from smbpasswd
passdb backend = smbpasswd
; Updates passwd files if its changed in smbpasswd
unix password sync = Yes
; And use encrypted password. This may cause problems with som win95 and win98 first edition
encrypt passwords = yes
; Tell where is the command for password
passwd program = /usr/bin/passwd %u
; For the password change dialog for users. Not necessary.
passwd chat = *New*UNIX*password* %n *ReType*new*UNIX*pas sword* %n *passwd:*all*authent ication*tokens*updat ed*successfully*

# -------------------- -- End: Password Authintication

# -------------------- ----- Start: Primary Domain Related

; We don't want to compete for browse master elections - we win always
os level = 255
; Below mentioned codes are required if you want samba to act as a PDC for windows network
preferred master = yes
domain master = yes
local master = yes
security = user
; The code below are used for domain logon by clients
domain logons = yes

# -------------------- ------- End: Primary Domain Related

# -------------------- ----- Start: WINS Server Related

; This is all it needs to setup a wins server. If this server is acting as wins server
; then commend next two lines.
; wins server =

; Below line will force the server we have made as the name resolver even if there is a
; broadcast from another machine. Use this if WINS server is on another subnet. Otherwise
; the broadcast will reach the WINS server regardless of any proxying.

; wins proxy = yes

; Comment this section if this is not acting as a wins server. This should be commended if
; you enable the winserver option above. Only either of the one should be there.
wins support = yes

;This determines the order of name resolution for netbios
name resolve order = lmhosts hosts wins bcast

; If you have a dns and need to use that for name resolution then use below option
; dns proxy = yes

# -------------------- ----- End: WINS Server Related

# -------------------- ----- Start: Printing Configuration

; if you want to automatically load your printer list rather
; than setting them up individually then you'll need this
printcap name = /etc/printcap
load printers = no
# It should not be necessary to spell out the print system type unless
# yours is non-standard. Currently supported print systems include:
# bsd, sysv, plp, lprng, aix, hpux, qnx
printing = bsd

; Uncomment this if you want a guest account, you must add this to /etc/passwd
; otherwise the user "nobody" is used
; guest account = pcguest

# -------------------- ------- End: Printing Configuration

# -------------------- ------ Start:Important Security Related

bind interfaces only = True
interfaces = eth1 lo
; -- Security -- This sees to it that only allowed network are as said in hosts allow
hosts deny = All
hosts allow = 255.0
; Fix Samba permissions so when you create a file/directory, the
; UNIX perms are correct too!
create mask = 0770
directory mask = 0750
invalid users = root bin daemon adm sync shutdown halt mail news uucp operator gopher
;------------------- ------- End :Important Security Related

; Now if we want a machine trust account which is necessary for winnt, win2000 and above we need below line
; It adds machine to the samba PDC automatically. I M P O R T A N T

add user script = /usr/sbin/useradd -d /dev/null -g 100 -s /bin/False -M %u

; The path shown as /usr/sbin/useradd should point to wherever your system stores the useradd program.
; This setting as shown will work on most GNU/Linux systems.

; You can create trusted machine accounts on your Samba PDC two ways. The first method is to create manually the
; password with a known value (such as the lower case netbios name of the machine) before you join the machine to
; the domain. The other method creates the trusted machine account when the admin joins the machine to the domain.
; This second method uses the session key of the administrative account as an encryption key for setting the
; password to a random value. The second method is much more secure than the first method, and is recommended.
; Currently, Samba requires a Linux user id from which a Microsoft Windows NT system id can be generated.
; For this reason, you'll need to add a configuration line to your smb.conf file if you want your Samba PDC to
; add Linux user ids on the fly when users access the server from a trusted machine. In your global settings of
; the smb.conf file, add the setting:

; To manually add a trusted machine account, you must first create an entry in your /etc/passwd file. For example,
; let's say you're adding the machine "elaine" manually to your domain. Using your favorite text editor as root,
; open your /etc/password file and create an entry that looks like this:

; elaine$:x:505:501:NT Machine:/dev/null:/b in/false

; The appended "$" to the user "Elaine" in the /etc/passwd entry signifies this as a machine account. The rest of
; the settings establish the account without a home directory and no shell access. Once you've created this entry,
; add the user to your smbpasswd file with the following command run as the superuser root:

; smbpasswd -s -m elaine

; You should then immediately join the machine to the domain with your NT Admin applet.

#logon path = \%Nprofiles%u
; This option specifies the drive letter on an NT client to which the home directory
; specified with the logon home option will be mapped.
; Note that this option will work with Windows NT clients only.
logon drive = H:
logon home = \%L%U.profile s
;logon path = \%Lprofiles%U
logon path = \%L%u
logon script = %U.bat
; into to be case insensitive for windows compatability
preserve case = yes
case sensitive = no
; We will use guest account to facilitate printing to a printer connected on windows machine
;Make sure to add the smbguest account to system's password file. Use command given below
# groupadd smbguest
# useradd smbguest -g smbguest -d /dev/null -s /bin/false
; Only now guest will work
#guest account = smbguest

; To use the logon script, we need to have a share called netlogon on our server.
; Don't forget that the Unix directory shared this way must be readable and executable
; for all of the users.
comment = Logon scripts and policies
; The path of logon scripts for users or machine as per your choice
; This must be set up in the Win95 setup in the registry with ``remote update''
; and ``automatic path'' in the Network settings of the registry. This is where
; we put the Config.POL file and all those individual .bat files. Make sure the logon
; scripts (which will be kept in the directory specified in the [netlogon] section)
; use DOS-style line endings; a good way to ensure that is to use a DOS editor
; on a DOS system to create the files.
path = /export/samba/logon
public = no
writeable = no
browsable = no

# the default path is to use the user's home directory
path = /usr/samba/ntprofile
browsable = no
writeable = yes
create mask = 0600
directory mask = 0700

; -- Security -- This sees to it that only allowed network IPC are as said in hosts allow
hosts allow =
hosts deny =

# In some cases you will nee to chmod 4777 /var/spool/lpd/lp
comment = "Windows Printer"
path = /var/spool/lpd/samba
; If the above path does not work use the one below
;path = /var/spool/lpd/lp
read only = yes
#printcap name = /etc/printcap
printable = yes
public = no
writable = no
lpq command = /usr/bin/lpq -P%p
lprm command = /usr/bin/lprm -P%p %j
lppause command = /usr/sbin/lpc stop %p
lpresume command = /usr/sbin/lpc start %p
create mode = 0700
browseable = no
#load printers = yes

comment = FAX (mgetty+sendfax)
path = /tmp
printable = yes
public = yes
writable = no
create mode = 0700
browseable = yes
guest ok = no

;Normally dont use a homes share. Its better to create individual shares
comment = Home Directory of %u
browseable = no

; By default, the home directories are exported read only. Change next
; parameter to "no" if you want to be able to write to them.
read only = no

; File creation mask is set to 0700 for security reasons. If you want to
; create files with group=rw permissions, set next parameter to 0775.
create mask = 0700

; Directory creation mask is set to 0700 for security reasons. If you want to
;create dirs. with group=rw permissions, set next parameter to 0775.
directory mask = 0700

comment = Narayanan's Home
path = /home/ramesh
read only = no

comment = Ramesh's Home
path = /home/ramesh
read only = no

comment = T.Ullas's Home
path = /home/ullas
read only = no

comment = Padmaja's Home
path = /home/padmaja
read only = no

comment = Pattabi's Home
path = /home/pattabi
read only = no

comment = Shreekant's Home
path = /home/shreekant
read only = no

comment = CD Writer in Server
path = /mnt/cdrom
public = yes
read only = yes
;you may need to use "root preexec/postexec
preexec = mount /mnt/cdrom1
postexec = umount /mnt/cdrom1

fake oplocks = yes
comment = CD Drive in Server
path = /mnt/cdrom
public = yes
read only = yes
;you may need to use "root preexec/postexec
preexec = mount /mnt/cdrom
postexec = umount /mnt/cdrom

comment = Accounting Department Directory
writeable = yes
; The valid users who can access this directory are users of unix group accounting
valid users = @accounting
; Now there should be a directory for this section. Create it anywhere its safe. Apply these
; unix commands after the creation of directory.
; # chgrp account /home/samba/accounti ng. # chmod 770 /home/samba/accounti ng
path = /home/samba/accounti ng
create mode = 0660
directory mode = 0770

comment = Floppy Drive in the Server
path = /mnt/floppy
public = yes
read only = yes
;you may need to use "root preexec/postexec
preexec = mount /mnt/fd0 -t msdos /mnt/floppy
postexec = umount /mnt/floppy

comment = Backup Folder
browseable = yes
read only = yes
path = /mnt/backup/
; The command below makes this read only share writable for stated users
write list = ramesh ullas

SSH Account

1) You can log into a ssh session using either of the following commands.

ssh -l ullas servername
ssh ullas@servername

If you use non standard port then

ssh -p 2222 ullas@servername

2) If its the first time you log into that server it will ask for password along with server RSA Key shown on screen. If you login then a file is created in client ~ullas/ssh/.known_ho sts so that it will recognise the server next time you login.

3) Now let us see how to create a key on client machine and put it on user's
home directory on the server machine. Issue this command on client first.

ssh-keygen -t rsa

It will ask for a passphrase. Enter it. This creates RDA key. Also at the end
it gives a long list string called "finger print". We need to copy this into
"authorized_keys" file on server. So copy it.

4) Now transfer public key to server using command below. For this create a
file called "authorized_keys" in the home directory of user on server in .ssh/
directory. Paste finger print here. File and directory Permission is important. So go into ssh
directory and issue the following command.

# chown yourusername.yourgro upname . *
# chmod 700 .
# chmod 600 *

ssh servername "umask 077; cat >> .ssh/authorized_keys " < ~/.ssh/

5) Now if you try to login to server it asks for ssh passphrase. Note that its
not password that is asked.

NIS Installation

1) Start services for server

2) If setting up a client start ypbind.
To configure ypbind open /etc/yp.conf and add this line.

ypserver (server ip)

3) To config server first edit /var/yp/securenets. It should be like this.

#Always allow localhost
#Our Lan
#For everyone put this

Now set NIS Domain with following command.

ypdomain name engineers (domain name)

Now run the command

/usr/lib/yp/ypinit -m

This creates all NIS database.Actually makedbm is the program that converts the ASCII to DBM. This is all for a server.

4) Now in client you will find programs like ypwhich, ypcat, yppasswd, yppoll, ypmatch. Normally in /usr/bin or sbin. First set domain name

/bin/ypdomain name engineers

Then start ypbind. Use rpcinfo -p to see if its running.

Now you will be able to use programs like

ypcat passwd

Note that /var/yp directoty must exist before ypbind is started.

You can edit /etc/passwd.

+ullas : : : : : : :
+elango : : : : : : :
+@samba : : : : : : :
+:*: : : : : :/etc.noshell

This adds login access and elango and all members of samba group but show all a/c data due to 4th line. FTP users are disabled.

5) Now setup properly nsswitch.conf

hosts: files nis dns

To see to it that look into details in this order. Here is a eg: must use nisplus if version is above 3

passwd : compact
group : compact
shadow : compact # for lib5 use shadow : files nis
passwd_compact : nis
group_compact : nis
shadow_compact : nis
hosts : nis files dns
services : nis [NOTFOUND=return] files
networks : nis [NOTFOUND=return] files
protocols : nis [NOTFOUND=return] files
rpc : nis [NOTFOUND=return] files

LDAP Configuration

1) Sample of /etc/openldap/slapd. conf

include /etc/openldap/schema /core.schema
include /etc/openldap/schema /cosine.schema
include /etc/openldap/schema /inetorgperson.schem a
#include /etc/openldap/schema /samba.schema
include /etc/openldap/schema /nis.schema
include /etc/openldap/schema /redhat/autofs.schem a
# This confirms that these schemas are there for us and will not say database schema not present message.
schemacheck on

allow bind_v2
pidfile /var/run/

database ldbm
suffix "dc=index,dc=com"
rootdn "cn=Manager,dc=inde x,dc=com"
rootpw {SSHA}LNmVAsdffdsaaa aswqq
dbcachesize 100000
directory /var/lib/ldap
index objectClass eq,pres
index ou,cn,mail,surname,g ivenname eq,pres,sub
index uidNumber,gidNumber, loginShell eq,pres
index uid,memberUid eq,pres,sub
index nisMapName,nisMapEnt ry eq,pres,sub

2) Now configure /etc/openldap/ldap.c onf

BASE dc=index,dc=com

3) Now configure /etc/ldap.conf

base dc=index,dc=com
rootbinddn cn=manager,dc=index, dc=com
port 389
ssl no
pam_password md5

4) Now start ldap service and issue this command

ldapsearch -x -b 'dc=index,dc=com' '(objectClass=x)'

This will show the message
# extended LDIF
#LDAP v3
#base with scop.sub
#filter:(objectClass =x)

5) There are other type of commands which should be used only after stopping ldap service. These are slapadd,slapcat and slapindex.

For eg if you want to populate ldbm first stop service

/etc/init.d/slapd stop
/usr/sbin/slapadd -V < /home/ullas_sample.l dif
/usr/sbin/slapindex -V
/etc/init.d/slapd start

6) To backup LDAP first stop slapd. Now issue command

/usr/sbin/slapcat > /tmp/backup.ldif

7) To search

/usr/sbin/ldapsearch -x cn=admin

8) To add data to database from command prompt

ldapadd -f ullas_sample.ldif -x -D "cn=Manager,dc=inde x,dc=com" -w password

This will add data from file ullas_sample.ldif to database.

9) Sample of ullas_sample.ldif

dn: dc=index,dc=com
objectclass: dcObject
objectclass: organization
o: e-commodities ltd
dc: index

dn: cn=Manager,dc=index, dc=com
objectclass: organizationalRole
cn: Manager

Blocking anyone to su to root

The su (Substitute User) command allows you to become other existing users on the system. If you don't want anyone to su to root or restrict "su" command to certain users then add the following two lines to the top of your "su" configuration file in the "/etc/pam.d/" directory.

Step 1
Edit the su file (vi /etc/pam.d/su) and add the following two lines to the top of the file:
auth sufficient /lib/security/pam_ro debug
auth required /lib/security/Pam_wh group=wheel

Which means only members of the "wheel" group can su to root; it also includes logging. You can add the users to the group wheel so that only those users will be allowed to su as root.

Disable the Control-Alt-Delete keyboard shutdown

To do this comment out the line (with a "#") listed below in your "/etc/inittab" file .
To do this, edit the inittab file (vi /etc/inittab) and change the line:
ca::ctrlaltdel:/sbin /shutdown -t3 -r now
To read:
#ca::ctrlaltdel:/sbi n/shutdown -t3 -r now

CVS Configuration

1) First we need to create enviornment variable called CVSROOT and point it to the root of the repository

export CVSROOT=/home/cvsroo t

It can have othernames than cvsroot

2) Now we need to initialise the repository with the following command. Be root to do this.

cvc init

3) Next we have to setup files, directories and then define a module.

Suppose I have a directory called "staff/resume" with some files that should be added to CVS.
To import these files go to staff/resume directory and issue this command

cvs import -m "Import Source" staff/resume thestaff start
cvs checkout CVSROOT/modules

Now Alter the modules file in root directory (not repository) and add this

resume staff/resume

Now save the file and issue the command

cvs commit -m "Added resume module." modules

Now this creates our needed file in CVSROOT. Now we can delete the original
staff/resume directory.

One way is to rm -rf staff. But a better and safer way is

cvs release -d staff

4) Now we should give proper unix group and user permission for modules
directory as this determines who can commit changes. It means that modules
directory should be owned by group who has permission to commit change.
Also group must have write permission if they have permission to update CVS.

5) To make the changes you have made locally into the repository use command

cvs commit staff

or to update

cvs update staff

Normally its good to update the cvs and then give command commit.

6) To create login authentication for cvs do the following.
a) Create a /etc/xinetd.d/cvspse rver file if it does not exist, and add the

service cvspserver
port = 2401
socket_type = stream
protocol = tcp
wait = no
user = root
passenv = PATH
server = /usr/bin/cvs
server_args = -f --allow-root=/usr/cv sroot pserver

Then restart xinetd with /usr/xinetd restart

b) Now create password file in $CVSROOT/CVSROOT/pas swd with following content

ullas:$1$75g0K7Vm$UL M55Jj/b6QvVB8RxAlk5/
vikas:@#$$$%76776655 66@45667777665555667 :ullas
suvas:233$$%76776655 66@45667777665555667 :ullas

Here password is unix crypt.
Here ullas will have permission if he supplies password. Vikas user can login
with password even if he does not have an account in server and he will run as
ullas in this case. Simalar is the case with Suvas.

c) Now you can login with following command

cvs -d :pserver:anonymous@l ocalhost:/home/cvsro ot co staff
cvs -d :pserver:ullas:sallu t123@localhost:/home /cvsroot co staff

d) You can make this as your CVSROOT enviornment variable in .bash_profile
like the comman below.

CVSROOT=:pserver:ull as:sallut123@localho st:/home/cvsroot co staff

e) To create readonly access to CVS create a file $CVSROOT/CVSROOT/rea ders
with following contents.


Now above three persons becomes read only members of cvs.

RPM Management

1) To Install an RPM package use command
rpm -ivh foo.rpm

2) To Uninstall
rpm -e foo.rpm

3) To Upgrade
rpm -Uvh foo.rpm

4) To Query
rpm -qpi foo.rpm

5) To List files in rpm which is installed
rpm -ql foo.rpm

6) To list files in a rpm which is not installed
rpm -qpl foo.rpm

7) To know to which rpm a file felong
rpm -qf /etc/passwd

8) To check PGP signature
rpm --checksig foo.rpm

9) To Check only md5sum
rpm --checksig --nopgp foo.rpm

SSL enabling Postgresql

1) Copy some 5 random selected files to /usr/share/ssl for random seeding. eg of files f1, f2, f3, f4, f5

2) Create RSA private key not protected with pass phrase
openssl genrsa -rand f1:f2:f3:f4:f5 -out server.key 1024
Now backup the server.key.

3) Now generate the Certificate Signing Request (CSR) with RSA private key. The command below prompt for X.509 attrib of the certificate. When prompted for Common Name give FQDN

openssl req -new -key server.key -out server.csr

After generation of CSR you may send this certificate to a commercial CA like Verisign. You have to post your CSR into webform, pay for it await signed certificate and store it into server.crt. This is real certificate.

4) If you want a self certificate you should have a CA keypair first (Refer Openssl Docs)

/usr/share/ssl/misc/ server.csr

This signs CSR and result is in server.crt.

5) Now we must place the certificate file server.crt and key server.key in /var/lib/pgsql/data directory.

chmod 0400 server.key server.crt
chown postgres:postgres server.crt server.key

6) Now edit postgresql.conf and put ssl=true.

User and Group Quota

1) Edit /etc/fstab and add one of these lines

/dev/hda3 /home ext3 defaults,usrquota 1 2
/dev/hda3 /home ext3 defaults,grpquota 1 2
/dev/hda3 /home ext3 defaults,usrquota,gr pquota 1 2

Here /dev/hda3 has my data from home mount point

2) To remount fstab without reboot

mount -oremount /home/

3) Now create file as follows as a root

touch /home/quota.user
touch /home/
chmod 600 quota.user

4) Use edquota tool for quota creation

edquota -u ramesh
Quotas for user ramesh:
/dev/hda3: blocks in use: 0, limits (soft=0,hard=0)
inodes in use: 0, limits (soft=0,hard=0)

5) To assign 5MB quota for user ramesh modify as follows

edquota -u ramesh
Quotas for user ramesh:
/dev/hda3: blocks in use: 0, limits (soft=5000,hard=6000 )
inodes in use: 0, limits (soft=5000,hard=5000 )

Hard is a value that can go up to with a grace period

edquota -t ramesh
Time units may be : days,hours,minutes or seconds
Grace period before enforcing soft limit for users
/dev/hda3: block grace period:0 days, file grace period: 0 days

Change it to no of days required

6) To edit group
edquota -g mygroup

7) Command are as follows,

quota -display disk usage and limits
quotacheck -scan filesystem for disk usage
quotactl -manipulate disk quota
quotaon, quotaoff - turnon or off filesystem quota
repquota -summerize quota for file system
rquota -implement quota on remote machine

8) quota -u ramesh shows ramesh's quota
quota -g mygroup shows group quota

9) repquota -a This will produce a quota summary.


1) To create a key
gpg ----gen-key

2) To generate export key used for distribution eg on the home page, use the command

gpg --export -ao ullas

-a will produce ascii output and -o will create an output file: here its named ullas

3) To import a key to the keyring

gpg --import redhat2.asc

This will import the redhat key into keyring. Next we have to sign this key. This will add trust. So do as follows.

gpg --sign-key RedHat

4) To check signature of an encrypted data

gpg --verify data

5) Now suppose you want to send a file message.txt to user RedHat

gpg -sear RedHat message.txt

-s Sign, -e Encrypt, -a Ascii, -r to encrypt user id

6) Now RedHat can decrypt as follows

gpg -o message -d message.asc

7) Windows has email client that support gnupg. Its thunderbird with Enigmail plugin support (

Telnet to Mail

Here is a way to telnet to mail server.

telnet 25
Connected to et24 (
Escape character is '^]'.
220 m ESMTP Postfix
250 m
mail from:
250 Ok
rcpt to:
250 Ok
354 End data with .

hello world
250 Ok: queued as 2D40A7D29

There are many options with this type of checking
You can give ehlo instead of helo and the system will show all authentication available.

Sweep Ping

To sweep ping and findout which hosts are up

nmap -sP

This will find out all hosts that are up in the subnet It uses ICMP and TCP Ack to findout this. If you need to do it using ICMP alone then

nmap -sP -PI

Import Export Procedure for Oracle DB

We can use following commands for importing or exporting in oracle database.

exp user@db file=output.file log=export.log

imp user@db file=input.file log=import.log full=y

Learn Perl Modules

Here is some good examples

AWK Oneliners

Taken from

# Print the length of the longest input line:
awk '{ if (length($0) > max) max = length($0) } END { print max }' data

# Print every line that is longer than 80 characters:
awk 'length($0) > 80' data

# Print the length of the longest line in data:
expand data | awk '{ if (x < length()) x = length() }
END { print "maximum line length is " x }'

# Print seven random numbers from 0 to 100, inclusive:
awk 'BEGIN { for (i = 1; i <= 7; i++) print int(101 * rand()) }

# Print the total number of bytes used by files:
ls -l files | awk '{ x += $5 }
END { print "total bytes: " x }'

# Print the even-numbered lines in the data file:
awk 'NR % 2 == 0' data

# Print first two fields in opposite order:
awk '{ print $2, $1 }' file

# Print lines longer than 72 characters:
awk 'length > 72' file

# Print length of string in 2nd column
awk '{print length($2)}' file

# Add up first column, print sum and average:
{ s += $1 }
END { print "sum is", s, " average is", s/NR }
# Print fields in reverse order:
awk '{ for (i = NF; i > 0; --i) print $i }' file

# Print the last line
awk '{line = $0} END {print line}' file

# Print the total number of lines that contain the word Pat
awk '/Pat/ {nlines = nlines + 1}
END {print nlines}' file

# Print all lines between start/stop pairs:
awk '/start/, /stop/' file

# Print all lines whose first field is different from previous one:
awk '$1 != prev { print; prev = $1 }' file

# Print column 3 if column 1 > column 2:
awk '$1 > $2 {print $3}' file

# Print line if column 3 > column 2:
awk '$3 > $2' file

# Count number of lines where col 3 > col 1
awk '$3 > $1 {print i + "1"; i++}' file

# Print sequence number and then column 1 of file:
awk '{print NR, $1}' file

# Print every line after erasing the 2nd field
awk '{$2 = ""; print}' file

# Print hi 28 times
yes | head -28 | awk '{ print "hi" }'

# Print hi.0010 to hi.0099 (NOTE IRAF USERS!)
yes | head -90 | awk '{printf("hi00%2.0 f \n", NR+9)}'

# Find maximum and minimum values present in column 1
NR == 1 {m=$1 ; p=$1}
$1 >= m {m = $1}
$1 <= p {p = $1}
END { print "Max = " m, " Min = " p }

# Example of using substrings
# substr($2,9,7) picks out characters 9 thru 15 of column 2
{print "imarith", substr($2,1,7) " - " $3, "out."substr($2,5, 3)}
{print "imarith", substr($2,9,7) " - " $3, "out."substr($2,13 ,3)}
{print "imarith", substr($2,17,7) " - " $3, "out."substr($2,21 ,3)}
{print "imarith", substr($2,25,7) " - " $3, "out."substr($2,29 ,3)}

# Single space to Double space
awk '{print ; print ""}' infile > outfile

Unencrypting a directory of gpg files in perl

Here is a way to unencrypt all files in a directory which contain many gpg files

my @FList=`ls *.gpg`;
foreach $FFile (@FList)
open (MYFILE, "echo $secret | gpg --batch --passphrase-fd 0 --decrypt $FFile | cut -c2-5 |");
while (){
print "Line # ".$i." ".$_;
close MYFILE;

Automatic FTP

Here is a way to automate FTP through script.

stty -echo
read -p "FTP Password: " ftpsecret; echo
stty echo

ftp -n <quote USER myuser
quote PASS $ftpsecret
cd the/directory
mget *

Chopping with BASH

We can use a form of variable expansion to select a specific substring, based on a specific character offset and length. Try typing in the following lines under bash:

$ EXCLAIM=cowabunga
$ echo ${EXCLAIM:0:3}
$ echo ${EXCLAIM:3:7}

This form of string chopping can come in quite handy; simply specify the character to start from and the length of the substring, all separated by colons.

$ MYVAR=foodforthought .jpg
$ echo ${MYVAR##*fo}
$ echo ${MYVAR#*fo}

In the first example, we typed ${MYVAR##*fo}. What exactly does this mean? Basically, inside the ${ }, we typed the name of the environment variable, two ##s, and a wildcard ("*fo"). Then, bash took MYVAR, found the longest substring from the beginning of the string "foodforthought.jpg " that matched the wildcard "*fo", and chopped it off the beginning of the string.

The second form of variable expansion shown above appears identical to the first, except it uses only one "#" -- and bash performs an almost identical process. It checks the same set of substrings as our first example did, except that bash removes the shortest match from our original string, and returns the result. So, as soon as it checks the "fo" substring, it removes "fo" from our string and returns "odforthought.jpg" .

$ MYFOO="chickensoup. tar.gz"
$ echo ${MYFOO%%.*}
$ echo ${MYFOO%.*}
chickensoup.tarAs you can see, the % and %% variable expansion options work identically to # and ##, except they remove the matching wildcard from the end of the string. Note that you don't have to use the "*" character if you wish to remove a specific substring from the end:

MYFOOD="chickensoup "
$ echo ${MYFOOD%%soup}

In this example, it doesn't matter whether we use "%%" or "%", since only one match is possible.

Thursday, August 13, 2009

JDBC Connection pool Status using Jython

    print '---------------------- JDBC CONNECTION POOLS ---------------------'
    print 'Name Maxcapacity ActiveCurrent ActiveHighCount WaitSecondsHighCount \
    WaitingCurrentCount State'
    print ' '
    for poolRT in poolrtlist:
        pname = poolRT.getName()
        pmaxcapacity = poolRT.getAttribute("MaxCapacity")
        paccc = poolRT.getAttribute("ActiveConnectionsCurrentCount")
        pachc = poolRT.getAttribute("ActiveConnectionsHighCount")
        pwshc = poolRT.getAttribute("WaitSecondsHighCount")
        pwfccc = poolRT.getAttribute("WaitingForConnectionCurrentCount")
        pstate = poolRT.getAttribute("State")
        print pname,' ',pmaxcapacity,' ',paccc,' ',pachc,' '\
        ,pwshc,' ',pwfccc,' ',pstate
        print ' '
    print "This Server has no JDBC Connection Pool"

Tuesday, August 11, 2009

Sending mail from unix box with attachment

First create the message in a text file and give below command

mailx -s "SQL File you requested" < message |/usr/bin/uuencode >> message

Friday, August 07, 2009

FTP port forwarding using Iptables

[a] is WAN interface with (just an example) IP assigned to it, [b] is NIC with and [c] is server’s interface with IP All what we need is that users from Internet can access FTP server using IP and default 21 TCP port.

One of the main problems is that passive mode of FTP service uses any port from range 1024 to 65535 so it’s not enough to forward 21/20 ports to FTP server and let the ball rolling. So, go to servers’ CLI and open configuration file of an FTP service. It would be vsftpd, proftpd whatever. Let’s say we have vsftpd so we have to add the following lines to /etc/vsftpd.conf:



When changes are saved restart vsftpd server.

Now access router’s CLI and type the following:

iptables -t nat -I PREROUTING -d -p tcp -m tcp --dport 21 -j DNAT --to-destination

iptables -t nat -I PREROUTING -d -p tcp -m tcp --dport 12000:13000 -j DNAT --to-destination

This will add netfilter port forwarding rules which will redirect traffic coming at routers’ public IP through 21 TCP port to FTP server and will properly handle passive FTP mode.

Backing Up Postgresql

Backup: $ pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

Restore: $psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}

Backup a single postgres database

This example will backup wp database that belongs to user smartgeek, to the file mydb.sql

$ pg_dump -U smartgeek wp -f mydb.sql

It prompts for password, after authentication mydb.sql got created with create table, alter table and copy commands for all the tables in the wp database.

Backup all postgres databases

To backup all databases, list out all the available databases as shown below.

Login as postgres / psql user:

$ su postgres

List the databases:

$ psql -l

Backup all postgres databases using pg_dumpall:

You can backup all the databases using pg_dumpall command.

$ pg_dumpall > alldb.sql

Backup a specific postgres table

$ pg_dump –table products -U smartgeek shop -f onlytable.sql

To backup a specific table, use the -table TABLENAME option in the pg_dump command. If there are same table names in different schema then use the -schema SCHEMANAME option.

Restore a postgres database

$ psql -U smartgeek -d wp_devel -f mydb.sql

This restores the dumped database to the wp_devel database.

Backup a local postgres database and restore to remote server using single command:

$ pg_dump dbname | psql -h hostname dbname

Restore all the postgres databases

$ su postgres

$ psql -f alldb.sql

Restore a single postgres table

The following psql command installs the mytable in the smartgeek database.

$ psql -f mytable.sql smartgeek

Set limits on users

The ulimit programs allow to limit system-wide resource use using a normal configuration file - /etc/security/limits.conf. This can help a lot in system administration, e.g. when a user starts too many processes and therefore makes the system unresponsive for other users.

$ ulimit -a

core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 20
file size (blocks, -f) unlimited
pending signals (-i) unlimited
max locked memory (kbytes, -l) unlimited
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) unlimited
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) unlimited
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited


smartgeek hard nproc 20
@geeks hard nproc 50

Above will prevent user “smartgeek” to create more than 20 process and anyone in the geeks group from having more than 50 processes.

There are many more setting and limits that you can set on a particular user or to a entire group like ..

using below configuration will prevent any users in the system to logins not more than 3 places at same time.
* hard maxlogins 3

Limit on size of core file
* hard core 0

Linux as Internet Gateway

Step 1. Add 2 Network cards to the Linux box

Step 2. Verify the Network cards, check if they installed properly or not

Step 3. Configure eth0 for Internet with a Public (External network or Internet)
# cat ifcfg-eth0
BROADCAST=xx.xx.xx.255 # Optional Entry
HWADDR=00:50:BA:88:72:D4 # Optional Entry
NETMASK= # Provided by the ISP
NETWORK=xx.xx.xx.0 # Optional
GATEWAY=xx.xx.xx.1 # Provided by the ISP

Step 4. Configure eth1 for LAN with a Private IP (Internal private network)
# cat ifcfg-eth1
HWADDR=00:50:8B:CF:9C:05 # Optional
NETMASK= # Specify based on your requirement
IPADDR= # Gateway of the LAN
NETWORK= # Optional

Step 5. Host Configuration (Optional)
# cat /etc/hosts nat localhost.localdomain localhost

Step 6. Gateway Configuration
# cat /etc/sysconfig/network
GATEWAY=xx.xx.xx.1 # Internet Gateway, provided by the ISP
Step 7. DNS Configuration
# cat /etc/resolv.conf
nameserver # Primary DNS Server provided by the ISP
nameserver # Secondary DNS Server provided by the ISP
Step 8. NAT configuration with IP Tables
First of all you have to flush and delete existing Firewall rules. So flush rules by typing in terminal:
iptables -F
iptables -t nat -F
iptables -t mangle -F
Now delete these chains:
iptables -X
iptables -t nat -X
iptables -t mangle -X
# Set up IP FORWARDing and Masquerading
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth1 -j ACCEPT
# Enables packet forwarding by kernel (save this setting in /etc/sysctl.conf file)
>echo 1 > /proc/sys/net/ipv4/ip_forward
#Apply the configuration
service iptables save
service iptables restart
# Check if iptables is set to start during boot up
chkconfig –list iptables
Step 9. Testing
Ping the Gateway of the network from client system: ping
Try it on your client systems: ping

Configuring PCs on the network (Clients)
All PC’s on the private office network should set their “gateway” to be the local private network IP address of the Linux gateway computer.
The DNS should be set to that of the ISP on the internet.

Windows 2000, XP, Configuration:
Select “Start” + Settings” + “Control Panel”
Select the “Network” icon
Select the tab “Configuration” and double click the component “TCP/IP” for the ethernet card. (NOT the TCP/IP -> Dial-Up Adapter)

Select the tabs:
“Gateway”: Use the internal network IP address of the Linux box. (
“DNS Configuration”: Use the IP addresses of the ISP Domain Name Servers.
“IP Address”: The IP address (192.168.XXX.XXX – static) and netmask (typically for a small local office network) of the PC can also be set here

Recover password MySQL

Step # 1 : Stop mysql service
# /etc/init.d/mysql stop

Step # 2: Start to MySQL server w/o password:
# mysqld_safe –skip-grant-tables &


edit my.cnf



start the server

service mysqld start

Step # 3: Connect to mysql server using mysql client:
# mysql -u root

Step # 4: Setup new MySQL root user password
mysql> use mysql;
mysql> update user set password=PASSWORD(”NEW-ROOT-PASSWORD”) where User=’root’;
mysql> flush privileges;
mysql> quit

Step # 5: Stop MySQL Server:
# /etc/init.d/mysql stop

Step # 6: Start MySQL server and test it
# /etc/init.d/mysql start
# mysql -u root -p

Mail somebody about space running low in some path (ksh, bash):

PATHS="/export/home /home"
DU="/usr/bin/du -ks"
DF="/usr/bin/df -k"
for path in $PATHS
DISK_AVAIL=`$DF $path | $GREP -v "Filesystem" | $AWK '{print $5}'|$SED 's/%//g'`
if [ $DISK_AVAIL -gt 90 ];then
echo "Please clean up your stuff\n\n" > $MAILFILE
$CAT $MAILFILE | $MAILER -s "Clean up stuff" $mailto

To find out the number of files of each type in your current directory

find ${*-.} -type f | xargs file | awk -F, '{print $1}' | awk '{$1=NULL;print $0}' | sort | uniq -c | sort -nr

One liner to find biggest file or directory.

du -sk ./* | sort -n | awk 'BEGIN{ pref[1]="K"; pref[2]="M"; pref[3]="G";} { total = total + $1; x = $1; y = 1; while( x > 1024 ) { x = (x + 1023)/1024; y++; } printf("%g%s\t%s\n",int(x*10)/10,pref[y],$2); } END { y = 1; while( total > 1024 ) { total = (total + 1023)/1024; y++; } printf("Total: %g%s\n",int(total*10)/10,pref[y]); }'