Posh-SSH module easy access to SSH and SCP from PowerShell

    for powershell there is a Posh-SSH module that implements support for the SSH, SFTP, SCP protocols in PowerShell. It describes how to install, and basic notes on the work. In fact, this is an extract from the English-language article below.

    on a specific event, it was necessary to reset the network port on the switch. The switch has a cisco command line interface. Before using putty from the command line, it was decided to see if there are modules for working on ssh directly from powershell. Searches gave the Posh-SSH module on github .

    The module allows you to:

    • establish SSH and SFTP sessions on loans or using the OpenSSH key
    • connect via SOCKS and HTTP proxies for both types of SSH and SFTP sessions
    • execute commands individually by sending them to SSH
    • upload and download files using SCP and SFTP protocols

    For SSH, authentication by key, login \ password, keyboard input is supported. Various encryption algorithms are supported, proxies are supported.

    Minimum requirements are PowerShell 3.0 and .NET 4.0. Description of the module on the official page .

    Module installation


    The easiest way to install from the admin console is to run the command:

    iex (New-Object Net.WebClient).DownloadString("https://gist.github.com/darkoperator/6152630/raw/c67de4f7cd780ba367cccbc2593f38d18ce6df89/instposhsshdev")
    

    If you have PowerShell 5:

    Find-Module Posh-SSH | Install-Module
    

    You can view the commands in the module as follows:

    Get-Command -Module Posh-SSH
    

    How to work with SSH


    1. First, create an SSH session:

    Import-Module Posh-SSH
    $SSHSession = New-SSHSession -ComputerName 192.168.1.1 -Credential $(Get-Credential) -Verbose

    At the first connection, the module will ask whether to add the remote host to the list of trusted ones. It can be done once the launch of New-SSHSession from the console and press the Y . Subsequently, it will connect without question.

    Trusted Hosts
    Cmdlets are used to view and delete trusted hosts.

    • Get-SSHTrustedHost
    • Get-SSHSession
    • Remove-SSHSession


    2. Create a shell:

    $SSH = $SSHSession | New-SSHShellStream

    That's it, now you can send commands and read the answer:

    # отправляет команду
    $SSH.WriteLine( "enable" )
    # считываем ответ
    $SSH.read()
    

    3. Completion of work:

    $sshSession | Remove-SSHSession
    

    You can view sessions using the Get-SSHSession command .

    Below is an example of work:

    • connect via ssh
    • go to enable mode
    • go to interface configuration mode
    • reset interface

    SSH Switch Example
    $SwitchIP = '10.10.3.2'
    $SwitchPort = 4
    $Cred = Get-Credential admin
    $SSHSession = New-SSHSession -ComputerName $SwitchIP -Credential $Cred -Verbose
    if ($($sshSession.Connected) -eq $true) {
        Write-Host "SSH session opened" -ForegroundColor Green
        Write-Host " "
        Write-Host "     open shell" -ForegroundColor Green
        ### сессия открыта успешно, начинаем сброс порта
        $ssh = $sshSession | New-SSHShellStream
        Start-Sleep -Seconds 1
        # ресетим интерфейс
        $ssh.read()
        Start-Sleep -Seconds 1
        $ssh.WriteLine( "enable" )
        $ssh.read()
        Write-Host "     переходим в привелигированный режим" -ForegroundColor Green
        Start-Sleep -Seconds 1
        $ssh.WriteLine( "password" )
        $ssh.read()
        Write-Host "     вводим пароль" -ForegroundColor Green
        Start-Sleep -Seconds 1
        $ssh.WriteLine( "configure" )
        $ssh.read()
        Write-Host "     переходим в режим конфигурации" -ForegroundColor Green
        Start-Sleep -Seconds 1
        $ssh.WriteLine( "interface gigabitEthernet 1/0/$SwitchPort" )
        $ssh.read()
        Write-Host "     переходим к конфигурации интерфейса    interface gigabitEthernet 1/0/$SwitchPort" -ForegroundColor Green
        Start-Sleep -Seconds 1
        $ssh.WriteLine( "shutdown" )
        $ssh.read()
        Write-Host "     отключаем интерфейс" -ForegroundColor Green
        Start-Sleep -Seconds 3
        $ssh.WriteLine( "no shutdown" )
        $ssh.read()
        Write-Host "     включаем интерфейс" -ForegroundColor Green
        Write-Host "     отработали, завершаемся" -ForegroundColor Green
    }
    else {
        Write-Host "SSH session cannot be established" -ForegroundColor Red
        Write-Host "script terminate" -ForegroundColor Red
        exit
    }
    if ( $($sshSession | Remove-SSHSession) -eq $true) {
        Write-Host "SSH session closed" -ForegroundColor Green
    }
    else{
        Write-Host "SSH session NOT closed" -ForegroundColor Red
        Write-Host "please check manual" -ForegroundColor Red
        Get-SSHSession
    }
    

    As you can see from the example, you can get the console output back and parse if necessary
    the send method 2 - Write and WriteLine, the first prints to the console, the second prints and press Enter, respectively.

    File Transfer Through SCP


    It's still simpler here. I give an example from the official page. File upload:

    Set-SCPFile -LocalFile .\Downloads\VMware-PowerCLI-5.5.0-1671586.exe -RemoteFile "/tmp/powercliinstaller.exe" -ComputerName 192.168.10.3 -Credential (Get-Credential root)

    File Download:

    Get-SCPFile -LocalFile .\Downloads\VMware-PowerCLI.exe -RemoteFile "/tmp/powercliinstaller.exe" -ComputerName 192.168.10.3 -Credential (Get-Credential root)

    » The official page from the creator of the module

    Useful links: one and two .

    Also popular now: