Wednesday, October 6, 2010

Get prod or dev environment by IP address

I have some DMZ with same computer name (...). These computers use one of my schedule script to retrieve some computers informations and put them by ssh on a secure ftp server. As these computers don't have same IP address, I can differentiate computer environnement (Production or Dev) using a list I get before using the same secure ftp server.

So here, script part to get prod or dev environment by IP address (Download it)

You need at least psftp from http://www.chiark.greenend.org.uk/~sgtatham/putty/ (Alternative Download). Put these files in the same directory than you will put GetEnvByIP.ps1 file.



#
# Get Env By IP Address
#
# by F.Richard 2010-10
#

set-psdebug -strict

# Script Directory
$strCurDir = Split-Path -parent $MyInvocation.MyCommand.Path
Set-Location $strCurDir | Out-Null


# Computername
$Computername = Get-Content env:COMPUTERNAME


# get IP file by FTP
# Ip File format
# ip,csv
$ftp_cmdline = "
get ip.csv
quit
"
$ftp_cmdline | out-file -encoding OEM ".\ftp-get.txt"
$cmdline = $strCurDir + "\psftp yourftpserver -l user -pw password -b `"" + $strCurDir + "\ftp-get.txt`""
cmd /c $cmdline


# Get IP/env into Hash
$hashIP = @{ }
$content = import-csv "$strCurDir\ip.csv"
foreach ($line in $content) {
$IPAddress = $line.ip.Trim()
If ($IPAddress.length -gt 0) {
$env = $line.env.Trim()
$hashIP["$IPAddress"] = "$env"
}
}

# Detect IPs and display env
$StringToAdd="unknown"
$NetworkAdapterConfigurations = Get-WMIObject -Class Win32_NetworkAdapterConfiguration -computername $Computername
foreach ($NetworkAdapterConfiguration in $NetworkAdapterConfigurations) {
$IPAddress = $NetworkAdapterConfiguration.IPAddress
If ($hashIP.ContainsKey("$IPAddress")) {
$StringToAdd = $hashIP["$IPAddress"]
}
}
Write-Host "This computer is in $StringToAdd environment"



Ip.csv file should be like this

ip,csv
192.168.1.10,dev
192.168.1.20,prod


Do not forget to change variables yourftpserver user and password by your ftp, your user and your password. And put an ip.csv file on your ftp server.

This script use psftp for secure ftp but if you don't need secure ftp, you can use windows ftp by replacing psftp part by these lines


# get IP file by FTP
# Ip File format
# ip,csv
$ftp_cmdline = "
open yourftpserver
ftpuser
ftppassword
prompt
get ip.csv
quit
"
$ftp_cmdline | out-file -encoding OEM ".\ftp-get.txt"
$cmdline = "ftp -i -s:`"" + $strCurDir + "\ftp-get.txt`""
cmd /c $cmdline

No comments: