Sunday, September 2, 2012

Perl script to check Kernel parameter differences between 2 Linux machines

This Perl script can be used for checking the Kernel Parameters difference between 2 Linux machines.
All you got to do is, take the ‘sysctl –a’ output into a file from each Linux machine that you wish to compare and give it as an input for this script like shown below:
Upon execution, you need to choose option 1 or 2.  ‘1’ is for listing out all the kernel parameter values of both servers in tabular form and ‘2’ for listing out only the parameters that are either differing or non-exist on other server.
 # perl  <scriptname>.pl  <first_server_kernel.txt>  <second_server_kernel.txt>



#!/usr/bin/perl
# Description   :       This script can be used to list out of the differences in the Kernel Settings between 2 Linux Servers.        
#                       It takes 2 files (consists of sysctl -a output) as input, upon execution it asks for User's choice either      
#                       to List out all the Kernel parameter of 2 Servers or to list out only the Differences.                        
# Version       :       1.1                                                                                                            
# Execution method :    Manual (by any normal user)                                                                                    

if( @ARGV != 2 )
{
   print "\nUsage: $0 <First-file> <Second-file>\n\n";
   print "First-file should contain 'sysctl -a' output taken from first Linux Machine\n\n";
   print "Second-file should contain 'sysctl -a' output taken from Second Linux Machine\n\n";
   exit 1;
}

open(File1, "$ARGV[0]" );
open(File2, "$ARGV[1]" );

my @first_file = <File1>;
my @second_file = <File2>;
my %output1, %output2, %kerparm;
my ($cnt1,$cnt2) = (0,0);

print "\nEnter '1' for Listing all Kernel parameters or '2' to list only the Differences : ";
my $choice=<STDIN>;
chomp($choice);

system $^O eq 'MSWin32' ? 'cls' : 'clear';
printf("%-50s %-25s %-50s\n\n", "KERNEL PARAMETER", "FIRST SERVER", "SECOND SERVER");

foreach $i(@first_file) {
        $i =~ s/\s+$//;
        @array1 = split(" = ",$i);
        $output1{$array1[0]} = $array1[1];
        $cnt1++;
        $kerparm{$array1[0]} = $cnt1;
}

foreach $j(@second_file) {
        $j =~ s/\s+$//;
        @array2 = split(" = ",$j);
        $output2{$array2[0]} = $array2[1];
        $cnt2++;
        $kerparm{$array2[0]} = $cnt2;
}

foreach $key (sort keys %kerparm)
{
  $output1{$key} = "" unless defined $output1{$key};
  $output2{$key} = "" unless defined $output2{$key};
  if($choice eq '1') {
          printf("%-50s %-25s %-50s\n", $key,$output1{$key},$output2{$key}); }
  elsif($choice eq '2') {
          printf("%-50s %-25s %-50s\n", $key,$output1{$key},$output2{$key}) if ($output1{$key} ne $output2{$key});
  }
}

Friday, August 24, 2012

PowerCLI script to get the status of CPU/Memory Hot-Plug in vSphere5

Get-VM | Get-View | Select Name, `
@{N="CpuHotAddEnabled";E={$_.Config.CpuHotAddEnabled}}, `
@{N="CpuHotRemoveEnabled";E={$_.Config.CpuHotRemoveEnabled}}, `
@{N="MemoryHotAddEnabled";E={$_.Config.MemoryHotAddEnabled}} | Export-Csv C:\<path>\file.csv

Wednesday, August 22, 2012

Bash script to stop and disable list of services in Linux

# Defining List of unwanted services
SERVICES="rhnsd sendmail cups netfs autofs nfslock mdmonitor isdn cpuspeed rpcidmapd rpcgssd iptables xfs pcmcia smartd"

# Finding each service status
for service in $SERVICES; do
  if [ -f /etc/init.d/$service ]; then
     # Turning off the service
      chkconfig $service off
     if_running=`service $service status | egrep -i running`
      # Stopping the service if it is running
      [ ! -z "$if_running" ] && service $service stop
  fi
done

Tuesday, August 21, 2012

Sample script to change JDK version

#!/bin/bash
# Purpose      :  For changing JDK version to 1.6.0_14 non-interactively. This script could be useful for
#                      changing the JDK version automatically on multiple servers. I have used this script in a
#                      production change where we got to update JDK version simultaneously on 60+ servers.  
# Assumption :  The Binary version of JDK version 1.6.0_14 already installed under /usr/java/jdk1.6.0_14"

/usr/sbin/alternatives --install /usr/bin/java java /usr/java/jdk1.6.0_14/bin/java 1
/usr/sbin/alternatives --set java /usr/java/jdk1.6.0_14/bin/java

/usr/sbin/alternatives --install /usr/bin/javac javac /usr/java/jdk1.6.0_14/bin/javac 1
/usr/sbin/alternatives --set javac /usr/java/jdk1.6.0_14/bin/javac

unlink /usr/bin/java
ln -s /usr/java/jdk1.6.0_14/bin/java /usr/bin/java

sed -i.bak '/export/ i JAVA_HOME=/usr/java/jdk1.6.0_14\nPATH=$PATH:$JAVA_HOME/bin\nJAVAPTH=$JAVA_HOME/bin\n' /etc/profile

sed -i.bak 's/export.*$/export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC JAVA_HOME JAVAPTH/' /etc/profile

java -version 2&> java_ver

java_ver=`cat java_ver | grep java | cut -c 15-22`

if [ "$java_ver" != "1.6.0_14" ]; then
echo -e "Updating JDK version to 1.6.0_14 Failed. Please check manually.\n"
exit 1
else
rm -f ./java_ver
echo -e "\n\n\nJDK version has been successfully changed to 1.6.0_14.\n\n"
fi

Friday, July 27, 2012

How to debug a Bash shell script ?

When executing a shell script use 'bash' command with below options to debug a shell script in effective way. 
 -x if you set this option, it will show you each line before it executes it. Comments will not be reported.
sh -x scriptname.sh
-v Echo’s each line as it is read. It’s a kind of verbose and even echo back commented lines too.
sh -v scriptname.sh
Note: A small difference between –x and –v is that –v echo’s the line as it is read (So it will even display comments too.), whereas –x flag causes each command to be echoed as it is executed.
sh -xv scriptname.sh
-u –At times you use a variable without setting some value to it. If you use this flag it will give you the error saying so and so variable is not set before executing the script.
-e –Exit the shell script if any error occurs. This option will stop the script to run further once the script encounters an error. Use full for debugging the first error itself when running big scripts…
sh -e scriptname.sh

Saturday, July 14, 2012

Bash syntax to calculate sum list of numeric values in a file

Lets say you have a file which consists list of Numeric values and wish to add the total sum of all the numeric values. The bash syntax would be:
sum=0; for i in `cat filename.txt`; do sum=$(( $sum + $i )); done; echo $sum
(or)
declare -i sum=0; for i in `cat filename.txt`; do sum+=$i; done; echo $sum

Friday, June 22, 2012

Useful Run Commands For Windows 7

List of commands that you can run off from the Run Command prompt in Windows 7:

To get the command prompt, press Windows logo key + R 

Administrative Tools
Administrative Tools = control admintools
Authorization Manager = azman.msc
Component Services = dcomcnfg
Certificate Manager = certmgr.msc
Direct X Troubleshooter = dxdiag 
Display Languages = lpksetup
ODBC Data Source Administrator = odbcad32
File Signature Verification Tool = sigverif
Group Policy Editor = gpedit.msc
Add Hardware Wizard = hdwwiz.cpl
iSCSI Initiator = iscsicpl
Iexpress Wizard = iexpress
Local Security Settings = secpol.msc
Microsoft Support Diagnostic Tool = msdt
Microsoft Management Console = mmc
Print management = printmanagement.msc
Printer User Interface = printui
Problems Steps Recorder = psr
People Near Me = p2phost 
Registry Editor = regedit or regedt32
Resoure Monitor = resmon
System Configuration Utility = msconfig
Resultant Set of Policy = rsop.msc
SQL Server Client Configuration = cliconfg
Task Manager = taskmgr
Trusted Platform Module = tpm.msc
TPM Security Hardware = TpmInit 
Windows Remote Assistance = msra
Windows Share Folder Creation Wizard = shrpubw
Windows Standalong Update Manager = wusa
Windows System Security Tool = syskey
Windows Script Host Settings = wscript
Windows Version = winver
Windows Firewall with Advanced Security = wf.msc
Windows Memory Diagnostic = MdSched
Windows Malicious Removal Tool = mrt 

Computer Management
Computer Management = compmgmt.msc or CompMgmtLauncher
Task Scheduler = control schedtasks
Event Viewer = eventvwr.msc
Shared Folders/MMC = fsmgmt.msc
Local Users and Groups = lusrmgr.msc
Performance Monitor = perfmon.msc
Device Manager = devmgmt.msc
Disk Management = diskmgmt.msc
Services = services.msc
Windows Management Infrastructure = wmimgmt.msc

Conrtol Panel
Control Panel = control
Action Center= wscui.cpl 
Autoplay = control.exe /name Microsoft.autoplay
Backup and Restore = sdclt
Create a System Repair disc = recdisc
BDE Administrator = bdeadmin.cpl
Color Management = colorcpl 
Credential Manager = control.exe /name Microsoft.CredentialManager
Credential Manager Stored User Names and Passwords = credwiz
Date and Time Properties = timedate.cpl
Default Programs = control.exe /name Microsoft.DefaultPrograms
Set Program Access and Computer Defaults = control appwiz.cpl,,3 or ComputerDefaults
Devices and Printers = control printers
Devices and Printers Add a Device = DevicePairingWizard
Display = dpiscaling 
Screen Resolution = desk.cpl
Display Color Calibration = dccw 
Cleartype Text Tuner = cttune 
Folders Options = control folders
Fonts = control fonts
Getting Started = GettingStarted
HomeGroup = control.exe /name Microsoft.HomeGroup
Indexing Options = control.exe /name Microsoft.IndexingOptions
Internet Properties = inetcpl.cpl
Keyboard = control keyboard
Location and Other Sensors = control.exe /name Microsoft.LocationandOtherSensors 
Location Notifications = LocationNotifications
Mouse = control mouse or main.cpl
Network and Sharing Center = control.exe /name Microsoft.NetworkandSharingCenter
Network Connections = control netconnections or ncpa.cpl
Notification Area Icons = control.exe /name Microsoft.NotificationAreaIcons
Parental Controls = control.exe /name Microsoft.ParentalControls
Performance Information = control.exe /name Microsoft.PerformanceInformationandTools
Personalization = control desktop
Windows Color and Appearance = control color
Phone and Modem Options = telephon.cpl
Power Configuration = powercfg.cpl
Programs and Features = appwiz.cpl or control appwiz.cpl
Optional Features Manager = optionalfeatures or control appwiz.cpl,,2
Recovery = control.exe /name Microsoft.Recovery
Regional and Language = intl.cpl
RemoteApp = control.exe /name Microsoft.RemoteAppandDesktopConnections
Sound = mmsys.cpl
Volume Mixer = sndvol
System Properties = sysdm.cpl or Windows logo key + Pause/Break
SP ComputerName Tab = SystemPropertiesComputerName
SP Hardware Tab = SystemPropertiesHardware
SP Advanced Tab = SystemPropertiesAdvanced
SP Performance = SystemPropertiesPerformance
SP Data Execution Prevention = SystemPropertiesDataExecutionPrevention
SP Protection Tab = SystemPropertiesProtection
SP Remote Tab = SystemPropertiesRemote
Windows Activation = slui
Windows Activation Phone Numbers = slui 4
Taskbar and Start Menu = control.exe /name Microsoft.TaskbarandStartMenu
Troubleshooting = control.exe /name Microsoft.Troubleshooting
User Accounts = control.exe /name Microsoft.UserAccounts
User Account Control Settings = UserAccountControlSettings
User Accounts Windows 2000/domain version = netplwiz or control userpasswords2
Encryption File System = rekeywiz
Windows Anytime Upgrade = WindowsAnytimeUpgradeui
Windows Anytime Upgrade Results = WindowsAnytimeUpgradeResults
Windows CardSpace = control.exe /name Microsoft.cardspace
Windows Firewall = firewall.cpl
WindowsSideshow = control.exe /name Microsoft.WindowsSideshow
Windows Update App Manager = wuapp

Accessories
Calculator = calc
Command Prompt = cmd
Connect to a Network Projector = NetProj
Presentation Settings = PresentationSettings
Connect to a Projector = displayswitch or Windows logo key + P
Notepad = notepad
Microsoft Paint = mspaint.exe
Remote Desktop Connection = mstsc
Run = Windows logo key + R
Snipping Tool = snippingtool 
Sound Recorder = soundrecorder 
Sticky Note = StikyNot 
Sync Center = mobsync
Windows Mobility Center (Only on Laptops) = mblctr or Windows logo key + X
Windows Explorer = explorer or Windows logo key + E 
Wordpad = write
Ease of Access Center = utilman or Windows logo key + U
Magnifier = magnify
Narrator = Narrator
On Screen Keyboard = osk
Private Character Editor = eudcedit
Character Map = charmap
Ditilizer Calibration Tool = tabcal
Disk Cleanup Utility = cleanmgr
Defragment User Interface = dfrgui
Internet Explorer = iexplore
Rating System = ticrf
Internet Explorer (No Add-ons) = iexplore -extoff
Internet Explorer (No Home) = iexplore about:blank
Phone Dialer = dialer
Printer Migration = PrintBrmUi
System Information = msinfo32
System Restore = rstrui
Windows Easy Transfer = migwiz
Windows Media Player = wmplayer
Windows Media Player DVD Player = dvdplay
Windows Fax and Scan Cover Page Editor = fxscover
Windows Fax and Scan = wfs
Windows Image Acquisition = wiaacmgr
Windows PowerShell ISE = powershell_ise
Windows PowerShell = powershell
XPS Viewer = xpsrchvw

Open Documents folder = documents
Open Pictures folder = pictures
Open Music folder = music
Open Favorites folder = favorites
Open Downloads folder = downloads
Logs out of Windows = logoff
Shuts Down Windows = shutdown

Tuesday, June 5, 2012

Calculating sum of Array elements in Perl

@array1 = `cat filename | grep Numeric_String_Value`;
$Total += $_ for @array1;
print "Total sum of Array values is $Total \n";

Wednesday, May 23, 2012

How to assign a password present in a file to a variable ?

Let's say you have a file 'secretfile' which contains the password 'newpass'. You want to assign the password mentioned in that file to a variable called 'pass1'.  The syntax will go like this:

# cat  secretfile
newpass

Method 1
# pass1=$(cat secretfile)
# echo $pass1
newpass

Method 2
# read pass1 < secretfile
# echo $pass1
newpass

Sunday, May 20, 2012

Setting alias for 'ls -l' command

I wish to enhance the default alias ('ll') for 'ls -l' command into more pleasing one:

Following is the alias options which I set for 'll' :   # alias ll='ls -lhGpt --color=always'
'-h' - Human readable
'G' - No Group information
'p' - Append / notation for folders
't' - Sort by modification time.

SAMPLE OUTPUT:

[ashok@hostxyz etc]$ ll
total 3.5M
-rw-r--r--  1 root 204K May 20 04:05 prelink.cache
-rw-r--r--  1 root  14K May 16 20:36 group
-r--------  1 root 7.6K May 16 20:36 gshadow
-rw-r--r--  1 root  43K May 16 20:36 passwd
-r--------  1 root  27K May 16 20:36 shadow
-rw-r--r--  1 root  14K May 16 20:33 group-
-r--------  1 root 7.6K May 16 20:33 gshadow-
-rw-r--r--  1 root  43K May 16 20:33 passwd-
-r--------  1 root  27K May 16 20:33 shadow-
drwxr-xr-x  2 root 4.0K May  9 05:16 ssh/
drwxr-xr-x  2 root 4.0K May  8 19:00 blkid/
drwxr-xr-x 10 root 4.0K May  8 06:11 sysconfig/
-rw-r--r--  1 root  128 May  7 03:55 resolv.conf
.
.
<Output truncated>

Syntax to check NIC statistics using 'sar' command

This syntax checks the statistics of 'eth1' interface:
[root@hostxyz ~]# sar -n DEV -f /var/log/sa/sa15 -s 18:00:01 -e 23:01:01 | head -3 | tail -1 | sed 's/^.........../           /'; sar -n DEV -f /var/log/sa/sa15 -s 18:00:01 -e 23:01:01 | grep "eth1"
                      IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
06:10:01 PM      eth1     20.54      0.02   2056.62      3.12      0.00      0.00      0.00
06:20:01 PM      eth1     26.11      0.01   2650.42      1.98      0.00      0.00      0.00
06:30:01 PM      eth1     17.03      0.01   1711.49      1.98      0.00      0.00      0.00
06:40:01 PM      eth1     10.40      0.01    972.02      1.60      0.00      0.00      0.00
06:50:01 PM      eth1     24.11      0.02   2426.33      2.74      0.00      0.00      0.00
07:00:01 PM      eth1     25.27      0.01   2554.85      1.87      0.00      0.00      0.00
07:10:01 PM      eth1     13.36      0.01   1312.31      1.98      0.00      0.00      0.00
07:20:01 PM      eth1     12.21      0.02   1175.69      3.12      0.00      0.00      0.00
07:30:01 PM      eth1     25.09      0.01   2566.25      1.98      0.00      0.00      0.00
07:40:01 PM      eth1     26.01      0.01   2612.24      1.60      0.00      0.00      0.00
07:50:01 PM      eth1    206.35    635.89  13526.21 947854.38      0.00      0.00      0.00
08:00:01 PM      eth1   1326.80   4410.98  80781.99 6673444.08      0.00      0.00      0.00
08:10:01 PM      eth1    796.86   2608.67  49050.73 3947034.38      0.00      0.00      0.00
08:20:01 PM      eth1    773.95   2411.76  47858.10 3649035.90      0.00      0.00      0.00
08:30:01 PM      eth1    798.65   2814.04  48448.94 4257857.47      0.00      0.00      0.00
08:40:01 PM      eth1 599122.53 1729538.33 3278958.93 585797.40      0.00      0.00      0.00
08:50:01 PM      eth1   1126.42   3821.02  68802.91 5781612.42      0.00      0.00      0.00
09:00:01 PM      eth1   1416.86   4984.36  85843.95 377147.69      0.00      0.00      0.00
09:10:01 PM      eth1    803.29   2777.80  48717.98 4202947.25      0.00      0.00      0.00
09:20:01 PM      eth1    129.55    352.83   8700.49 533737.74      0.00      0.00      0.00
09:30:01 PM      eth1     25.34      0.01   2581.83      1.98      0.00      0.00      0.00
09:40:01 PM      eth1     15.67      0.01   1523.95      1.79      0.00      0.00      0.00
09:50:01 PM      eth1     11.38      0.01   1066.06      1.60      0.00      0.00      0.00
10:00:01 PM      eth1     23.75      0.03   2366.47      3.01      0.00      0.00      0.00
10:10:01 PM      eth1     26.29      0.01   2679.49      1.98      0.00      0.00      0.00
10:20:01 PM      eth1     12.79      0.01   1241.40      1.98      0.00      0.00      0.00
10:30:01 PM      eth1     13.03      0.03   1273.22      3.12      0.00      0.00      0.00
10:40:01 PM      eth1     25.71      0.01   2586.43      1.60      0.00      0.00      0.00
10:50:01 PM      eth1     24.44      0.01   2448.89      1.60      0.00      0.00      0.00
11:00:01 PM      eth1     10.38      0.01    958.51      1.87      0.00      0.00      0.00
Average:         eth1    288.58    929.73  18156.03 212554.92      0.00      0.00      0.00
[root@hostxyz ~]#

Monday, May 14, 2012

Perl subroutine to check Database Status

sub CheckDBStatus($)
{
my $host = $_[0];
my $dbStatus=`ssh $host -C "ps -ef | grep ora_pmon | grep -v grep -c"`;
if ($dbStatus == 1)
{
Log("Database is up on $host",0,LOGFILE);
return("0");
}
else
{
Log("Database is down on $host",0,LOGFILE);
return("1");
}
}

Note: You can use appropriate string to capture Oracle process with grep command.

Perl subroutine to un-mount a file-system


sub UnMountVolume($)
{
  my $mountPoint = $_[0];
  print "Un-mounting $mountPoint\n";
  # Checking if the mount point exists
  if ( grep m{$mountPoint}, qx{/bin/mount} )
  {
    #Mount point exists, attempt to unmount it without force option
    system("/bin/umount $mountPoint");
  }
  else
  {
    print "$mountPoint is not mounted, please check it out\n";
  }
}

Zip files using 'find' command

Let's say we want to Zip files which are more than a week time under a folder /var/log/nmon :

# for i in `find /var/log/nmon -mtime +7 -type f -print`; do gzip $i; done

Friday, May 11, 2012

Command-line syntax to reset the password

Let’s say we have to reset the Root password of a Linux machine to “XYZabc123”.  We can use the below command set to do it. This can be executed on remote machines if we have a centralized administration server.

# echo ‘XYZabc123’ > /opt/pass; passwd --stdin root < /opt/pass; rm -f  /opt/pass

Thursday, May 10, 2012

Perl script to list all Failed Login attempts in Linux

#!/usr/bin/perl -w
# Description             :  Upon execution, this script will list all the Failed Login attempts on a Linux Server
# Mode of Execution  :  As 'root' user from shell prompt
# Developed by          :  Ashok Raj
# Version                   :  1.2
# -------------------------------------------------------------------------------------------------------------------------

$osnam=`uname -s`;
chomp($osnam);
$cnt=0;

if($osnam eq 'Linux')
{
chdir "/var/log" or die "$!";
@arylog = `cat ./secure*|grep 'Failed password'`;
print "\n";
print "REPORT ON FAILED ATTEMPT LOGINS\n\n";
print " DATE/TIME       USERNAME\tHOSTNAME/IPADDRESS\n";
print "---------------------------------------------\n";
foreach(@arylog)
 {
 if($_ =~ m/(\w+\s+\d+\s\d\d:\d\d:\d\d)\s\S+\ssshd\[\d+\]:\s+Failed\s.*?\sfor.*?\s(\w+)\sfrom\s+(\S+)/)
            {
              printf "%-16s   %-16s%-16s\n",$1,$2,$3;
              $cnt++;
            }
}
}
print "\nTotal Number of Failed Attempts: $cnt \n\n";

Monday, April 16, 2012

FUNC - Fedora Unified Network Controller Installation Script

FUNC is an open source automation tool developed by using Python programming language. We can use this tool for automating system admin tasks such as status check, configuration tweak, file transfer, rebooting the systems etc in multiple Linux-based systems. It uses the typical Client-Server model, where the server is called by the term "overlord" and the clients which are binded to the server are called as "minions".

Check out this link for more details with examples:
http://advanced-sysadmin-stuff.blogspot.in/2011/03/func-fedora-unified-network-controller.html

I have developed an Installation bundle which consists of Script for installing and configuring the FUNC client with all the required packages. URL to download the software bundle : http://dl.dropbox.com/u/50666315/blog/func_pack.tar

Just download it, extract and install the FUNC client by executing the 'install_func_client.sh' script.
http://dl.dropbox.com/u/50666315/scripts/install_func_client.sh

SAMPLE INSTALLATION:

[root func_pack]# bash install_func_client.sh

Enter the FQDN of FUNC Master Server : funcserver.domain.com

Starting RPM installation

Preparing...                ########################################### [100%]
   1:pyOpenSSL              ########################################### [100%]
Preparing...                ########################################### [100%]
   1:certmaster             ########################################### [100%]
Preparing...                ########################################### [100%]
   1:python-ctypes          ########################################### [100%]
Preparing...                ########################################### [100%]
   1:python-paste           ########################################### [100%]
Preparing...                ########################################### [100%]
   1:python-simplejson      ########################################### [100%]
Preparing...                ########################################### [100%]
   1:smolt                  ########################################### [100%]
Preparing...                ########################################### [100%]
   1:func                   ########################################### [100%]

 Proceeding with configuring the FUNC client
 PLEASE CONFIRM IF ALL THE LISTED BELOW RPMS ARE INSTALLED PROPERLY ?

pyOpenSSL-0.6-2.el5.i386.rpm
certmaster-0.27-1.el5.noarch.rpm
python-ctypes-1.0.2-2.el5.i386.rpm
python-paste-1.7.4-1.el5.noarch.rpm
python-simplejson-2.0.9-8.el5.i386.rpm
smolt-1.4-2.3.el5.noarch.rpm
func-0.27-1.el5.noarch.rpm

Type either 'yes' or 'no' : yes
Updating the config file
 Starting the FUNC Service

Starting func daemon

FUNC client service has been started successfully
Proceeding with registering to FUNC Master Server

The CSR(Certmaster Sign Request) has been successfully send to FUNC Master Server.
Please contact your FUNC Server Administrator to accept the CSR for this machine.

[root - func_pack]#

Saturday, April 14, 2012

PowerCLI: Start and Stop the VMs resides on a vCenter Folder

Starting all the VMs in the folder 'production1'

$vms = Get-VM -Location production1

ForEach($vm in $vms)                 # Start each VM in the folder 'production1'
{
start-vm -RunAsync -VM $vm -Confirm:$false
}

Stopping all the VMs in the folder 'production1'

$vms = Get-VM -Location production1
ForEach($vm in $vms)
# Try a graceful shutdown of VMGuest if vmware tools are installed, Otherwise just stop the VM
{
$vm_view = $vm | get-view
$vmtoolsstatus = $vm_view.summary.guest.toolsRunningStatus
Write-Host “VM $vm says tools status is $Vmtoolsstatus”
if ($vmtoolsstatus -eq “guestToolsRunning”)
{
Shutdown-VMGuest -VM $vm -Confirm:$false       # Shutting down VMGuest gracefully
}
else
{
Stop-VM -RunAsync -VM $vm -Confirm:$false      # Stopping the VM
}
}

Friday, April 13, 2012

PowerCLI script for listing VM partition information

This script will display the VM partition information of all the Virtual Machines (both Linux and Windows) in vCenter.

PS> ForEach ($VM in Get-VM ){($VM.Extensiondata.Guest.Disk | Select @{N="Name";E={$VM.Name}},DiskPath, @{N="Capacity(MB)";E={[math]::Round($_.Capacity/ 1MB)}}, @{N="Free Space(MB)";E={[math]::Round($_.FreeSpace / 1MB)}}, @{N="Free Space %";E={[math]::Round(((100* ($_.FreeSpace))/ ($_.Capacity)),0)}})}

<output not shown>


-------------------------------------------------------------------------------------------------------------------------------------------------------

This modified version of above script will display the VM partition information of the Virtual Machines that are hosted on ESXi host : "iss-esxi-vm01.xxxx.com"

PS> ForEach ($VM in get-vmhost iss-esxi-vm01.xxxx.com | get-vm){($VM.Extensiondata.Guest.Disk | Select @{N="Name";E={$VM.Name}},DiskPath, @{N="Capacity(MB)";E={[math]::Round($_.Capacity/ 1MB)}}, @{N="Free Space(MB)";E={[math]::Round($_.FreeSpace / 1MB)}}, @{N="Free Space %";E={[math]::Round(((100* ($_.FreeSpace))/ ($_.Capacity)),0)}})}

Name           : itc-esxi-dnx01.xxxx.com
DiskPath       : C:\
Capacity(MB)   : 51191
Free Space(MB) : 36503
Free Space %   : 71

Name           : iss-esxi-mail1.xxxx.com
DiskPath       : /
Capacity(MB)   : 1008
Free Space(MB) : 813
Free Space %   : 81

Name           : iss-esxi-mail1.xxxx.com
DiskPath       : /boot
Capacity(MB)   : 99
Free Space(MB) : 86
Free Space %   : 87

Name           : iss-esxi-mail1.xxxx.com
DiskPath       : /tmp
Capacity(MB)   : 1008
Free Space(MB) : 975
Free Space %   : 97

<output truncated>

Thursday, April 12, 2012

PowerCLI scripts for automating VMware vSphere - part 1

PS> get-vm iss-esx-scc1

Name                 PowerState Num CPUs Memory (MB)
----                 ---------- -------- -----------
iss-esx-scc1.itci... PoweredOn  2        8192

PS> get-vm iss-esx-scc1 | format-list

Name            : iss-esx-scc1.xxxx.com
PowerState      : PoweredOn
NumCpu          : 2
MemoryMB        : 8192
HardDisks       : {Hard disk 1, Hard disk 2}
CDDrives        : {CD/DVD drive 1}
FloppyDrives    : {Floppy drive 1}
NetworkAdapters : {Network adapter 1, Network adapter 2}
UsbDevices      : {}
Host            : iss-esx-vm01.xxxx.com
Id              : VirtualMachine-vm-178
Notes           :

PS> get-vm iss-esx-scc1 | format-list *

PowerState           : PoweredOn
Version                 : v7
Description            :
Notes                   :
Guest                   : iss-esx-scc1.xxxx.com:
NumCpu                  : 2
MemoryMB                : 8192
HardDisks               : {Hard disk 1, Hard disk 2}
NetworkAdapters         : {Network adapter 1, Network adapter 2}
UsbDevices              : {}
CDDrives                : {CD/DVD drive 1}
FloppyDrives            : {Floppy drive 1}
Host                    : iss-esx-vm01.xxxx.com
HostId                  : HostSystem-host-115
VMHostId                : HostSystem-host-115
VMHost                  : iss-esx-vm01.xxxx.com
VApp                    :
FolderId                : Folder-group-v22
Folder                  : vm
ResourcePoolId          : ResourcePool-resgroup-114
ResourcePool            : Resources
PersistentId            : 5256a506-9e03-ac9c-c997-b2b8936b1b0b
UsedSpaceGB             : 16.80688
ProvisionedSpaceGB      : 127.0002
DatastoreIdList         : {Datastore-datastore-148, Datastore-datastore-149}
HARestartPriority       :
HAIsolationResponse     :
DrsAutomationLevel      :
VMSwapfilePolicy        : Inherit
VMResourceConfiguration : CpuShares:Normal/2000 MemShares:Normal/81920
CustomFields            : {}
ExtensionData           : VMware.Vim.VirtualMachine
Id                      : VirtualMachine-vm-178
Name                    : iss-esx-scc1.xxxx.com
Uid                     : /VIServer=ardevaraju@iss-esx-vc02.xxxx.com:443/VirtualMachine=VirtualMachine-vm-178/

PS> get-vmhost | get-vm | where-object { $_ -like "*nim*" }

Name                 PowerState Num CPUs Memory (MB)
----                 ---------- -------- -----------
iss-esx-nimmonfp0... PoweredOn  2        4032
iss-esx-nim01.itc... PoweredOn  4        8192
iss-esx-nimsql1.i... PoweredOn  4        8192
iss-esx-nimthub01... PoweredOn  2        4096
iss-esx-nimfhub01... PoweredOn  2        4096

PS> get-vmhost | get-vm | where-object { $_.name -eq 'iss-esx-nim01' } | Get-NetworkAdapter

Name                 Type       NetworkName  MacAddress         WakeOnLan
                                                                  Enabled
----                 ----       -----------  ----------         ---------
Network adapter 1    e1000      ISS Network  00:50:56:b7:65:e3       True
Network adapter 2    e1000      VM Storag... 00:50:56:b7:3c:38       True

PS> get-vmhost | get-vm | where-object { $_.name -eq 'iss-esx-nim01' } | Get-Datastore

Name                               FreeSpaceMB      CapacityMB
----                               -----------      ----------
iss-esx-nim01:OSDISKn                    21704           81664
iss-esx-nim01:D_DISK                     19526           50944

PS > get-vmhost iss-esx-vm01 | get-vm | get-vmguest

State          IPAddress            OSFullName
-----          ---------            ----------
Running        {10.0.0.40, 10.15... Microsoft Windows Server 2008 R2 (64-bit)
Running        {172.17.1.200}       Microsoft Windows Server 2003 (32-bit)
NotRunning     {}
Running        {10.0.0.186, 10.1... Microsoft Windows Server 2008 R2 (64-bit)
NotRunning     {}
NotRunning     {}
NotRunning     {}
NotRunning     {}
NotRunning     {}
Running        {10.150.1.28, fe8... Red Hat Enterprise Linux 4 (32-bit)


Running        {10.150.4.157, fe... Red Hat Enterprise Linux 4 (32-bit)
Running        {10.150.1.35, fe8... Red Hat Enterprise Linux 5 (64-bit)
Running        {10.150.1.14}        Microsoft Windows Server 2008 (32-bit)
NotRunning     {}
Running        {10.0.0.180, 10.1... Microsoft Windows Server 2008 R2 (64-bit)
Running        {10.0.0.183, 10.1... Microsoft Windows Server 2008 R2 (64-bit)
Running        {10.150.1.16, 10.... Microsoft Windows Server 2008 R2 (64-bit)
Running        {169.254.9.208, 1... Microsoft Windows Server 2003 (32-bit)

PS> get-vmhost iss-esx-vm01 | get-vm | where {$_.Memorymb -lt 2048}

Name                 PowerState Num CPUs Memory (MB)
----                 ---------- -------- -----------
rfin-esx-mail1.it... PoweredOn  1        512
iss-esx-w2k3_32.h... PoweredOff 1        1024
iss-esx-w2k8_64.h... PoweredOff 2        1024
iss-esx-rhel5664-... PoweredOff 2        1024
hjbb-esx-ftp1.itc... PoweredOn  1        500
iss-esx-mman01.it... PoweredOn  2        512
iss-esx-sfm01.itc... PoweredOn  2        1024

PS> get-vmhost iss-esx-vm01 | get-vm | where {$_.Memorymb -gt 2048}

Name                 PowerState Num CPUs Memory (MB)
----                 ---------- -------- -----------
iss-esx-nimmonfp0... PoweredOn  2        4032
itc-esx-dnx01.itc... PoweredOn  2        4096
iss-esx-scc1.itci... PoweredOn  2        8192
iss-esx-mail1.itc... PoweredOn  2        4096
iss-esx-ad01.itci... PoweredOn  2        4096
iss-esx-mgr02.itc... PoweredOn  4        8192
iss-esx-nim01.itc... PoweredOn  4        8192
iss-esx-sdp01.itc... PoweredOn  4        4096
iss-esx-nimsql1.i... PoweredOn  4        8192

PS>

PowerCLI Banner: http://dl.dropbox.com/u/50666315/blog/Final-PowerCLI-4.1.1.pdf

Thursday, March 1, 2012

Sample Rsync script for syncing set of remote server file-systems using BASH


#!/bin/bash
#----------------------------------------------------------------------------------------------------------------------------------------------------------------
# Description      : This script can be used to sync the filesystems one server to another.
# Mode of exection : As 'root' user from Cron using the following syntax: '/opt/rsync_seq.sh >> /var/log/rsync/rsync.log 2>&1'
# Date of Creation : 01-Mar-2012
# Version          : 2.1

# DETAILS OF FILESYSTEMS TO BE SYNCED from 'Source Machine' -----> 'Remote machine'
#  mb-chic-pap01:/ua1001   ----->  mb-365c-pap01:/ua1001
#  mb-chic-pap01:/ua1002   ----->  mb-365c-pap01:/ua1002
#  mb-chic-pap01:/us1001   ----->  mb-365c-pap01:/us1001

#----------------------------------------------------------------------------------------------------------------------------------------------------------------

# Define the mail address to which Rsync status to be sent
MAIL_ADD='ashok_sysad@hotmail.com'

# Define the path of Log file
RSYNC_LOG='/var/log/rsync/rsync.log'

#Define functions for Mail Text
SUCCESS()
{
echo -e "\nRsync Completed !!!!! \nHostname: `hostname`\nCommand executed to sync: $RSYNC\nJob Run date & time : $ST_TIME\n\nScript Name: $0 \n\nLast few lines from Rsync log files. $RSYNC_LOG: \n`tail -10 $RSYNC_LOG` " | mail -s "Rsync is Finished!!!!! " $MAIL_ADD
}

FAILED()
{
 echo -e "\nRsync Failed !!!!! \n\tHostname: `hostname`\nCommand executed to sync: $RSYNC\nJob Run date & time : $ST_TIME\n\nScript Name: $0 \n\nLast few lines from Rsync log files. $RSYNC_LOG: \n`tail -10 $RSYNC_LOG` " | mail -s "Rsync Failed !!!!! " $MAIL_ADD
}

#----------------------------------------------------------------------------------------------------------------------------------------------------------------

# /ua1001   ----->  mb-365c-pap01:/ua1001

# Setting the Rsync command-set specifying the Filesystem details and required switches.
RSYNC='rsync -atlrzvuop --progress /ua1001/ root@mb-365c-pap01:/ua1001/'

# Setting this variable to capture the Rsync status
PCOUNT=`ps ax |grep -v grep |grep 'rsync -atlrzvuop --progress /ua1001/ root@mb-365c-pap01:/ua1001/' | wc -l`
ST_TIME=`date`

# Execution starts from here
        if [ $PCOUNT -eq " " ] || [ $PCOUNT -lt 1 ]
        then
                echo "Sync start: $ST_TIME"
                $RSYNC
                if [ $? -ne "0" ]; then
                        echo "Rsync Failed: `date`"
                        FAILED
                else
                        echo "\n\nSync completed: `date`"
                        SUCCESS
                fi
        else
                echo "Another Rsync process is running.Exiting !!!!!!!!!! "
                exit
        fi

#----------------------------------------------------------------------------------------------------------------------------------------------------------------

# /ua1002   ----->  mb-365c-pap01:/ua1002

# Setting the Rsync command-set specifying the Filesystem details and required switches.
RSYNC='rsync -atlrzvuop --progress /ua1002/ root@mb-365c-pap01:/ua1002/'

# Setting this variable to capture the Rsync status
PCOUNT=`ps ax |grep -v grep |grep 'rsync -atlrzvuop --progress /ua1002/ root@mb-365c-pap01:/ua1002/' | wc -l`
ST_TIME=`date`

# Execution starts from here
        if [ $PCOUNT -eq " " ] || [ $PCOUNT -lt 1 ]
        then
                echo "Sync start: $ST_TIME"
                $RSYNC
                if [ $? -ne "0" ]; then
                        echo "Rsync Failed: `date`"
                        FAILED
                else
                        echo "\n\nSync completed: `date`"
                        SUCCESS
                fi
        else
                echo "Another Rsync process is running.Exiting !!!!!!!!!! "
                exit
        fi

#----------------------------------------------------------------------------------------------------------------------------------------------------------------

# /us1001   ----->  mb-365c-pap01:/us1001

# Setting the Rsync command-set specifying the Filesystem details and required switches.
RSYNC='rsync -atlrzvuop --progress /us1001/ root@mb-365c-pap01:/us1001/'

# Setting this variable to capture the Rsync status
PCOUNT=`ps ax |grep -v grep |grep 'rsync -atlrzvuop --progress /us1001/ root@mb-365c-pap01:/us1001/' | wc -l`
ST_TIME=`date`

# Execution starts from here
        if [ $PCOUNT -eq " " ] || [ $PCOUNT -lt 1 ]
        then
                echo "Sync start: $ST_TIME"
                $RSYNC
                if [ $? -ne "0" ]; then
                        echo "Rsync Failed: `date`"
                        FAILED
                else
                        echo "\n\nSync completed: `date`"
                        SUCCESS
                fi
        else
                echo "Another Rsync process is running.Exiting !!!!!!!!!! "
                exit
        fi

Popular Posts

About Me

My photo
I have started this blog to share my work experience and spread some smart solutions on Linux to Internet community. I'm hoping more people will get benefited from this blog. Brief about me: I have 14+ years experience working as System Admin and currently work with VMware.