Hya!! After a long gap, I am here again...
This time I have come up with an utility that takes the details of your inventory.
Problem Statement: I have a lot of servers on my network and my manager comes and tell me, "Can you get me details like the total RAM, HDD, Manufacturer, Serial Number and ServerName of all these servers?? I need to report this to Infrastructure team! Please get this in 2 hours time!!" Sounds laborious..Isn't it??
Here's the script:
"IP`tHardDisk`tRAM`tSystemName`tManufacturer`tSerialNumber" out-file C:\Results.csv -append
Function HDDInfo { param($ip) $alldrives = get-wmiobject win32_logicaldisk -filter "DriveType=3" -computername $ip $HDD = 0 foreach ($i in $alldrives) { $HDD = $HDD + ($i.size)/(1gb) } $HDD }
Function RAMInfo { param($ip) $ram = get-wmiobject win32_ComputerSystem -computername $ip $RAM = ($ram.TotalPhysicalMemory)/(1gb) $RAM }
Function SystemName { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.name }
Function Manufacturer { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.manufacturer } Function SerialNumber { param($ip) $bios = get-wmiobject win32_bios -computer $ip $bios.SerialNumber }
$address = "10.2.2."
2..254 foreach-object { $ip = $address + $_
$ping = get-wmiobject win32_pingstatus -filter "Address = '$ip'" select-object statuscode
if($ping.statuscode -eq 0) { $HDD = HDDInfo $ip sleep 1 $RAM = RAMInfo $ip sleep 1 $SystemName = SystemName $ip $Manufacturer = Manufacturer $ip $SerialNumber = SerialNumber $ip
"$ip`t$HDD`t$RAM`t$SystemName`t$Manufacturer`t$SerialNumber" out-file C:\Results.csv -append } else { "$ip is Offline or Not Reachable.." out-file C:\Results.csv -append }
}
In this script, I assume all your systems on the network are in the IP range of 10.2.2.x and I am collecting the details of IPs: 10.2.2.2 - 10.2.2.254
Run the script, wait for 4-5 minutes and get the results in Results.csv file. :-)
Hope this helps!!
Lookout for scripting experiences, automated tools and frameworks that I develop....
Wednesday, April 1, 2009
Friday, February 13, 2009
PowerShell: OS Statistics for a Remote Host
Here's a small PowerShell Script that would enable you to get the OS Statistics for a Host...
----------OS-Statistics.ps1------------------
Function Main {
# Load the Winforms assembly
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
# Create the form
$form = New-Object Windows.Forms.Form
#Set the dialog title
$form.text = "OS Statistics"

# Create the label control and set text, size and location
$label = New-Object Windows.Forms.Label
$label.Location = New-Object Drawing.Point 50,50
$label.Size = New-Object Drawing.Point 200,15
$label.text = "Enter Hostname"
$combo = new-object System.Windows.Forms.ComboBox
$combo.Location = new-object System.Drawing.Size(50,80)
$combo.Size = new-object System.Drawing.Size(200,25)
$combo.Items.Add("ComputerName / IP")
$combo.Items.Add("192.168.219.")
$combo.Items.Add("127.0.0.1")
# Create Button and set text and location
$button = New-Object Windows.Forms.Button
$button.text = "Get OS Statistics"
$button.Location = New-Object Drawing.Point 50,130
$button.Size = New-Object Drawing.Point 200,25
$button3 = New-Object Windows.Forms.Button
$button3.text = "Quit...."
$button3.Location = New-Object Drawing.Point 50,180
$button3.Size = New-Object Drawing.Point 200,25
# Set up event handler to extarct text from TextBox and display it on the Label.
$button.add_click({ NewForm $combo.text })
$button3.add_click({ $form.dispose() })
# Add the controls to the Form
$form.controls.add($button)
$form.controls.add($button3)
$form.controls.add($label)
$form.controls.add($combo)
# Display the dialog
$form.ShowDialog()
}
Function NewForm
{
Param ($ip)
$ALive=get-wmiobject win32_pingstatus -Filter "Address='$ip'" Select-Object statuscode
if($ALive.statuscode -ne 0)
{
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
$form1 = New-Object Windows.Forms.Form
$form1.height = 180
$label1 = New-Object Windows.Forms.Label
$label1.Location = New-Object Drawing.Point 50,10
$label1.Size = New-Object Drawing.Point 200,50
$label1.text = "Sorry!! The Host is Unreachable `n`n Check if" + $ip + " is Online..."
$button2 = New-Object Windows.Forms.Button
$button2.text = "Click to Get Back"
$button2.Location = New-Object Drawing.Point 50,80
$button2.Size = New-Object Drawing.Point 200,25
$button2.add_click({
$form1.dispose()
})
$form1.controls.add($button2)
$form1.controls.add($label1)
$form1.showdialog()
}

else{
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
$form1 = New-Object Windows.Forms.Form
$form1.height = 600
$form1.width = 300
$label1 = New-Object Windows.Forms.Label
$label1.Location = New-Object Drawing.Point 50,10
$label1.Size = New-Object Drawing.Point 200,600
$perf= get-wmiobject Win32_PerfFormattedData_PerfOS_System -computer $ip
$uptime=$perf.SystemUpTime/3600
$freedisk = get-wmiobject win32_logicaldisk -filter "DriveType=3" -computer $ip foreach-object {"`n{0} {1}" -f $_.DeviceID,($_.freespace/1gb)}
$result = "`n--------------------------------------------`n" + "OS STATISTICS :: " + $ip + "`n--------------------------------------------`n`n" + "Processes:`t" + $perf.Processes + "`n`nThreads:`t" + $perf.Threads + "`n`nSystem UpTime In hours:`t" + $uptime + "`n`nAlignment Fixups/sec:`t" + $perf.AlignmentFixupsPersec + "`n`nContext Switches/sec:`t" + $perf.ContextSwitchesPersec + "`n`nException Dispatches/sec:`t" + $perf.ExceptionDispatchesPersec + "`n`nFile Control Bytes/sec:`t" + $perf.FileControlBytesPersec + "`n`nFile Control Operations/sec:`t" + $perf.FileControlOperationsPersec + "`n`nFile Data OperationsPersec:`t" + $perf.FileDataOperationsPersec+ "`n`nFile Read Bytes/sec:`t" + $perf.FileReadBytesPersec + "`n`nFile Read Operations/sec:`t" + $perf.FileReadOperationsPersec + "`n`nFile Write Bytes/sec:`t"+ $perf.FileWriteBytesPersec +"`n`nFile Write Operations/sec:`t" + $perf.FileWriteOperationsPersec + "`n`nSystem Calls/sec:`t"+ $perf.SystemCallsPersec + "`n`nFree Disk Space in GB:`n" + $freedisk
$label1.text = "$result"
$button1 = New-Object Windows.Forms.Button
$button1.text = "Click to Get Back"
$button1.Location = New-Object Drawing.Point 50,520
$button1.Size = New-Object Drawing.Point 200,25
$button1.add_click({
$form1.dispose()
})
$form1.controls.add($button1)
$form1.controls.add($label1)
$form1.showdialog()
}
}
Main
----------OS-Statistics.ps1------------------
Function Main {
# Load the Winforms assembly
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
# Create the form
$form = New-Object Windows.Forms.Form
#Set the dialog title
$form.text = "OS Statistics"
# Create the label control and set text, size and location
$label = New-Object Windows.Forms.Label
$label.Location = New-Object Drawing.Point 50,50
$label.Size = New-Object Drawing.Point 200,15
$label.text = "Enter Hostname"
$combo = new-object System.Windows.Forms.ComboBox
$combo.Location = new-object System.Drawing.Size(50,80)
$combo.Size = new-object System.Drawing.Size(200,25)
$combo.Items.Add("ComputerName / IP")
$combo.Items.Add("192.168.219.")
$combo.Items.Add("127.0.0.1")
# Create Button and set text and location
$button = New-Object Windows.Forms.Button
$button.text = "Get OS Statistics"
$button.Location = New-Object Drawing.Point 50,130
$button.Size = New-Object Drawing.Point 200,25
$button3 = New-Object Windows.Forms.Button
$button3.text = "Quit...."
$button3.Location = New-Object Drawing.Point 50,180
$button3.Size = New-Object Drawing.Point 200,25
# Set up event handler to extarct text from TextBox and display it on the Label.
$button.add_click({ NewForm $combo.text })
$button3.add_click({ $form.dispose() })
# Add the controls to the Form
$form.controls.add($button)
$form.controls.add($button3)
$form.controls.add($label)
$form.controls.add($combo)
# Display the dialog
$form.ShowDialog()
}
Function NewForm
{
Param ($ip)
$ALive=get-wmiobject win32_pingstatus -Filter "Address='$ip'" Select-Object statuscode
if($ALive.statuscode -ne 0)
{
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
$form1 = New-Object Windows.Forms.Form
$form1.height = 180
$label1 = New-Object Windows.Forms.Label
$label1.Location = New-Object Drawing.Point 50,10
$label1.Size = New-Object Drawing.Point 200,50
$label1.text = "Sorry!! The Host is Unreachable `n`n Check if" + $ip + " is Online..."
$button2 = New-Object Windows.Forms.Button
$button2.text = "Click to Get Back"
$button2.Location = New-Object Drawing.Point 50,80
$button2.Size = New-Object Drawing.Point 200,25
$button2.add_click({
$form1.dispose()
})
$form1.controls.add($button2)
$form1.controls.add($label1)
$form1.showdialog()
}
else{
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
$form1 = New-Object Windows.Forms.Form
$form1.height = 600
$form1.width = 300
$label1 = New-Object Windows.Forms.Label
$label1.Location = New-Object Drawing.Point 50,10
$label1.Size = New-Object Drawing.Point 200,600
$perf= get-wmiobject Win32_PerfFormattedData_PerfOS_System -computer $ip
$uptime=$perf.SystemUpTime/3600
$freedisk = get-wmiobject win32_logicaldisk -filter "DriveType=3" -computer $ip foreach-object {"`n{0} {1}" -f $_.DeviceID,($_.freespace/1gb)}
$result = "`n--------------------------------------------`n" + "OS STATISTICS :: " + $ip + "`n--------------------------------------------`n`n" + "Processes:`t" + $perf.Processes + "`n`nThreads:`t" + $perf.Threads + "`n`nSystem UpTime In hours:`t" + $uptime + "`n`nAlignment Fixups/sec:`t" + $perf.AlignmentFixupsPersec + "`n`nContext Switches/sec:`t" + $perf.ContextSwitchesPersec + "`n`nException Dispatches/sec:`t" + $perf.ExceptionDispatchesPersec + "`n`nFile Control Bytes/sec:`t" + $perf.FileControlBytesPersec + "`n`nFile Control Operations/sec:`t" + $perf.FileControlOperationsPersec + "`n`nFile Data OperationsPersec:`t" + $perf.FileDataOperationsPersec+ "`n`nFile Read Bytes/sec:`t" + $perf.FileReadBytesPersec + "`n`nFile Read Operations/sec:`t" + $perf.FileReadOperationsPersec + "`n`nFile Write Bytes/sec:`t"+ $perf.FileWriteBytesPersec +"`n`nFile Write Operations/sec:`t" + $perf.FileWriteOperationsPersec + "`n`nSystem Calls/sec:`t"+ $perf.SystemCallsPersec + "`n`nFree Disk Space in GB:`n" + $freedisk
$label1.text = "$result"
$button1 = New-Object Windows.Forms.Button
$button1.text = "Click to Get Back"
$button1.Location = New-Object Drawing.Point 50,520
$button1.Size = New-Object Drawing.Point 200,25
$button1.add_click({
$form1.dispose()
})
$form1.controls.add($button1)
$form1.controls.add($label1)
$form1.showdialog()
}
}
Main
Monday, February 9, 2009
PowerShell<->Perl: Reading UNICODE files
Problem Statement:
Recently, I faced a tricky situation at work. I had a CSV file generated out of a PowerShell script. I was trying to read the CSV file and generate a graph using Perl TK module. To my surprise, no value from the CSV file got plotted on the graph! Why would this happen?
Reason:
After some tussle, I found that, this was because PowerShell generated the CSV file in a UNICODE format. PERL opens the Unicode file but can’t recognize the content. This is because “Unicode format is not a character encoding”. Hence the issue!
Resolution:
In such cases, one needs to open the Unicode files using any other Perl supported encoding format. Say, we open the file as:
Open (FH, “<:utf-8”, “filepath”);
OR
Open (FH, “<:encoding(utf-8)”, “filepath”);
Thus, Unicode text files are read exactly the same way that other files are read: by specifying a text encoding.
Recently, I faced a tricky situation at work. I had a CSV file generated out of a PowerShell script. I was trying to read the CSV file and generate a graph using Perl TK module. To my surprise, no value from the CSV file got plotted on the graph! Why would this happen?
Reason:
After some tussle, I found that, this was because PowerShell generated the CSV file in a UNICODE format. PERL opens the Unicode file but can’t recognize the content. This is because “Unicode format is not a character encoding”. Hence the issue!
Resolution:
In such cases, one needs to open the Unicode files using any other Perl supported encoding format. Say, we open the file as:
Open (FH, “<:utf-8”, “filepath”);
OR
Open (FH, “<:encoding(utf-8)”, “filepath”);
Thus, Unicode text files are read exactly the same way that other files are read: by specifying a text encoding.
Wednesday, February 4, 2009
PowerShell: Ensure Successful Build Installation
Here’s one problem statement. Let’s say, you have an application installed on multiple systems i.e.; more than 1 system. And you need to know, the files that get installed on these systems once you have installed the application. To top it, the application gets installed on either C: or D: How do you do this? In PowerShell it’s easy.
Code:
Disclaimer: I’m not responsible for any inadvertent consequences you face after running this script.
Below, ‘test’ is the folder where the application gets installed.
FileName: Files-AfterInstall.ps1
foreach ($computer in $args)
{
"-----------------" | out-file BuildInstalled.txt -append
"$computer" | out-file BuildInstalled.txt -append
"-----------------" | out-file BuildInstalled.txt -append
if ((Test-Path -path \\$computer\c$\test) -ne $True)
{}
else
{
get-childitem -recurse \\$computer\c$\test -include *.* | foreach-object {$_.FullName} | out-file BuildInstalled.txt -append
}
if ((Test-Path -path \\$computer\d$\test) -ne $True)
{}
else
{
get-childitem -recurse \\$computer\d$\test -include *.* | foreach-object {$_.FullName} | out-file BuildInstalled.txt -append
}
}
Run as: .\Files-AfterInstall.ps1 system1 system2 (system1, system2 ... system n are the systems where build is installed)
Output:
As output, you would receive a file named BuildInstalled.txt which gets created where the script is running. This file would contain the full path of the files that get installed.
Code:
Disclaimer: I’m not responsible for any inadvertent consequences you face after running this script.
Below, ‘test’ is the folder where the application gets installed.
FileName: Files-AfterInstall.ps1
foreach ($computer in $args)
{
"-----------------" | out-file BuildInstalled.txt -append
"$computer" | out-file BuildInstalled.txt -append
"-----------------" | out-file BuildInstalled.txt -append
if ((Test-Path -path \\$computer\c$\test) -ne $True)
{}
else
{
get-childitem -recurse \\$computer\c$\test -include *.* | foreach-object {$_.FullName} | out-file BuildInstalled.txt -append
}
if ((Test-Path -path \\$computer\d$\test) -ne $True)
{}
else
{
get-childitem -recurse \\$computer\d$\test -include *.* | foreach-object {$_.FullName} | out-file BuildInstalled.txt -append
}
}
Run as: .\Files-AfterInstall.ps1 system1 system2 (system1, system2 ... system n are the systems where build is installed)
Output:
As output, you would receive a file named BuildInstalled.txt which gets created where the script is running. This file would contain the full path of the files that get installed.
Monday, February 2, 2009
PowerShell: GetFileVersion Information as Build Verification Test
As a Dev or QA, we often are worried about the FileVersion information being present on the binaries that we develop and that are shipped to customers. Here’s a small PowerShell script that would help in finding whether we have the fileversion data on all the binaries or not (Currently it checks for .exe and .dll files). Those who know a bit of programming would definitely be able to customize the script as per their requirement.
Please run this carefully. I’m not responsible for any inadvertent consequences.
$files = get-childitem $args -recurse -include *.dll,*.exe
if($files -eq $null)
{
Write-Host "No Exe or dll files present in the folder";
}
else
{
foreach ($i in $files)
{
$ver = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($i).FileVersion
if($ver -eq $null)
{
$i.FullName Out-File NoVersion.txt -append
}
else
{
"{0}`t{1}"-f $i.FullName, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($i).FileVersion out-file Version.xls -append
}
}
}
Run as:
If the above code is copied in a file named: Build-FileVersion-Info.ps1
.\ Build-FileVersion-Info.ps1 FolderName FolderName - is the build folder
Output:
1. We have a file called Version.xls as output that would give the filepaths and fileversion of all the binaries that have fileversion information.
2. Output is also a Noversion.txt file that would give the filepaths of the files that have no fileversion.
3. Output can also be No Exe or dll files present in the folder, which should be self explanatory.
Hope this was useful!!
Please run this carefully. I’m not responsible for any inadvertent consequences.
$files = get-childitem $args -recurse -include *.dll,*.exe
if($files -eq $null)
{
Write-Host "No Exe or dll files present in the folder";
}
else
{
foreach ($i in $files)
{
$ver = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($i).FileVersion
if($ver -eq $null)
{
$i.FullName Out-File NoVersion.txt -append
}
else
{
"{0}`t{1}"-f $i.FullName, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($i).FileVersion out-file Version.xls -append
}
}
}
Run as:
If the above code is copied in a file named: Build-FileVersion-Info.ps1
.\ Build-FileVersion-Info.ps1 FolderName FolderName - is the build folder
Output:
1. We have a file called Version.xls as output that would give the filepaths and fileversion of all the binaries that have fileversion information.
2. Output is also a Noversion.txt file that would give the filepaths of the files that have no fileversion.
3. Output can also be No Exe or dll files present in the folder, which should be self explanatory.
Hope this was useful!!
Monday, January 19, 2009
PowerShell: Issues with GetEventLog on Windows XP
Enough of PERL for the time being......
Something in PowerShell now!
** Before starting, I am not responsible for the ramifications you face after running the below mentioned scripts...So be contemplative before trying these out!! **
Of late I have been working on Windows PowerShell and here’s one of my observations on Windows XP OS. – assuming that you have a XP system with PowerShell for XP running on it.
Following is the command that one would use in PowerShell for getting all the Event Logs of a remote system on the network.
$logs = [System.Diagnostics.EventLog]::GetEventLogs('HostName or IP')
Now, if you key in the command:
$logs
The output that you get would be something like this:
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
512 7 OverwriteOlder 2,130 Application
512 7 OverwriteOlder 0 Internet Explorer
16,384 0 OverwriteAsNeeded 0 Microsoft Office Diagnostics
16,384 0 OverwriteAsNeeded 2,960 Microsoft Office Sessions
512 7 OverwriteOlder 0 Security
512 7 OverwriteOlder 2,337 System
15,360 0 OverwriteAsNeeded 40 Windows PowerShell
The interesting thing here is: What happens if the hostname in the first command is “localhost”?
Well in Win2k3 – STD/ENT and x86/x64 versions of OS, this would work fine giving you the correct output. But if the same command is run on the XP machine, that is, if the following is run on variants of XP OS, you would encounter an error.
------------------------------------------------------------------------------------------------
$logs = [System.Diagnostics.EventLog]::GetEventLogs('localhost')
Exception calling "GetEventLogs" with "1" argument(s): "The network path was no
t found.
"
At line:1 char:52
+ $logs = [System.Diagnostics.EventLog]::GetEventLogs( <<<< 'localhost')
----------------------------------------------------------------------------------------------
Looks like there’s an issue with ‘localhost’ on XP.
Solution:
There’s a way to get the event log of local system while running on Windows XP. Here’s what would work: $logs = [System.Diagnostics.EventLog]::GetEventLogs('127.0.0.1'). so instead of localhost, you could run the same with 127.0.0.1. Simple! But, a bit less obvious. Definitely, giving the ‘ComputerName’ or ‘IP’ itself would work.
Something in PowerShell now!
** Before starting, I am not responsible for the ramifications you face after running the below mentioned scripts...So be contemplative before trying these out!! **
Of late I have been working on Windows PowerShell and here’s one of my observations on Windows XP OS. – assuming that you have a XP system with PowerShell for XP running on it.
Following is the command that one would use in PowerShell for getting all the Event Logs of a remote system on the network.
$logs = [System.Diagnostics.EventLog]::GetEventLogs('HostName or IP')
Now, if you key in the command:
$logs
The output that you get would be something like this:
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
512 7 OverwriteOlder 2,130 Application
512 7 OverwriteOlder 0 Internet Explorer
16,384 0 OverwriteAsNeeded 0 Microsoft Office Diagnostics
16,384 0 OverwriteAsNeeded 2,960 Microsoft Office Sessions
512 7 OverwriteOlder 0 Security
512 7 OverwriteOlder 2,337 System
15,360 0 OverwriteAsNeeded 40 Windows PowerShell
The interesting thing here is: What happens if the hostname in the first command is “localhost”?
Well in Win2k3 – STD/ENT and x86/x64 versions of OS, this would work fine giving you the correct output. But if the same command is run on the XP machine, that is, if the following is run on variants of XP OS, you would encounter an error.
------------------------------------------------------------------------------------------------
$logs = [System.Diagnostics.EventLog]::GetEventLogs('localhost')
Exception calling "GetEventLogs" with "1" argument(s): "The network path was no
t found.
"
At line:1 char:52
+ $logs = [System.Diagnostics.EventLog]::GetEventLogs( <<<< 'localhost')
----------------------------------------------------------------------------------------------
Looks like there’s an issue with ‘localhost’ on XP.
Solution:
There’s a way to get the event log of local system while running on Windows XP. Here’s what would work: $logs = [System.Diagnostics.EventLog]::GetEventLogs('127.0.0.1'). so instead of localhost, you could run the same with 127.0.0.1. Simple! But, a bit less obvious. Definitely, giving the ‘ComputerName’ or ‘IP’ itself would work.
Monday, January 5, 2009
PERL: Using return type of System(“ping…”)
** Before starting, I am not responsible for the ramifications you face after running the below mentioned scripts...So be contemplative before trying these out!! **
Problem Statement:
I had taken up an initiative of scripting an application that required me to ping a certain host that is keyed in by the user and if the host was PING able (that is if I could get a reply to my ICMP request), I had to start some tests on the same host.
Approach #1:
As you would know, after a PING command we have two kinds of outputs:
a. Reply from: bytes=32 time<1ms TTL=128 – PING successful, host reachable
b. Request timed out. – Unreachable host, PING unsuccessful
So my plan was to ping the host in the script and redirect the output of the ping request on to a file. If the redirected file contents happen to be one of these, that is either it matched “Reply from” or it matched “Request timed out”, then the host is PING able or not. Looks easy! But while implementing this logic, you need to open up a file (containing the redirected output), search for contents, match the lines with certain keywords (Reply from or Request timed out) and then decide further. It works, but at the same time it’s painful! I bet you would agree. So I thought of looking out for other options.
Approach #2:
Here’s what struck to me. How about using the return-type of PING? Actually, if you browse through some websites, you would understand that there are 3 return-types of PING.
a. 0 for successful ping
b. 1 if there is any fault in the way the ping request was sent i.e., corrupted packets
c. 2 for unreachable host
Actually, when I devised the trick that I am going to reveal now, I wasn’t thinking about these 3 return types. I simply tried this code:
Code:
use strict;
my $ping = system "ping hostname"; #replace hostname with your IP or Computer name
if(!$ping)
{
print "PING returned: $ping...Host Reachable!!";
}
else
{
print "PING returned: $ping...Host Unreachable!!";
}
#Line 3: if the host is reachable $ping has value of “0”. So using “!$ping”
Execution of the script:
When I ran this code snippet on WinXP and Win2k3 servers, I got the following results:
1. For Reachable IPs: PING returned: 0...Host Reachable!!
2. For Unreachable IPs: PING returned: 256...Host Unreachable!!
You would have realized that, if the host is contactable, the variable $ping contains a value 0 and if not then it stores value of 256. This is the trick secret!!
Approach #3:
This approach is the easiest one and an orthodox one. But you don’t learn anything here. Try using Net::Ping module available in PERL to check if the host is ping able. But again it involves 2 lines of code to understand if the host is reachable unlike 2nd approach!
Code:
$p = Net::Ping->new();
print "$host is alive.\n" if $p->ping($host);
Epilogue:
Out of the 3 approaches, I would go in for the second one; of course as I found it. But I am unsure at this point of time that, whether the return type was of PING or of System function? Anyhow, this consistently works in PERL code run on Windows platform that I mentioned. Let me know your thoughts!!
Problem Statement:
I had taken up an initiative of scripting an application that required me to ping a certain host that is keyed in by the user and if the host was PING able (that is if I could get a reply to my ICMP request), I had to start some tests on the same host.
Approach #1:
As you would know, after a PING command we have two kinds of outputs:
a. Reply from
b. Request timed out. – Unreachable host, PING unsuccessful
So my plan was to ping the host in the script and redirect the output of the ping request on to a file. If the redirected file contents happen to be one of these, that is either it matched “Reply from” or it matched “Request timed out”, then the host is PING able or not. Looks easy! But while implementing this logic, you need to open up a file (containing the redirected output), search for contents, match the lines with certain keywords (Reply from or Request timed out) and then decide further. It works, but at the same time it’s painful! I bet you would agree. So I thought of looking out for other options.
Approach #2:
Here’s what struck to me. How about using the return-type of PING? Actually, if you browse through some websites, you would understand that there are 3 return-types of PING.
a. 0 for successful ping
b. 1 if there is any fault in the way the ping request was sent i.e., corrupted packets
c. 2 for unreachable host
Actually, when I devised the trick that I am going to reveal now, I wasn’t thinking about these 3 return types. I simply tried this code:
Code:
use strict;
my $ping = system "ping hostname"; #replace hostname with your IP or Computer name
if(!$ping)
{
print "PING returned: $ping...Host Reachable!!";
}
else
{
print "PING returned: $ping...Host Unreachable!!";
}
#Line 3: if the host is reachable $ping has value of “0”. So using “!$ping”
Execution of the script:
When I ran this code snippet on WinXP and Win2k3 servers, I got the following results:
1. For Reachable IPs: PING returned: 0...Host Reachable!!
2. For Unreachable IPs: PING returned: 256...Host Unreachable!!
You would have realized that, if the host is contactable, the variable $ping contains a value 0 and if not then it stores value of 256. This is the trick secret!!
Approach #3:
This approach is the easiest one and an orthodox one. But you don’t learn anything here. Try using Net::Ping module available in PERL to check if the host is ping able. But again it involves 2 lines of code to understand if the host is reachable unlike 2nd approach!
Code:
$p = Net::Ping->new();
print "$host is alive.\n" if $p->ping($host);
Epilogue:
Out of the 3 approaches, I would go in for the second one; of course as I found it. But I am unsure at this point of time that, whether the return type was of PING or of System function? Anyhow, this consistently works in PERL code run on Windows platform that I mentioned. Let me know your thoughts!!
Subscribe to:
Posts (Atom)