Monday, December 28, 2009

Jacareto

A good testing tool with macro

http://jacareto.sourceforge.net/wiki/index.php/Main_Page

Writing and Compiling in Visual Basic

To compile use the command below

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vbc.exe code.vb

Sample 1 (Console)
--------
Module Tester

Sub Main()
Console.Write("Welcome to ")
Console.WriteLine("Visual Basic!")
End Sub ' Main

End Module


Sample 2 (GUI)
--------
Imports System
Imports System.Windows.Forms

Class MyFirstForm
Inherits Form

Private WithEvents mybutton As Button

Public Sub New()
Me.Text = "Hello, WinForms!"
mybutton = New Button()
mybutton.Text = "Click Me!"
Me.Controls.Add(mybutton)
End Sub

Public Sub mybutton_Click(sender As Object, e As EventArgs) Handles mybutton.Click
MessageBox.Show("Message")
End Sub

End Class

Class MyFirstApp
Shared Sub Main()
Dim myform As Form = New MyFirstForm()
Application.Run(myform)
End Sub
End Class

Friday, December 18, 2009

Creating users in Solaris

useradd -u 2372 -s /bin/ksh -c "Thachudayakaimal, Ullas" -d /home/tullas -m tullas

/usr/sbin/groupadd -g 102 weblogic

Stop Service from Script

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
' Obtain an instance of the the class
' using a key property value.
Set objShare = objWMIService.Get("Win32_Service.Name='ActiveMQ'")

' no InParameters to define

' Execute the method and obtain the return status.
' The OutParameters object in objOutParams
' is created by the provider.
Set objOutParams = objWMIService.ExecMethod("Win32_Service.Name='ActiveMQ'", "StopService")

' List OutParams
Wscript.Echo "Out Parameters: "
Wscript.echo "ReturnValue: " & objOutParams.ReturnValue

Start Service with a script

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
' Obtain an instance of the the class
' using a key property value.
Set objShare = objWMIService.Get("Win32_Service.Name='ActiveMQ'")

' no InParameters to define

' Execute the method and obtain the return status.
' The OutParameters object in objOutParams
' is created by the provider.
Set objOutParams = objWMIService.ExecMethod("Win32_Service.Name='ActiveMQ'", "StartService")

' List OutParams
Wscript.Echo "Out Parameters: "
Wscript.echo "ReturnValue: " & objOutParams.ReturnValue

Creating Queues in Windows with C#

Compile below code with following line

c:\windows\microsoft.net\framework\v2.0.50727\csc /nologo /out:qMaker.exe qMaker.cs


#qMaker.cs

using System;
using System.Messaging;

namespace MyProject
{
///
/// Provides a container class for the example.
///

public class MyNewQueue
{

//**************************************************
// Provides an entry point into the application.
//
// This example creates new public and private
// queues.
//**************************************************

public static void Main()
{
// Create a new instance of the class.
MyNewQueue myNewQueue = new MyNewQueue();

// Create public and private queues.
// myNewQueue.CreatePublicQueues();
myNewQueue.CreatePrivateQueues();

return;
}


//**************************************************
// Creates public queues and sends a message.
//**************************************************

public void CreatePublicQueues()
{

// Create and connect to a public Message Queuing queue.
if (!MessageQueue.Exists(".\\newPublicQueue"))
{
// Create the queue if it does not exist.
MessageQueue myNewPublicQueue =
MessageQueue.Create(".\\newPublicQueue");

// Send a message to the queue.
myNewPublicQueue.Send("My message data.");
}

// Create (but do not connect to) a second public queue.
if (!MessageQueue.Exists(".\\newPublicResponseQueue"))
{
MessageQueue.Create(".\\newPublicResponseQueue");
}

return;

}


//**************************************************
// Creates private queues and sends a message.
//**************************************************

public void CreatePrivateQueues()
{

// Create and connect to a private Message Queuing queue.
if (!MessageQueue.Exists(".\\Private$\\newPrivQueue"))
{
// Create the queue if it does not exist.
MessageQueue myNewPrivateQueue =
MessageQueue.Create(".\\Private$\\newPrivQueue");


// Send a message to the queue.
// myNewPrivateQueue.Send("My message data.");
}

// Create (but do not connect to) a second private queue.
if (!MessageQueue.Exists(".\\Private$\\newResponseQueue"))
{
MessageQueue.Create(".\\Private$\\newResponseQueue");
}

return;
}
}
}

Search and Replace strings in file with Regex

Eg

cscript searchAndReplace.vbs "jdbc:microsoft:sqlserver://GWMPAPP01:1433;DatabaseName=ReportCaster" "jdbc:microsoft:sqlserver://GWMPXXXXAPP01:1433;DatabaseName=ReportCaster" install.cfg





Dim FileName, Find, ReplaceWith, FileContents, dFileContents, regEx, CurrentMatch, CurrentMatches

Find = WScript.Arguments(0)

ReplaceWith = WScript.Arguments(1)

FileName = WScript.Arguments(2)



Set regEx = New RegExp

regEx.Pattern = Find

regEx.IgnoreCase = True

regEx.Global = True

regEx.MultiLine = True





'Read source text file

FileContents = GetFile(FileName)



'replace all string In the source file



dFileContents=regEx.Replace(FileContents, ReplaceWith)



'Compare source And result

if dFileContents <> FileContents Then

'write result If different

WriteFile FileName, dFileContents



Wscript.Echo "Replace done."

If Len(ReplaceWith) <> Len(Find) Then 'Can we count n of replacements?

Wscript.Echo _

( (Len(dFileContents) - Len(FileContents)) / (Len(ReplaceWith)-Len(Find)) ) & _

" replacements."

End If

Else

Wscript.Echo "Searched string Not In the source file"

End If



'Read text file

function GetFile(FileName)

If FileName<>"" Then

Dim FS, FileStream

Set FS = CreateObject("Scripting.FileSystemObject")

on error resume Next

Set FileStream = FS.OpenTextFile(FileName)

GetFile = FileStream.ReadAll

End If

End Function



'Write string As a text file.

function WriteFile(FileName, Contents)

Dim OutStream, FS



on error resume Next

Set FS = CreateObject("Scripting.FileSystemObject")

Set OutStream = FS.OpenTextFile(FileName, 2, True)

OutStream.Write Contents

End Function

Creating shares and setting permissions

md m:\lvshare

net share "MyShare=m:\lvshare"

cacls m:\lvshare /e/g Everyone:C

Env variable creation is Automation

Here is the batch file

REM Usage eg. thisFileName.bat 172.18.20.219 D09
setx -m /S 172.18.20.219 MAILHOST %1
setx -m /S 172.18.20.219 ENV %2

ODBC DSN Creation script

ODBCCONF.exe CONFIGSYSDSN "SQL Server" "DSN=dsGiftTracking | Description=Gift Tracking Data Source | SERVER=sqlserver01 | Trusted_Connection=Yes | Database=dbGiftTracking"

Thursday, December 10, 2009

Search and Replace function in VBS

Call this with below parameters


Eg.
cscript searchAndReplace.vbs "GWSQL2KPE1" "GPAPP01" install.cfg


Dim FileName, Find, ReplaceWith, FileContents, dFileContents, regEx, CurrentMatch, CurrentMatches
Find = WScript.Arguments(0)
ReplaceWith = WScript.Arguments(1)
FileName = WScript.Arguments(2)

Set regEx = New RegExp
regEx.Pattern = Find
regEx.IgnoreCase = True
regEx.Global = True
regEx.MultiLine = True


'Read source text file
FileContents = GetFile(FileName)

'replace all string In the source file

dFileContents=regEx.Replace(FileContents, ReplaceWith)

'Compare source And result
if dFileContents <> FileContents Then
'write result If different
WriteFile FileName, dFileContents

Wscript.Echo "Replace done."
If Len(ReplaceWith) <> Len(Find) Then 'Can we count n of replacements?
Wscript.Echo _
( (Len(dFileContents) - Len(FileContents)) / (Len(ReplaceWith)-Len(Find)) ) & _
" replacements."
End If
Else
Wscript.Echo "Searched string Not In the source file"
End If

'Read text file
function GetFile(FileName)
If FileName<>"" Then
Dim FS, FileStream
Set FS = CreateObject("Scripting.FileSystemObject")
on error resume Next
Set FileStream = FS.OpenTextFile(FileName)
GetFile = FileStream.ReadAll
End If
End Function

'Write string As a text file.
function WriteFile(FileName, Contents)
Dim OutStream, FS

on error resume Next
Set FS = CreateObject("Scripting.FileSystemObject")
Set OutStream = FS.OpenTextFile(FileName, 2, True)
OutStream.Write Contents
End Function

Monday, December 07, 2009

Apache POI and Jython

import sys

def setClassPath():
libDir = "E:/apps/jython2.5.1/com/"
classPaths = ["poi-3.5-FINAL-20090928.jar","commons-logging-1.1.jar","log4j-1.2.13.jar","poi-scratchpad-3.5-FINAL-20090928.jar"]
for classPath in classPaths:
sys.path.append(libDir + classPath)


setClassPath()

from org.apache.poi.hssf.usermodel import *
from java.io import FileInputStream

file = "users.xls"

fis = FileInputStream(file)
wb = HSSFWorkbook(fis)
sheet = wb.getSheetAt(0)

# get No. of rows
rows = sheet.getPhysicalNumberOfRows()
# print wb, sheet, rows

cols = 0 # No. of columns
tmp = 0

# This trick ensures that we get the data properly even if it
# doesn.t start from first few rows
for i in range(0, 10,1):
row = sheet.getRow(i)
if(row != None):
tmp = sheet.getRow(i).getPhysicalNumberOfCells()
if tmp > cols:
cols = tmp
# print cols

for r in range(0, rows, 1):
row = sheet.getRow(r)
# print r
if(row != None):
for c in range(0, cols, 1):
cell = row.getCell(c)
if cell != None:
# print cell
pass


print sheet.getRow(5).getCell(3)

#wb.close()
fis.close()

Setting Java Classpath in Jython

import sys

def setClassPath():
libDir = "E:/apps/jython2.5.1/com/"
classPaths = ["poi-3.5-FINAL-20090928.jar","commons-logging-1.1.jar","log4j-1.2.13.jar","poi-scratchpad-3.5-FINAL-20090928.jar"]
for classPath in classPaths:
sys.path.append(libDir + classPath)

setClassPath()

from org.apache.poi.hssf.usermodel import *
from java.io import FileInputStream

Thursday, December 03, 2009

Adobe Reader Installer Automation

FEAD Optimizer is a system that is used to compress installation files into a highly compact distributable file. The intention is of course to save on bandwidth and make installation a lot more reliable. The FEAD compressed file works sort of like an executable ZIP file. But unlike a ZIP file there are no third party tools that allow the contents to be extracted easily to a folder, also there are no command line options posted on the Netopsystems website.
In my experience of FEAD Optimized files, they take a very long time to re-compose on the target machine. When you multily the re-compose time on lots of machines, you start to wonder how to decompress the files and save yourself precious time.
Until now, the only method that I have found effective in locating the re-composed files, is to use FileMon (from www.sysinternals.com) and monitor the location of where the files are being stored. Then copying the files to a safe location and cancelling the software installation. I can then use the MSI files to deploy the software using Active Directory or the RM CC3 Management tools.
I have even emailed Netopsystems asking if there are command line options, but they have never replied. I had given up hope of ever finding the command line switches until I came across them in an installation manual for a product that uses the FEAD system.
FEAD Command line switches -nos_ne No execution ? Extracts the files from the Setup utility but does not execute the Setup utility or delete the setup files.-nos_nd No delete ? Does not remove the setup files after executing the Setup utility. If the -nos_-ne switch is also present, the -nos_-nd switch is overridden.

-nos_d Delete ? Removes the setup files after executing the Setup utility. If the -nos_-ne switch is also present, the -nos_-d switch is overridden.

-nos_s Silent mode ? Installs the setup files in silent mode. Installs automatically when using: /s, /S, -s, -S, /q, /Q, -q, -Q.

-nos_o"" Output folder ? The folder to which you want to extract the setup files.

So running the executable with the following command line switches will extract the files from the FEAD archive to a location of your choosing and not execute the setup file.
program.exe -nos_ne -nos_o"C:\FEAD_Extracted"
It is also possible to send parameters to the setup/MSI file inside the FEAD archive, for example this command would change the default installation path of an MSI installer.
program.exe -nos_d INSTALLDIR="C:\Program Files\Install Here"
To run an automated silent install of a contained MSI file use this command

program.exe -nos_d /qb
As you can see, the FEAD file is actually a lot more flexiable than it appears to be and I am supprised that Netopsystems don't put this type of information onto their support site. After all they are selling deployment software to big companies who intern sell the software to other big companies who need to deploy software with more flexibility.
Common Applications that use the FEAD Optimizer format are;
Adobe Acrobat Reader 6
Adobe Acrobat Reader 7
McAfee VirusScan 8.0i
McAfee VirusScan 7.10
and many more...

The command line options work for both version 1 and 2 of the FEAD system
I hope that you will have found this useful and that it will save you hours of figuring out how to save yourself time and effort waiting for the optimiser to finish re-composing the files that you need.
Download the FEAD Extractor Tool so that you don't need to fuss with the command line parameters.
http://www.schooltechnician.co.uk/knowledge_base/general/fead_optimizer_extract_tool.html

Basic to C Language converter

This is a good converter.


http://bax-basic.sourceforge.net/

Friday, November 20, 2009

All about command line for SQL Server

http://www.haidongji.com/2006/12/19/executing-sql-scripts-using-command-line-tools/

Search and Replace in Windows

Save below code in a file called replace.vbs.

Call this using below command

cscript searchAndReplace.vbs xxx ccc myfile.txt

It will replace all xxx with ccc


Dim FileName, Find, ReplaceWith, FileContents, dFileContents
Find = WScript.Arguments(0)
ReplaceWith = WScript.Arguments(1)
FileName = WScript.Arguments(2)

'Read source text file
FileContents = GetFile(FileName)

'replace all string In the source file
dFileContents = replace(FileContents, Find, ReplaceWith, 1, -1, 1)

'Compare source And result
if dFileContents <> FileContents Then
'write result If different
WriteFile FileName, dFileContents

Wscript.Echo "Replace done."
If Len(ReplaceWith) <> Len(Find) Then 'Can we count n of replacements?
Wscript.Echo _
( (Len(dFileContents) - Len(FileContents)) / (Len(ReplaceWith)-Len(Find)) ) & _
" replacements."
End If
Else
Wscript.Echo "Searched string Not In the source file"
End If

'Read text file
function GetFile(FileName)
If FileName<>"" Then
Dim FS, FileStream
Set FS = CreateObject("Scripting.FileSystemObject")
on error resume Next
Set FileStream = FS.OpenTextFile(FileName)
GetFile = FileStream.ReadAll
End If
End Function

'Write string As a text file.
function WriteFile(FileName, Contents)
Dim OutStream, FS

on error resume Next
Set FS = CreateObject("Scripting.FileSystemObject")
Set OutStream = FS.OpenTextFile(FileName, 2, True)
OutStream.Write Contents
End Function

Monday, November 16, 2009

Saturday, November 14, 2009

Monday, November 09, 2009

Adobe Reader Installer Automation

FEAD Optimizer is a system that is used to compress installation files into a highly compact distributable file. The intention is of course to save on bandwidth and make installation a lot more reliable. The FEAD compressed file works sort of like an executable ZIP file. But unlike a ZIP file there are no third party tools that allow the contents to be extracted easily to a folder, also there are no command line options posted on the Netopsystems website.
In my experience of FEAD Optimized files, they take a very long time to re-compose on the target machine. When you multily the re-compose time on lots of machines, you start to wonder how to decompress the files and save yourself precious time.
Until now, the only method that I have found effective in locating the re-composed files, is to use FileMon (from www.sysinternals.com) and monitor the location of where the files are being stored. Then copying the files to a safe location and cancelling the software installation. I can then use the MSI files to deploy the software using Active Directory or the RM CC3 Management tools.
I have even emailed Netopsystems asking if there are command line options, but they have never replied. I had given up hope of ever finding the command line switches until I came across them in an installation manual for a product that uses the FEAD system.
FEAD Command line switches -nos_ne No execution ? Extracts the files from the Setup utility but does not execute the Setup utility or delete the setup files.-nos_nd No delete ? Does not remove the setup files after executing the Setup utility. If the -nos_-ne switch is also present, the -nos_-nd switch is overridden.
-nos_d Delete ? Removes the setup files after executing the Setup utility. If the -nos_-ne switch is also present, the -nos_-d switch is overridden.

-nos_s Silent mode ? Installs the setup files in silent mode. Installs automatically when using: /s, /S, -s, -S, /q, /Q, -q, -Q.

-nos_o"" Output folder ? The folder to which you want to extract the setup files.

So running the executable with the following command line switches will extract the files from the FEAD archive to a location of your choosing and not execute the setup file.
program.exe -nos_ne -nos_o"C:\FEAD_Extracted"
It is also possible to send parameters to the setup/MSI file inside the FEAD archive, for example this command would change the default installation path of an MSI installer.
program.exe -nos_d INSTALLDIR="C:\Program Files\Install Here"
To run an automated silent install of a contained MSI file use this command
program.exe -nos_d /qb
As you can see, the FEAD file is actually a lot more flexiable than it appears to be and I am supprised that Netopsystems don't put this type of information onto their support site. After all they are selling deployment software to big companies who intern sell the software to other big companies who need to deploy software with more flexibility.
Common Applications that use the FEAD Optimizer format are;
Adobe Acrobat Reader 6

Adobe Acrobat Reader 7
McAfee VirusScan 8.0i

McAfee VirusScan 7.10

and many more...

The command line options work for both version 1 and 2 of the FEAD system
I hope that you will have found this useful and that it will save you hours of figuring out how to save yourself time and effort waiting for the optimiser to finish re-composing the files that you need.
Download the FEAD Extractor Tool so that you don't need to fuss with the command line parameters.
http://www.schooltechnician.co.uk/knowledge_base/general/fead_optimizer_extract_tool.html

Silent Install Parameters

Adobe Acrobat Reader 6.0 AdbeRdr60_enu_full.exe -p"-s /v\"/qn\"")
Adobe Acrobat Reader 6.0 AdbeRdr60_enu_full.exe
.NET Framework dotnetfx.exe /Q:A /R:N /C:\"install.exe /Q:A /R:N\"
7-Zip 7Zip.exe -y /q /r:n
Acrobat Reader 7.0 AdbeRdr705_esp_full.exe /w /v"/qb"
AdbeRdr60_enu_full
AdbeRdr60_enu_full.exe AdbeRdr60_enu_full.exe
adobe adobe.ex -p
Adobe Acrobat Reader
Adobe Acrobat Reader AdbeRdr60_enu_full.exe like -p"-s /v\"/qn\"")
Adobe Acrobat Reader 6.0 AdbeRdr60_enu_full.exe -p"-s /v\"/qn\""
Adobe Acrobat Reader 6.0 AdbeRdr60_hun.exe /qn
Adobe Acrobat Reader 6.0 AdbeRdr60_enu_full.exe -p"-s /v\"/qn\""
Adobe Acrobat Reader 7.0 AdbeRdr60_enu_full.exe -p"-s /v\"/qn\""
Adobe Acrobat Reader 7.0 like AdbeRdr60_enu_full.exe like -p"-s /v\"/qn\""
firefox firefox.exe -p intalar!!!
Flash Player 7.0 flashplayer7installer.exe /S
J2SE(TM) Runtime Enviroment 5.0 Update 4 jre-1_5_0_04-windows-i586-p.exe /s /v"/qb ADDLOCAL=ALL"

J2SE(TM) Runtime Enviroment 5.0 Update 4 jre-1_5_0_04-windows-i586-p.exe /s /v"/qb ADDLOCAL=ALL"

Mozilla Firefox 1.5 Firefox Setup 1.5.exe -ms
MSXML 4 SP msxml.msi /qb REBOOT=REALLYSUPPRESS
nero nero.exe /Q:A /R:N /C:\"setup_wm.exe /Q:A /R:N /DisallowSys
Office 2003 Professional SETUP.EXE TRANSFORMS=einstellungen.mst /qb-
Opera 8.50 ow32enen850.exe /S
ShockWawe 10.0.0.210 Shockwave_Installer_Full.exe /S
Windows Media Player 10 MP10Setup.exe /q:A /c:"setup_wm.exe /Q /R:N /DisallowSystemRest
winzip winzip90.exe /S

Monday, November 02, 2009

Learn Design Patterns

http://perfectjpattern.sourceforge.net/

Great Jython tutorial

http://onjava.com/pub/a/onjava/2002/03/27/jython.html

Swing with Jython - I

from javax.swing import *


#from java.awt.event import *

from java.awt import *

from java.lang import *



win = JFrame("This is a frame")

win.bounds = 100,100,100,100

win.defaultCloseOperation = 3 #EXIT_ON_CLOSE



menuBar = JMenuBar()

fileMenu = JMenu("File")

menuBar.add(fileMenu);



newMenuItem = JMenuItem("New")

newMenuItem.actionPerformed=lambda event : System.out.println("Clicked on New Menu Item")

fileMenu.add(newMenuItem)



openMenuItem = JMenuItem("Open")

openMenuItem.actionPerformed=lambda event : System.out.println("Clicked on Open Menu Item")

fileMenu.add(openMenuItem)



saveMenuItem = JMenuItem("Save")

saveMenuItem.actionPerformed=lambda event : System.out.println("Clicked on Save Menu Item")

fileMenu.add(saveMenuItem)

saveMenuItem.enabled = 0 #false



win.JMenuBar = menuBar



contentPane = win.contentPane

contentPane.layout = GridLayout()



buttonOne = JButton("Button One")

buttonOne.actionPerformed=lambda event : System.out.println("Clicked on Button One")

contentPane.add(buttonOne)



buttonTwo = JButton("Button Two")

buttonTwo.actionPerformed=lambda event : System.out.println("Clicked on Button Two")

contentPane.add(buttonTwo)



buttonThree = JButton("Button Three")

buttonThree.actionPerformed=lambda event : System.out.println("Clicked on Button Three")

contentPane.add(buttonThree)



win.pack()

win.show()

Tuesday, September 29, 2009

Solaris: Which process is associated with a socket connection?

Consider the following real world scenario (copied from an e-mail message that I got from one of our partners):

[...] one process is waiting for a very long time in a send system call. It is sending on a valid fd but the question we have is that, is there any way to find who is on the other end of that fd? We want to know to which process is that message being sent to. [...]

Here is how I proceed in finding the other end of the socket, and the state of the socket connection with Mozilla's Thunderbird mail client in one end of the socket connection:

Get the process id of the application

% prstat PID USERNAME SIZE RSS STATE PRI NICE TIME CPU PROCESS/NLWP 22385 mandalik 180M 64M sleep 49 0 0:05:15 0.1% thunderbird-bin/5

Run pfiles on the pid - it prints a list of open files including open sockets (pfiles is the Solaris supported equivalent of lsof utility).

% pfiles 2238522385: /usr/lib/thunderbird/thunderbird-bin -UILocale C -contentLocale C Current rlimit: 512 file descriptors ... ... 33: S_IFSOCK mode:0666 dev:280,0 ino:31544 uid:0 gid:0 size:0 O_RDWR
O_NONBLOCK SOCK_STREAM SO_SNDBUF(49152),SO_RCVBUF(49640) sockname: AF_INET 192.168.1.2 port: 60364 peername: AF_INET 192.18.39.10 port: 993 ... ...

Locate the socket id and the corresponding sockname/port#, peername/port# in the output of pfiles pid (see step #2).

Here my assumption is that I know the socket id I'm interested in. In the above output, 33 is the socket id. One end of the socket is bound to port 60364 on the local host 192.168.1.2; and the other end of the socket is bound to port 993 on the remote host 192.18.39.10.

Run netstat -a
egrep "
(get the port numbers from step 3); and check the state of the socket connection. If you see anything other than ESTABLISHED, it indicates trouble.

% netstat -a
egrep "60364
993"solaris-devx-iprb0.60364 mail-sfbay.sun.com.993 48460 0 49640 0 ESTABLISHED

If you want to see the host names in numbers (IP addresses), run netstat with option -n.

% netstat -an
egrep "60364
993"192.168.1.2.60364 192.18.39.10.993 49559 0 49640 0 ESTABLISHED

Now since we know both ends of the socket, we can easily get the state of the socket connection at the other end by running netstat -an
egrep '

If the state of the socket connection is CLOSE_WAIT, have a look at the following diagnosis: CPU hog with connections in CLOSE_WAIT.

Finally to answer ... which process is that message being sent to ... part of the original question:

Follow the above steps and find the remote host (or IP) and remote port number. To find the corresponding process id on the remote machine to which the other half of the socket belongs to, do the following:

Login as root user on the remote host.

cd /proc

Run pfiles *
egrep "^[0-9]
sockname" > /tmp/pfiles.txt.

vi /tmp/pfiles.txt and search for the port number. If you scroll few lines up, you can see the process ID, name of the process along with its argument(s).

Thursday, September 24, 2009

Find Duplicate records in Oracle

SELECT COL_TO_CHECK, COUNT(COL_TO_CHECK)
FROM TABLE_NAME
GROUP BY COL_TO_CHECK
HAVING COUNT(COL_TO_CHECK) > 1

Thursday, September 10, 2009

Change network setting from DHCP to Static

[root@host ~]# ifconfig


eth0 Link encap:Ethernet HWaddr 00:D0:BC:08:09:BC

inet addr:70.238.17.69 Bcast:255.255.255.255 Mask:255.255.255.248

inet6 addr: fe80::2d0:b7ff:fe08:9bb/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:7174 errors:0 dropped:0 overruns:0 frame:0

TX packets:2305 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:5339910 (5.0 MiB) TX bytes:170109 (166.1 KiB)



lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:34 errors:0 dropped:0 overruns:0 frame:0

TX packets:34 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:4275 (4.1 KiB) TX bytes:4275 (4.1 KiB)




cat /etc/hosts


# Do not remove the following line, or various programs

# that require network functionality will fail.

127.0.0.1 myhost.mydomain.com myhost localhost.localdomain localhost

192.168.1.100 myhost.mydomain.com myhost

::1 localhost6.localdomain6 localhost6







cat /etc/sysconfig/network-scripts/ifcfg-eth0

DEVICE=eth0

BOOTPROTO=dhcp

HWADDR=00:D0:B7:08:09:BB

ONBOOT=yes







Change above file to below one

OUTPUT for static IP (example)

#

# File: ifcfg-eth0

#

DEVICE=eth0

IPADDR=192.168.1.100

NETMASK=255.255.255.0

BOOTPROTO=static

ONBOOT=yes

#

# The following settings are optional

#

BROADCAST=192.168.1.255

NETWORK=192.168.1.0

TYPE=Ethernet









Also confirm below files have correct entry

cat /etc/sysconfig/network

NETWORKING=yes

HOSTNAME=myhost

GATEWAY=192.168.1.1









Now restart network

/etc/rc.d/init.d/network restart





Check all with below command

ethtool eth0

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):
    pass

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 =>', Initialised.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

try:
    print '---------------------- Application status ---------------------'
    mBeans=adminHome.getMBeansByType("ApplicationRuntime")
    for bean in mBeans:
        if server_name != bean.getObjectName().getLocation():
            continue
        components= bean.lookupComponents()
        for componentRTList in components:
            app = componentRTList.getParent().getName()
            istate=componentRTList.getDeploymentState()

            if istate == 0:
                istate='UNPREPARED'
            if istate == 1:
                istate='PREPARED'
            if istate == 2:
                istate='ACTIVE'
            if istate == 3:
                istate='NEW'

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

except:
    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.

/etc/hosts.allow
portmap:192.168.0.
rpc.mountd:192.168.0 .
rpc.nfsd:192.168.0.
nasd:192.168.0.

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

/home/ullas 192.168.0.1(rw)

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
or
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
ENGINEER.NET.IN
Then to /etc/krb.realms
.ENGINEER.NET.IN
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 engineer.net.in is realm. Issue the following command
kdb5_util create -s -r engineer.net.in
This will create database /var/kerberos/krb5kd c/principal for the realm. Master ket name will be like K/M@engineer.net.in, 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
/sbin/kadmin.local
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
/sbin/kadmin.local
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 r.net.in
Then go to the workstation called pattabi andkadmin which can be had after kinit
ktadd -k /etc/krb5.keytab host/pattabi.enginee r.net.in

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).

id:5:initdefault:

That is it

Terminal Server Setup

This is a terminal setup for Fedora Core1

1) In /etc/init.d/xfs change
From
daemon xfs -droppriv -daemon
To
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
#no-listen=tcp

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

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

6) In /etc/X11/gdm/gdm.con f
[xdmcp]
Enable=true
Port=177

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 192.168.0.1

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 192.168.0.1

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

[global]
# -------------------- - 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
socket options = TCP_NODELAY SO_RCVBUF=8192 IPTOS_LOWDELAY SO_RCVBUF=8192 SO_SNDBUF=8192
; 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 = 192.168.0.1/24 127.0.0.1/24
; 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 = 192.168.0.100

; 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 0.0.0.0/0
hosts allow = 192.168.0.0/255.255. 255.0 127.0.0.1
; 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



[netlogon]
; 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


[profiles]
# 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


[IPC$]
; -- Security -- This sees to it that only allowed network IPC are as said in hosts allow
hosts allow = 192.168.0.0/24 127.0.0.1
hosts deny = 0.0.0.0/0


[printers]
# 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

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


[homes]
;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



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

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


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

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

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


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



[cdrom1]
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

[cdrom]
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


[accounting]
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

[ServerFloppy]
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

[backup]
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/id_rsa.pub

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
ypserv
yppasswdd
ypbind
portmap

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

ypserver 192.168.0.1 (server ip)

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

#Always allow localhost
255.0.0.0 127.0.0.0
#Our Lan
255.255.255.0 192.168.0.0
#For everyone put this
0.0.0.0 0.0.0.0

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
-ftp

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/slapd.pid

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

HOST 127.0.0.1
BASE dc=index,dc=com

3) Now configure /etc/ldap.conf

host 127.0.0.1
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 otok.so debug
auth required /lib/security/Pam_wh eel.so 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
line.

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
following.

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

anonymous:
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
or
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.

ramesh
sujatha
suvas

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
/usr/share/ssl
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/ sign.sh 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/quota.group
chmod 600 quota.user quota.group

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.

GNUPg

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 (http://web.archive.org/web/20050415033810/http://ullas.modblog.com/?gourl=http://enigmail.mozdev.org/download.html).

Telnet to Mail

Here is a way to telnet to mail server.

telnet 192.168.111.24 25
Trying 192.168.111.24...
Connected to et24 (192.168.111.24).
Escape character is '^]'.
220 mail.embeddedteam.co m ESMTP Postfix
helo 192.168.111.24
250 mail.embeddedteam.co m
mail from:
250 Ok
rcpt to:
250 Ok
data
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 192.168.0.0/24

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

nmap -sP -PI 192.168.0.0/24

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
http://www.webreference.com/programming/perl/modules/2.html

AWK Oneliners

Taken from http://web.archive.org/web/20060212103434/http://ullas.modblog.com/?gourl=http://www.softpanorama.org/Tools/awk.shtml

# 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." ".$_;
$i++;
}
close MYFILE;

Automatic FTP

Here is a way to automate FTP through script.

#!/bin/sh
stty -echo
read -p "FTP Password: " ftpsecret; echo
stty echo

ftp -n 201.54.111.157 <quote USER myuser
quote PASS $ftpsecret
cd the/directory
binary
hash
ls
mget *
bye
END_SCRIPT

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}
cow
$ echo ${EXCLAIM:3:7}
abunga

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}
rthought.jpg
$ echo ${MYVAR#*fo}
odforthought.jpg



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%%.*}
chickensoup
$ 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}
chicken

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

try:
    poolrtlist=home.getMBeansByType('JDBCConnectionPoolRuntime')
    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 ' '
except:
    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" t.ullas@gmail.com < message |/usr/bin/uuencode sql.zip sql.zip >> message

Friday, August 07, 2009

FTP port forwarding using Iptables

[a] is WAN interface with 212.213.214.215 (just an example) IP assigned to it, [b] is NIC with 192.168.0.1 and [c] is server’s interface with IP 192.168.0.2. All what we need is that users from Internet can access FTP server using 212.213.214.215 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:

pasv_min_port=12000

pasv_max_port=13000

When changes are saved restart vsftpd server.

Now access router’s CLI and type the following:

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

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

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

Example;

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
DEVICE=eth0
BOOTPROTO=none
BROADCAST=xx.xx.xx.255 # Optional Entry
HWADDR=00:50:BA:88:72:D4 # Optional Entry
IPADDR=xx.xx.xx.xx
NETMASK=255.255.255.0 # Provided by the ISP
NETWORK=xx.xx.xx.0 # Optional
ONBOOT=yes
TYPE=Ethernet
USERCTL=no
IPV6INIT=no
PEERDNS=yes
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
BOOTPROTO=none
PEERDNS=yes
HWADDR=00:50:8B:CF:9C:05 # Optional
TYPE=Ethernet
IPV6INIT=no
DEVICE=eth1
NETMASK=255.255.0.0 # Specify based on your requirement
BROADCAST=”"
IPADDR=192.168.1.1 # Gateway of the LAN
NETWORK=192.168.0.0 # Optional
USERCTL=no
ONBOOT=yes

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

Step 6. Gateway Configuration
# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=nat
GATEWAY=xx.xx.xx.1 # Internet Gateway, provided by the ISP
Step 7. DNS Configuration
# cat /etc/resolv.conf
nameserver 208.67.222.222 # Primary DNS Server provided by the ISP
nameserver 208.67.220.220 # 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 192.168.2.1
Try it on your client systems: ping google.com

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. (192.168.1.1)
“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 255.255.0.0 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 &

Or

edit my.cnf

[mysqld]

skip-grant-tables

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"
AWK=/usr/bin/awk
DU="/usr/bin/du -ks"
GREP=/usr/bin/grep
DF="/usr/bin/df -k"
TR=/usr/bin/tr
SED=/usr/bin/sed
CAT=/usr/bin/cat
MAILFILE=/tmp/mailviews$$
MAILER=/bin/mailx
mailto="all@company.com"
for path in $PATHS
do
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
fi
done

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]); }'

Wednesday, July 29, 2009

INITTAB changes

In case you make changes to inittab file you need not reboot the system. You can gibe below command to make the chane effective.

kill -HUP 1

This will make effect the change you have made.

Monday, July 27, 2009

Grinder Load Testing Framework

1) To start the agent issue below command
java -cp "E:\apps\grinder-3.2\grinder-3.2\lib\grinder.jar" net.grinder.Grinder

2) To start the console
java -cp "E:\apps\grinder-3.2\grinder-3.2\lib\grinder.jar" net.grinder.Console

You have to set classpath for grinder.jar and jython.jar before this.

This assumes grinder is installed at E:\apps\grinder-3.2

Use TCPProxy to create a macro of the activity of testing

Here is a sample grinder.properties file

grinder.logDirectory=log
grinder.threads=5
grinder.processes=1
grinder.runs=0
grinder.script=mailcom.py

Saturday, July 25, 2009

Swing Frame using Jython

from javax.swing import JButton, JFrame

class MyFrame(JFrame):
def __init__(self):
JFrame.__init__(self, "Hello Jython")
button = JButton("Hello", actionPerformed=self.hello)
self.add(button)

self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(300, 300)
self.show()

def hello(self, event):
print "Hello, world!"

if __name__=="__main__":
MyFrame()

Swing using Jython

from java import awt
from pawt import swing

labels = ['7', '8', '9', '+',
'4', '5', '6', '-',
'1', '2', '3', '*',
'0', '.', '=', '/' ]

keys = swing.JPanel(awt.GridLayout(4, 4))
display = swing.JTextField()

def push(event): # Callback for regular keys
display.replaceSelection(event.actionCommand)

def enter(event): # Callback for '=' key
display.text = str(eval(display.text))
display.selectAll()

for label in labels:
key = swing.JButton(label)
if label == '=':
key.actionPerformed = enter
else:
key.actionPerformed = push
keys.add(key)

panel = swing.JPanel(awt.BorderLayout())
panel.add("North", display)
panel.add("Center", keys)
swing.test(panel)

Swing using Jython

from java import awt
from pawt import swing

labels = ['7', '8', '9', '+',
'4', '5', '6', '-',
'1', '2', '3', '*',
'0', '.', '=', '/' ]

keys = swing.JPanel(awt.GridLayout(4, 4))
display = swing.JTextField()

def push(event): # Callback for regular keys
display.replaceSelection(event.actionCommand)

def enter(event): # Callback for '=' key
display.text = str(eval(display.text))
display.selectAll()

for label in labels:
key = swing.JButton(label)
if label == '=':
key.actionPerformed = enter
else:
key.actionPerformed = push
keys.add(key)

panel = swing.JPanel(awt.BorderLayout())
panel.add("North", display)
panel.add("Center", keys)
swing.test(panel)

Friday, July 24, 2009

Awk script to create Insert statements

#!/usr/bin/awk -f
BEGIN {
# change the record separator from newline to nothing
#RS=""
# change the field separator from whitespace to newline
#FS="n"

}
{
# print the second and third line of the file
if ($1=="") $1 = "NULL";
if ($2=="") $2 = "NULL";
if ($3=="") $3 = "NULL";
if ($4=="") $4 = "NULL";
print "insert into mytable (someno,sequance,1_id1,2_id2,3_id3)values(501," NR "," $2 "," $3 "," $4")
;"


}
END {

}