Tuesday, October 18, 2016

Powershell Script to retrieve process details from UNIX machines

<#  
.SYNOPSIS  
Script to retrieve process details from UNIX machines. Read the credentials file for the UNIX box which are separated by # symbol as root#password

.FILE NAME

getUNIXStatus.ps1
#>


# Import the SSH libraries which is one time task as below
#iex (New-Object Net.WebClient).DownloadString("https://gist.github.com/darkoperator/6152630/raw/c67de4f7cd780ba367cccbc2593f38d18ce6df89/instposhsshdev")

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$CredPath = $scriptDir + "\securestring.txt"

$list = @()
$flag = ""

$Credential = Get-Content $CredPath
$User = $Credential.Split("#")[0]
$Password = $Credential.Split("#")[1] | ConvertTo-SecureString -AsPlainText -Force

$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $User,$Password

New-SSHSession -ComputerName "machine1" -Credential $creds
$session = Invoke-SSHCommand -Index 0 -Command "/app/oracle/opmn/bin/opmnctl status | egrep 'process0|process1|process2|process3|process4|process5'"

#Since there are 24 values in the session object for loop has been iterated till 24

for($i=0; $i -lt 24)
{
    $Obj=New-Object -TypeName PSObject -Property @{
    Name = $session.Output.Split('|')[$i+1]
    Pid = $session.Output.Split('|')[$i+2]
    Status = $session.Output.Split('|')[$i+3]
    } | Select Name, Pid, Status

    $list += $Obj

    $i = $i+4
}

# Disconnect the UNIX session
Remove-SSHSession -Index 0 -Verbose

$Output = "<HTML><TITLE>UNIX Machine Details</TITLE><BODY><font color =""orange"" face=""Comic Sans MS""><H2 align=left>UNIX Machine Details</H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=black align=center><TD><font color=""white"" face=""Comic Sans MS"">Name</font></TD><TD><font color=""white"" face=""Comic Sans MS"">Process ID</font></TD><TD><font color=""white"" face=""Comic Sans MS"">Status</font></TD></TR>"
            foreach ($listobj in $list)
            {
                if($listobj.Status -eq "Down")
                {
                    $Output += "<TR bgcolor=red>"
                    $flag = "Red"
                }
               else
                { 
                    $Output += "<TR>" 
                } 
            
                $Output += "<TD>$($listobj.Name)</TD><TD>$($listobj.Pid)</TD><TD align=center>$($listobj.Status)</TD></TR>"
            }
$Output += "</Table></BODY></HTML>"

Powershell Script to retrieve URL response

<#  
.SYNOPSIS  
Script to retrieve URL response & relevant details and save it in HTML file. URLs are read from file

.FILE NAME

URL-Response.ps1
#>

clear
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$urlsPath = $scriptDir + "\" + "URLs.txt"

$FileName = (Get-Date).tostring("dd-MM-yyyy-HH-mm-ss")
$file = $scriptDir + "\Logs\" + "URLs-" + $FileName +".htm"

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    
    public class IgnorePolicy : ICertificatePolicy {
        public IgnorePolicy() {}
        public bool CheckValidationResult(
            ServicePoint sPoint, X509Certificate cert,
            WebRequest wRequest, int certProb) {
            return true;
        }
    }
"@

$urls = Get-Content $urlsPath
$list = @()
$count = 1

foreach($url in $urls) {
    
    try{
            [System.Net.ServicePointManager]::CertificatePolicy = new-object IgnorePolicy
            $request = Invoke-WebRequest -Uri $url
            $result = Measure-Command {$request}
            $timetaken = $result.TotalMilliseconds
            $status = $request.StatusCode
            #$reslen = $request.RawContentLength

            $cusObj=New-Object -TypeName PSObject -Property @{
                TT = $timetaken
                status = $status
                #reslen = $reslen
                url = $url
                Time = Get-Date
                count = $count++
                } | Select TT,status,url,Time, count
            
            $list += $cusObj
            
         }
    
    catch {
               $_.Exception
    }
}
            $Outputreport = "<HTML><TITLE>URL Response Report</TITLE><BODY><font color =""blue"" face=""Comic Sans MS""><H2 align=left> URL Response Report </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=black align=center><TD><font color=""white"" face=""Comic Sans MS"">S.No</font></TD><TD><font color=""white"" face=""Comic Sans MS"">URL</font></TD><TD><font color=""white"" face=""Comic Sans MS"">StatusCode</font></TD><TD><font color=""white"" face=""Comic Sans MS"">Time Captured</font></TD><TD><font color=""white"" face=""Comic Sans MS"">TimeTaken(MS)</font></TD></TR>"
            foreach ($obj in $list)
            {
                if($obj.status -ne "200")
                {
                    $Outputreport += "<TR bgcolor=yellow>" 
                }
                else
                { 
                    $Outputreport += "<TR>" 
                } 
            
                $Outputreport += "<TD>$($obj.count)</TD><TD>$($obj.url)</TD><TD align=center>$($obj.status)</TD><TD align=center>$($obj.Time)</TD><TD align=center>$($obj.TT)</TD></TR>"
            }
            $Outputreport += "</Table></BODY></HTML>"
            
            $Outputreport | Out-File $file

Wednesday, October 12, 2016

Powershell Script to Amend ASG values - AWS Cloud

<#  
.SYNOPSIS  
Amend ASG for updating & reverting Values. ASGs will be read through file

.FILE NAME
SetASGtoZero.ps1
#>

clear

Set-ExecutionPolicy Unrestricted
Set-DefaultAWSRegion -Region {Specify the region}
Set-AWSCredentials –AccessKey {Specify the Access Key} –SecretKey {Specify the Secret Key}
Import-Module 'C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1'; Initialize-AWSDefaults

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

$Asg_LCGFilePath = $scriptDir + "\ASG.txt"
$logOrigPath = $scriptDir + "\" + "Log_Orig.txt"
$logFilePath = $scriptDir + "\" + "Log.txt"

try
{
    $AutoScalingGroups = Get-Content $Asg_LCGFilePath

    foreach($AutoScalingGroup in $AutoScalingGroups)
    {
        $AutoScalingGroupDetails = Get-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroup 
        $AutoScalingGroup + "#" + $AutoScalingGroupDetails.MinSize + "#" + $AutoScalingGroupDetails.DesiredCapacity >> $logOrigPath
        Update-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroup -MinSize 0 -DesiredCapacity 0
    }
}

catch 
{
$originalException = $_.Exception 
try
{
"Error: " + $originalException.Message >> $logFilePath
}
catch

"Original Error: " + $originalException.Message >> $logFilePath
"Logging Error:" + $_.Exception.Message >> $logFilePath
}

    Exit 1
}

<#  
.SYNOPSIS  
Amend ASG for updating & reverting Values. ASGs will be read through file

.FILE NAME
RevertASG.ps1
#>

clear

Set-ExecutionPolicy Unrestricted
Set-DefaultAWSRegion -Region {Specify the region}
Set-AWSCredentials –AccessKey {Specify the Access Key} –SecretKey {Specify the Secret Key}
Import-Module 'C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1'; Initialize-AWSDefaults

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

$logOrigPath = $scriptDir + "\" + "Log_Orig.txt"
$logZeroPath = $scriptDir + "\" + "Log_Zero.txt"
$logFilePath = $scriptDir + "\" + "Log.txt"

try
{
    $OriginalASGValues = Get-Content $logOrigPath

    foreach($OriginalASGVal in $OriginalASGValues)
    {
        $AutoScalingGroupName = $OriginalASGVal.Split("#")[0]
        $MinVal = $OriginalASGVal.Split("#")[1]
        $DesVal = $OriginalASGVal.Split("#")[2]
        "Values are:" + $AutoScalingGroupName + " " + $MinVal + " " + $DesVal >> $logZeroPath
        Update-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroupName -MinSize $MinVal -DesiredCapacity $DesVal >> $logZeroPath
    }
}

catch 
{
$originalException = $_.Exception 
try
{
"Error: " + $originalException.Message >> $logFilePath
}
catch

"Original Error: " + $originalException.Message >> $logFilePath
"Logging Error:" + $_.Exception.Message >> $logFilePath
}

    Exit 1
}

Powershell Script to add Notification for all ASGs - AWS Cloud

<#  
.SYNOPSIS  
Script to add Notification for all ASGs

FILE NAME

AddNotifASG.ps1
#>

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$CommonFilePath = $scriptDir + "\AWSCredentials.ps1"
. $CommonFilePath


$Environment = "PROD"

$AutoScalingGroupName=""

try
{
   $AutoScalingGroups = (Get-ASAutoScalingGroup | Where-Object -FilterScript {
                        $_.Tags | Where-Object {
                                ($_.Key -eq "Environment" -and $_.Value -eq $Environment)
                                }             
                            }) 

    foreach($AutoScalingGroup in $AutoScalingGroups)
    {
        $AutoScalingGroupName = $AutoScalingGroup.AutoScalingGroupName
        Write-ASNotificationConfiguration -AutoScalingGroupName $AutoScalingGroupName -NotificationType @("autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_TERMINATE") -TopicARN "{Specify the ARN Value here}"
    }

}

catch 
{
$originalException = $_.Exception 
try
{
"Error: " + $originalException.Message
}
catch

"Original Error: " + $originalException.Message
"Logging Error:" + $_.Exception.Message
}

    Exit 1
}

Powershell Script to Remove Tags for ASG and associated instances - AWS Cloud

<#  
.SYNOPSIS  
Script to Remove Tags for ASG and associated instances by reading the ASG's from file

.FILE NAME
RemoveTags.ps1
#>

clear

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

$Asg_FilePath = $scriptDir + "\ASG.txt"

$AutoScalingGroups = Get-Content $Asg_FilePath

foreach($AutoScalingGroup in $AutoScalingGroups)
{
    $Tag = New-Object Amazon.AutoScaling.Model.Tag
    $Tag.ResourceId = $AutoScalingGroup
    $Tag.ResourceType = "auto-scaling-group"
    $Tag.Key = "{Specify the Tag Key}"
    Remove-ASTag -Tag $Tag -Force
    "Removed Tag for ASG " + $AutoScalingGroup

    $Instances = (Get-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroup).Instances
    foreach ($Instance in $Instances)
    {
        $tag = New-Object Amazon.EC2.Model.Tag
        $tag.Key = "{Specify the Tag Key}"
        Remove-EC2Tag -Resource $Instance.InstanceId -tag $tag -Force
        "Removed Tag for Instance " + $Instance.InstanceId
    }
}

Powershell Script to retrieve Instance Details under AWS Account - AWS Cloud

<#  
.SYNOPSIS  
Script to retrieve Instance Details under AWS Account

This script will also gather last 24hrs Average CPU Value using the function getStats


.FILE NAME

Instance.ps1
#>

clear

Set-ExecutionPolicy Unrestricted
Set-DefaultAWSRegion -Region {Specify the region}
Set-AWSCredentials –AccessKey {Specify the Access Key} –SecretKey {Specify the Secret Key}
Import-Module 'C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1'; Initialize-AWSDefaults

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

try
{
    $Environment = "PROD"
            
    $Insts = ((Get-EC2Instance -Region {Specify the region}).RunningInstance | Where-Object -FilterScript {
                                    $_.Tags | Where-Object {
                                        ($_.Key -eq "Environment" -and $_.Value -eq $Environment )
                                    }
                                })
           
    $Instances = $Insts | Where-Object {$_.State.Name.Value -eq "Running"}
    
    $Ins = @{Expression={$_.InstanceId};Label="Instance ID"}, `
    @{Expression={$_.Tags | ? { $_.key -eq "Name" } | select -expand Value};Label="Instance Name"},
    @{Expression={$_.PrivateIpAddress};Label="Private IP"},
    @{Expression={$_.Tags | ? { $_.key -eq "Environment" } | select -expand Value};Label="Environment"},
    @{Expression={$_.Architecture};Label="Architecture"},
    @{Expression={$_.Tags | ? { $_.key -eq "Component" } | select -expand Value};Label="Component"},
    @{Expression={$_.Platform};Label="Platform"},
    @{Expression={(Get-EC2InstanceStatus -InstanceId $_.InstanceId).AvailabilityZone};Label="AvailZone"},
    @{Expression={getStats($_.InstanceId)};Label="Avg Cpu (last 24hrs)"}
        
    $Instances | Format-Table -AutoSize $Ins
}

catch 
{
$originalException = $_.Exception 
try
{
"Error: " + $originalException.Message
}
catch

"Original Error: " + $originalException.Message 
"Logging Error:" + $_.Exception.Message
}

    Exit 1
}

Function getStats($InstID)
{

    $Stats = Get-CWMetricStatistics -MetricName CPUUtilization -Dimension @{Name = "InstanceId"; Value = $InstID} -StartTime (Get-Date).AddDays(-1) -EndTime (Get-Date) -Namespace "AWS/EC2" -Period 12000 -Statistic Average | Select-Object -ExpandProperty DataPoints
    $aveCpu = $Stats | sort TimeStamp | select -ExpandProperty Average | measure -Average | select -ExpandProperty Average
    
    return $aveCpu
}

Powershell Script to retrieve Instances Status under ELB associated with ASG - AWS Cloud

<#  
.SYNOPSIS  
Script to retrieve Instances and their status under ELB aligned to ASG. Import the credentials file in the same script

.FILE NAME

LBChecks.ps1
#>

clear

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

$CommonFilePath = $scriptDir + "\AWSCredentials.ps1"
. $CommonFilePath

$file = $scriptDir + "\" + "Details-" + (Get-Date).tostring("dd-MM-yyyy-HH-mm-ss") + ".txt"

try
{
    $Environment = "PROD"
    
    $AutoScalingGroups = (Get-ASAutoScalingGroup | Where-Object -FilterScript {
                        $_.Tags | Where-Object {
                                ($_.Key -eq "Environment" -and $_.Value -eq $Environment)
                                }
                            }) 

    foreach($AutoScalingGroup in $AutoScalingGroups)
    {

        $ELBs = $AutoScalingGroup.LoadBalancerNames

        foreach ($elb in $ELBs)
        {
            $LBDetails = Get-ELBLoadBalancer -LoadBalancerName $elb
            foreach($Instance in $LBDetails.Instances)
            {
                $InstanceHealth = Get-ELBInstanceHealth -LoadBalancerName $elb -Instance $Instance
                $InstAvailZ = (Get-EC2InstanceStatus -InstanceId $Instance.InstanceId).AvailabilityZone
                
                if($InstanceHealth.State -eq "OutOfService")
                    { 
                     $Message = $AutoScalingGroup.AutoScalingGroupName + " || " + $Instance.InstanceId + " || " + $elb + " || " + $InstAvailZ + " || state is " + $InstanceHealth.State
                     Write-Host $Message -ForegroundColor Red
                    }
                else 
                    {
                    $Message = $AutoScalingGroup.AutoScalingGroupName + " || " + $Instance.InstanceId + " || " + $elb + " || " + $InstAvailZ + " || state is " + $InstanceHealth.State
                    Write-Host $Message -ForegroundColor Green
                    $Message >> $file
                    }
            }
        }

    }
}

catch 
{
$originalException = $_.Exception 
try
{
"Error: " + $originalException.Message
}
catch

"Original Error: " + $originalException.Message 
"Logging Error:" + $_.Exception.Message
}

    Exit 1
}

Powershell Script to RDP

<#  
.SYNOPSIS  
Script to connect multiple RDP sessions with single username/password

.FILE NAME

Connect.ps1
#>

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$CredPath = $scriptDir + "\securestring.txt"
$IPPath = $scriptDir + "\IP.txt"

$ComputerName = Get-Content $IPPath
#"IP's are" + $ComputerName

$Credential = Get-Content $CredPath
#"Credentials given are" + $Credential

try
{  

      $ComputerName | ForEach-Object {
      $User = $Credential.Split("#")[0]
      $Password = $Credential.Split("#")[1]
     
      cmdkey.exe /generic:TERMSRV/$_ /user:$User /pass:$Password
      mstsc.exe /v:$_
      #cmdkey.exe /delete:$_
    }

}

catch
{
$originalException = $_.Exception
    "Error: " + $originalException.Message
Exit 1
}