Search code examples
powershellsshcredentials

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


Solution

  • 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() }
    }