PS credential retry - powershell

I have this script
$db = import-csv -Path ".\testdb.csv"
$inputID = Read-Host -Prompt "ID"
$entry = $db -match $inputID
Write-Host "IP:" $entry.IP
$User = "user"
$Password = "pass"
$User2 = "user2"
$Password2 = "pass2"
$Command = "C:\test.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$secpasswd2 = ConvertTo-SecureString $Password2 -AsPlainText -Force
$Credentials2 = New-Object System.Management.Automation.PSCredential($User2, $secpasswd2)
Get-SSHTrustedHost | Remove-SSHTrustedHost
try {
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true
}
catch {
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials2 -AcceptKey:$true
}
Is any chance to try connect with 2 different credentials ; if one fail try to other?
So.. first time try user and password ; second time try user2 and password2
Thank you. :)

Related

Powershell: Using specific credentials to execute a command

Dears,
In my Powershell script, I would like to use a specific credential on a remote computer. This login exists on the remote computer and is local.
Hence, my code looks like this:
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$Vault = New-Object Windows.Security.Credentials.PasswordVault
$RESOURCE = "Resource"
$USERNAME = "MyLogin"
try {
$credentials = $Vault.Retrieve($RESOURCE,$USERNAME)
$pwd = $credentials.Password | ConvertTo-SecureString -Key (1..16)
}
catch {
$pwd = Read-Host "please enter your password:" -AsSecureString
$Encrypted = ConvertFrom-SecureString -SecureString $pwd -Key (1..16)
$credentials = new-object -Type Windows.Security.Credentials.PasswordCredential -ArgumentList $RESOURCE,"REMOTE_COMPUTER\"+$USERNAME,$Encrypted
$Vault.Add($credentials)
}
$cred = New-Object System.Management.Automation.PsCredential($USERNAME,$pwd)
$ComputerMemory = Get-WmiObject -ComputerName "REMOTE_COMPUTER" -Class win32_operatingsystem -ErrorAction Stop -Credential $cred
$Memory = ([math]::round(((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize), 2))
echo $Memory
Problem of course is when executing GetWmiObject, I got an Access denied error...
Is there something wrong with this code?
Thanks in advance for your feedback,
Kind regards,

Try different credentials PS script SSH

I have this script and cannot work correctly .. I try to connect with 2 users ; if one doesn't work try other one.
#1. Try user and pass1 if is not good try #2. user and pass2.
*problem is with winscp users ; I really don't know how to implement 2 try connection
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$db = import-csv -Path "C:\Program Files (x86)\WinSCP\db.csv"
$inputID = Read-Host -Prompt "ID"
$entry = $db | where-Object {$_.HostName -eq $inputID}
if ($inputID -eq $entry.HostName){
"$inputID Ok!"
}
else{
"$inputID nu exista in baza de date!"
$title = 'Title'
$question = 'Doriti sa introduceti un ID nou in Baza de Date?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
$ID = Read-Host -Prompt "Introduceti ID"
$IP = Read-Host -Prompt "Introduceti IP"
$wrapper = New-Object PSObject -Property #{ HostName = $ID; IP = $IP }
Export-Csv -Append -InputObject $wrapper -Path "C:\Program Files (x86)\WinSCP\db.csv" -NoTypeInformation -Force
$dbTrimmer = Get-Content -Path "C:\Program Files (x86)\WinSCP\db.csv"
$dbTrimmer.Replace('","',",").TrimStart('"').TrimEnd('"') | Out-File "C:\Program Files (x86)\WinSCP\db.csv" -Force -Confirm:$false
Exit
}
else{
Write-Host 'No'
Exit
}
}
Write-Host "IP:" $entry.IP
$User = "user"
$Password = "pass"
$Command = "C:\Info.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = "$User"
Password = "$Password"
GiveUpSecurityAndAcceptAnySshHostKey = "true"
}
$session = New-Object WinSCP.Session
$file = "Dev.log", "Info.dat"
$localPath = "E:\Arhive\*"
$remotePath = "/C:/Program Files/Dev.log", "/C:/Program File/Info.dat"
try {
# Connect
$session.Open($sessionOptions)
# Check exists files
foreach ($remotePath in $remotePath)
{
if ($session.FileExists($remotePath))
{
Write-Host "Fisierul $remotePath exista"
# Transfer files
$session.GetFiles($remotePath, $localPath).Check()
}
else
{
Write-Host "Fisierul $remotePath NU exista"
}
}
}
finally {
$session.Dispose()
}
foreach ($file in "E:\loguri\Dev.log", "E:\loguri\Info.dat") {
if (Test-Path $file) {
Compress-Archive $file -DestinationPath "E:\Arhive\$inputID.zip" -Update
Remove-Item $file
}
}
# Stergere fisiere din Arhive mai vechi de 60 minute
$Files = get-childitem 'E:\Arhive' | Where-Object PSIsContainer -eq $false
$LimitTime = (Get-Date).AddMinutes(-60)
$Files | ForEach-Object {
if ($_.CreationTime -lt $LimitTime -and $_.LastWriteTime -lt $LimitTime) {
Remove-Item -Path $_.FullName -Force
Write-Host "Am sters $Files pentru ca sunt mai vechi de $LimitTime !"
}
}
Here is all my script. In this moment all works very well , just I want to add 2 users for auth. If 1 fail try other one.
Any ideea ? Thank you
I couldn't test this myself, but I think I would go about it like below:
$User = "SameUser"
$Password = "Pass1"
$sPassword = "Pass2"
$Command = "C:\Info.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$ssecpasswd = ConvertTo-SecureString $sPassword -AsPlainText -Force
Get-SSHTrustedHost | Remove-SSHTrustedHost
try {
# try the first credentials
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true -Verbose -ErrorAction Stop
}
catch {
# first one failed, try second credentials
$Credentials = New-Object System.Management.Automation.PSCredential($User, $ssecpasswd)
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $sCredentials -AcceptKey:$true -Verbose
}
try {
Invoke-SSHCommand -SessionId $SessionID.SessionId -Command $Command -ErrorAction Stop
}
catch {
throw
}
# create a hashtable with the first password
$options = #{
Protocol = [WinSCP.Protocol]::Sftp
HostName = $entry.IP
UserName = $User
Password = $Password
GiveUpSecurityAndAcceptAnySshHostKey = $true
}
try {
# Set up session options using first password
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
# Set up session options using second password
$options['Password'] = $sPassword
try {
$sessionOptions = New-Object WinSCP.SessionOptions -Property $options
$session = New-Object WinSCP.Session
# Try Connect
$session.Open($sessionOptions)
}
catch {
Write-Error "Could not open WinSCP session: $($_.Exception.Message)"
throw
}
}
try {
# Check if exists files.
# Make sure variables $remotePath and $localPath are defined on top of the script
foreach ($remoteFile in $remotePath) {
if ($session.FileExists($remoteFile)) {
$session.GetFiles($remotePath, $localPath).Check()
}
else {
Write-Warning "File '$remoteFile' not found"
}
}
}
catch {
Write-Error "Could not open WinSCP session: $($_.Exception.Message)"
}
finally {
if ($session) { $session.Dispose() }
}

SSH Check Connection

I would like to check if machines have SSH installed.
So, I have this script:
I want the script to try to connect on machines and make a .txt 'log' like this:
10.10.10.1 - Connection refused (machines not have SSH or is down)
10.10.10.2 - Connection OK
...
$db = Get-Content -Path ".\hosts.txt"
$User = "user"
$Password = "pass"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $db -Credential $Credentials -AcceptKey:$true
In hosts.txt I have hostip for machines
eg:
10.10.10.1
10.10.10.2
10.10.10.3
...
Any ideea ?
$LogFile = ".\LogMachines.txt"
function LogMessage
{
param([string]$Message)
((Get-Date).ToString() + " - " + $Message) >> $LogFile;
}
$db = Get-Content -Path ".\hosts.txt"
$User = "user"
$Password = "pass"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $db -Credential $Credentials -AcceptKey:$true
LogMessage -Message "$db connected - OK";
LogMessage -Message "$db failed to connect - X";

Find the exact matched string from the variable

In the below code, $Result variable has the following information. I need to iterate below each line in $Result variable and get the <APPPOOL NAME> that is, "DefaultAppPool","Classic .NET AppPool" & ".NET v2.0 Classic" as an input to the second Invoke-Command saved in $Result2. Please advise how this can be accomplished.
$Result output:
APPPOOL "DefaultAppPool" (MgdVersion:v4.0,MgdMode:Integrated,state:Started)
APPPOOL "Classic .NET AppPool" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
APPPOOL ".NET v2.0 Classic" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
$Username = '<username>'
$Password = '<Password>'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
$input_file_path = "servers.txt"
$output_path = "result.txt"
foreach ($server in Get-Content $input_file_path) {
$Result = Invoke-Command -ComputerName $server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools
}
$Result | Add-Content $output_path
$Result2 = Invoke-Command -ComputerName #server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools <APPPOOL NAME> /text:processmodel.username
}
}

select multiple switch statements

I have the script below that lets me switch between the different elements and runs the functions in them one by one.
But what I need to do now is make it so I can select multiple ones and have them run and pause between them to verifiy if things were loaded correctly. So that way I don't run into the issue having to re rerun the full script again and redo the same one over.
Can anybody show me how to do this? I am lost as to how to get this completed and working properly.
write-host "Sets up location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (TV30/TV30BP/TV30LM/TV30PV/LT101/XR2/MU11/SAP)"
while ($ElementDistro -notmatch "^(TV30|TV30BP|TV30LM|TV30PV|LT101|XR2|MU11|SAP)$")
{
write-host "you have enterd an error" -ForegroundColor Red
write-host "You must type TV30 or TV30BP or TV30LM or TV30PV or LT101 or XR2 or MU11 or SAP"
write-host "you typed $ElementDistro"
write-host "set location you want to run staging"
$ElementDistro = Read-Host -Prompt "Which Element do you want to run? (TV30/TV30BP/TV30LM/TV30PV/LT101/XR2/MU11/SAP)"
}
switch ($ElementDistro)
{
'TV30'
{
# Do TV30 Stuff
write-host "you have entered TC TV30"
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'TV30BP'
{
# Do TV30BP Stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
# exit-pssession
break
}
'TV30LM'
{
# Do TV30LM stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'TV30PV'
{
# Do TV30PV stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
$source = Select-TC
$destination = 'Desktop'
"Calling Copy-Item with parameters source: '$source', destination: '$destination'."
Copy-Item -Path $source -Destination $destination
exit-pssession
break
}
'LT101'
{
# Do LT101 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'XR2'
{
# Do XR2 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'MU11'
{
# Do TF10 stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
'SAP'
{
# Do SAP stuff
$passwd = convertto-securestring -AsPlainText -Force -String ''
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "",$passwd
$session = enter-pssession -computername '' -credential $cred
break
}
}
break
}
If you got at least V3, you can use Out-GridView with -OutPutMode Multiple as a menu to select multiple items from:
$Menu = 'TV30','TV30BP','TV30LM','TV30PV','LT101','XR2','MU11','SAP','ALL'
$Choices = $Menu | Out-GridView -OutputMode Multiple -Title 'Select Locations you want to run staging, and click OK.'
Switch ($Choices)
{
.....
The quick answer is that Powershell's switch statement accepts an array for input. If you leave out the break statement at the end of each switch case it will execute each case that is a match. Enter your choices as a comma-separated list and put them into an array using the split statement.
Each choice in you $Choices array will be executed. If you put a Pause statement where your break statements are you can pause at the completion of each step.
$Choices = #('TV30','MU11')
switch ($Choices)
{
'TV30' {some code}
'TV30BP' {some code}
'MU11' {some code}
}