162

Posh-SSH: Open Source SSH PowerShell Module

What

Posh-SSH is a PowerShell 3.0 or newer module for automating tasks against system using the SSH protocol. The module supports only a subset of the capabilities that the different SSH RFCs  http://en.wikipedia.org/wiki/Secure_Shell define but it allows for:

  • Establish SSH and SFTP sessions using credentials or OpenSSH keys.
  • Connecting through SOCKS and HTTP proxies for both SSH and SFTP sessions.
  • Execution of commands in a remote host using SSH Exec command.
  • Uploading and downloading of files using SCP and SFTP.

From the SSH standards it supports the following:

  • Supports DIFFIE-HELLMAN-GROUP-EXCHANGE-SHA256, DIFFIE-HELLMAN-GROUP-EXCHANGE-SHA1, DIFFIE-HELLMAN-GROUP14-SHA1 and DIFFIE-HELLMAN-GROUP1-SHA1 key exchange methods.
  • Supports 3DES-cbc, AES128-CBC, AES192-CBC, AES256-CBC, AES128-CTR, AES192-CTR, AES256-CTR, BlowFish-CBC, CAST128-CBC, ARCFour and TwoFish encryptions.
  • Supports HMAC-MD5, HMAC-SHA1, HMAC-RIPEMD160, HMAC-SHA2-256, HMAC-SHA2-256-96, HMAC-MD5-96 and HMAC-SHA1-96 hashing algorithms.
  • Supports public key, password, and keyboard-interactive authentication methods
  • Supports RSA and DSA private key
  • Supports DES-EDE3-CBC, DES-EDE3-CFB, DES-CBC, AES-128-CBC, AES-192-CBC and AES-256-CBC algorithms for private key encryption
  • Supports SOCKS4, SOCKS5 and HTTP proxy

Why

I wrote the Posh-SSH module for automating testing of code I wrote in Ruby, Python and other languages in a lab environments where the code runs in a variety of systems than ranged from BSD Linux, OS X and Windows systems where I needed to only execute a series of commands and get the output. I knew I could do this with Python- or Ruby-based great SSH libraries but I took it as a challenge to do it in PowerShell. I found the SSHT.NET library in CodePlex http://sshnet.codeplex.com/ and just started implementing the code in PowerShell. Some of the tasks required the interaction with .NET events and I decided to manage those in C# since examples where already present. It was an interesting experience in my journey of learning how to write a PowerShell module in C#. Posh-SSH was born out of my own technical needs and the opportunity to learn new things.

Install

The module is hosted in GitHub at https://github.com/darkoperator/Posh-SSH; all source code for the cmdlets and for the module is available there and it is licensed under the BSD 3-Clause License. The module requires PowerShell 3.0 and .NET Framework 4.0. The quickest way to install the module is by running:

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

This will download the latest version of Posh-SSH and install it in the user’s profile. Once it finishes downloading and copying the module to the right place, it will list the commands available:

1

Connecting

The way the module works is by establishing sessions to each of the hosts we want to run against. By allowing multiple sessions at once it allows me to control and automate tasks against more than one hosts and not have to re-login to each one. The command to create a new session is New-SSHSession

PS C:\> help New-SSHSession

NAME
    New-SSHSession

SYNOPSIS
    Creates an SSH Session against a SSH Server

SYNTAX
    New-SSHSession [-ComputerName] <String[]> [-Credential] <PSCredential> [-Port <Int32>] [-ProxyServer <String>] [-ProxyPort <Int32>] [-ProxyCredential <PSCredential>] [-ProxyType <String>]
    [-ConnectionTimeOut <Int32>] [-KeepAliveInterval <Int32>] [-AcceptKey [<Boolean>]] [-PipelineVariable <String>] [<CommonParameters>]

    New-SSHSession [-ComputerName] <String[]> [-Credential] <PSCredential> [-Port <Int32>] [-ProxyServer <String>] [-ProxyPort <Int32>] [-ProxyCredential <PSCredential>] [-ProxyType <String>]
    [-KeyFile <String>] [-ConnectionTimeOut <Int32>] [-KeepAliveInterval <Int32>] [-AcceptKey [<Boolean>]] [-PipelineVariable <String>] [<CommonParameters>]

DESCRIPTION
    Creates an SSH Session against a remote server. The command supports creating connection thru a Proxy and allows for authentication to the server using username and password. If a key file is
    specified the command will use the password in the credentials parameter as the paraphrase of the key.

RELATED LINKS

REMARKS
    To see the examples, type: "get-help New-SSHSession -examples".
    For more information, type: "get-help New-SSHSession -detailed".
    For technical information, type: "get-help New-SSHSession -full".

When we establish a new session for the first time it will check SSH server certificate fingerprint and IP address combination to those saved in HKEY_CURRENT_USER\Software\PoshSSH registry key; if there is a mismatch it will generate an error that the fingerprint did not match and if it is not present it will show the fingerprint and ask if you want to trust or not the host before connecting:

PS C:\> New-SSHSession -ComputerName "192.168.1.191" -Credential (Get-Credential carlos)

Server SSH Fingerprint
Do you want to trust the fingerprint 62:ef:96:b6:f8:a9:6c:7c:34:29:e6:d6:ba:59:ad:2f
[] Y  [] N  [?] Help (default is "N"): Y

Index Host             Connected
----- ----             ---------
  0   192.168.1.191    True

We can see all the hosts we trust using the Get-SSHTrustedHost command and one can remove hosts from the trusts list using Remove-SSHTrustedHost:

PS C:\> Get-SSHTrustedHost | fl

SSHHost     : 192.168.1.191
Fingerprint : 62:ef:96:b6:f8:a9:6c:7c:34:29:e6:d6:ba:59:ad:2f

When =theession is created, we can look at the session using the Get-SSHSession command

PS C:\> Get-SSHSession | fl

Connected : True
Index     : 0
Host      : 192.168.1.191
Session   : Renci.SshNet.SshClient

Each session has the Index property that can be used with other commands or the object that is returned.

To disconnect from the hosts we use the Remove-SSHSession

PS C:\> Remove-SSHSession -Index 0 -Verbose

VERBOSE: 0
VERBOSE: Removing session 0
True
VERBOSE: Session 0 Removed

Executing Command

We can execute commands against a session or sessions using the Invoke-SSHCommand command. When a command is executed an object representing the results of the execution is returned. When executed it instantiates on the system a new instance of the default shell configured on the system, executes the command and returns an object and the exit status of the last command executed.

PS C:\> Invoke-SSHCommand -Index 0 -Command "uname -a"

Host       : 192.168.1.191
Output     : Linux testdebian7 3.2.0-4-amd64 #1 SMP Debian 3.2.51-1 x86_64 GNU/Linux
ExitStatus : 0

In the case of Linux/Unix systems when the command string is given to the shell, the instance is closed so it will retain the state because the shell instance is closed after each execution.

PS C:\> Invoke-SSHCommand -Index 0 -Command "pwd"

Host       : 192.168.1.191
Output     : /home/carlos
ExitStatus : 0

PS C:\> Invoke-SSHCommand -Index 0 -Command "cd /"

Host       : 192.168.1.191
Output     :
ExitStatus : 0

PS C:\> Invoke-SSHCommand -Index 0 -Command "pwd"

Host       : 192.168.1.191
Output     : /home/carlos
ExitStatus : 0

But in the case of Linux or Unix we can chain command with the shell command terminator and have the shell run them.

PS C:\> Invoke-SSHCommand -Index 0 -Command "uname -a; cd /; pwd; ls -l"
Host       : 192.168.1.191
Output     : Linux testdebian7 3.2.0-4-amd64 #1 SMP Debian 3.2.51-1 x86_64 GNU/Linux
             /
             total 88
             drwxr-xr-x   2 root root  4096 Dec 17  2013 bin
             drwxr-xr-x   3 root root  4096 Dec 17  2013 boot
             drwxr-xr-x  13 root root  3200 Jun 28 11:16 dev
             drwxr-xr-x 133 root root 12288 Jun 28 11:16 etc
             drwxr-xr-x   3 root root  4096 Dec 17  2013 home
             lrwxrwxrwx   1 root root    30 Dec 17  2013 initrd.img -> /boot/initrd.img-3.2.0-4-amd64
             drwxr-xr-x  15 root root  4096 Dec 17  2013 lib
             drwxr-xr-x   2 root root  4096 Dec 17  2013 lib64
             drwx------   2 root root 16384 Dec 17  2013 lost+found
             drwxr-xr-x   4 root root  4096 Oct 13  2013 media
             drwxr-xr-x   2 root root  4096 Sep 22  2013 mnt
             drwxr-xr-x   2 root root  4096 Oct 13  2013 opt
             dr-xr-xr-x 105 root root     0 Jun 28 11:15 proc
             drwx------   3 root root  4096 Dec 17  2013 root
             drwxr-xr-x  19 root root   880 Jun 28 11:16 run
             drwxr-xr-x   2 root root  4096 Dec 17  2013 sbin
             drwxr-xr-x   2 root root  4096 Jun 10  2012 selinux
             drwxr-xr-x   2 root root  4096 Oct 13  2013 srv
             drwxr-xr-x  13 root root     0 Jun 28 11:15 sys
             drwxrwxrwt   6 root root  4096 Jun 28 14:17 tmp
             drwxr-xr-x  10 root root  4096 Dec 17  2013 usr
             drwxr-xr-x  12 root root  4096 Dec 17  2013 var
             lrwxrwxrwx   1 root root    26 Dec 17  2013 vmlinuz -> boot/vmlinuz-3.2.0-4-amd64
ExitStatus : 0

This will work with Unix, Linux and even Windows systems running SSH.

One special case is with Cisco equipment where after execution of the command the Cisco equipment terminated the connection. In this case we can create a console using the SSH session object. When we create the console, it reruns a console stream object to which we can write commands we want to execute, terminating them with e new line and then read the output that was generated by reading the stream.

PS C:\&gt; $session = Get-SSHSession -Index 1
PS C:\&gt; $stream = $session.Session.CreateShellStream(&quot;dumb&quot;, 0, 0, 0, 0, 1000)
PS C:\&gt; $stream.Write(&quot;show ver<code>n&quot;)
PS C:\&gt; $stream.Read()
TSGAP01#show ver
Cisco IOS Software, C1240 Software (C1240-K9W7-M), Version 12.3(8)JA, RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2006 by Cisco Systems, Inc.
         Compiled Mon 27-Feb-06 09:17 by ssearch

         ROM: Bootstrap program is C1240 boot loader
         BOOTLDR: C1240 Boot Loader (C1240-BOOT-M) Version 12.3(7)JA1, RELEASE SOFTWARE (fc1)

         TSGAP01 uptime is 2 minutes
         System returned to ROM by power-on
         System image file is &quot;flash:/c1240-k9w7-mx.123-8.JA/c1240-k9w7-mx.123-8.JA&quot;

         This product contains cryptographic features and is subject to United
         States and local country laws governing import, export, transfer and
         use. Delivery of Cisco cryptographic products does not imply
         third-party authority to import, export, distribute or use encryption.
         Importers, exporters, distributors and users are responsible for
         compliance with U.S. and local country laws. By using this product you
         agree to comply with applicable laws and regulations. If you are unable
         to comply with U.S. and local laws, return this product immediately.
          --More--
PS C:\&gt; $stream.Write(&quot;</code>n&quot;)
PS C:\&gt; $stream.Read()
TSGAP01#

 

Uploading and Downloading Files with SCP

The module also provides SCP commands for uploading and downloading files. SCP works by establishing a connection and copying or downloading the file specified depending on the action selected.

For uploading a file we use the Set-SCPFile cmdlet. We need to specify a server, credentials, a local file that we want to upload, and the full path and name of the full path of the destination file.

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

The cmdlet provides progress information about the uploaded bytes.

2

To download a file the process is similar, but we use the Get-SCPFile cmdlet.

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

We can also do the same with folder using Get-SCPFolder and Set-SCPFolder. The cmdlet will upload all files recursively.

Using SFTP

The module also provides SFTP support. The SFTP commands also work with sessions.  To create a SFTP session we use the New-SFTPSession cmdlet. It uses the same list of trusted hosts as the one for SSH sessions.

PS C:\> New-SFTPSession -ComputerName 192.168.10.3 -Credential (Get-Credential root) -Verbose | fl
VERBOSE: Using Username and Password authentication for connection.
VERBOSE: Connecting to 192.168.10.3 with user root

Connected : True
Index     : 0
Host      : 192.168.10.3
Session   : Renci.SshNet.SftpClient

Just like with SSH commands, SFTP commands use the index of the session or the session object itself to specify a session. Use the Get-SFTPSession command to get all SFTP sessions or a specified one.

PS C:\> Get-SFTPSession  | fl

Connected : True
Index     : 0
Host      : 192.168.10.3
Session   : Renci.SshNet.SftpClient

One big difference between SSH and SFTP sessions is that the SFTP session is just like FTP. A stateful one where we can change directory paths and the session remains on that location.  We can get our current location on the system using the Get-SFTPCurrentDirectory command and we can change location using Set-SFTPDirectoryPath cmdlet.

PS C:\> Get-SFTPCurrentDirectory -Index 0
/root

PS C:\> Set-SFTPDirectoryPath -Index 0 -Path /usr/bin

PS C:\> Get-SFTPCurrentDirectory -Index 0
/usr/bin

We can get directory listings using the Get-SFTPDirectoryList command–the command will return a collection of objects referring to each of the files and directories in the given path.

PS C:\> Get-SFTPDirectoryList -Index 0 -Path /tmp

FullName       : /tmp/vmware-config2
LastAccessTime : 12/28/2013 8:54:40 AM
LastWriteTime  : 12/28/2013 8:54:40 AM
Length         : 4096
UserId         : 0

FullName       : /tmp/vmware-fonts0
LastAccessTime : 2/8/2013 7:50:24 PM
LastWriteTime  : 2/8/2013 7:50:24 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/vmware-root
LastAccessTime : 6/28/2014 3:00:52 PM
LastWriteTime  : 6/28/2014 3:00:52 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/vmware-config0
LastAccessTime : 2/8/2013 7:50:00 PM
LastWriteTime  : 2/8/2013 7:50:00 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/poshssh
LastAccessTime : 6/28/2014 7:57:30 PM
LastWriteTime  : 6/28/2014 7:58:38 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/vmware-fonts1
LastAccessTime : 4/26/2013 2:23:16 PM
LastWriteTime  : 4/26/2013 2:23:16 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/vmware-tools-distrib
LastAccessTime : 12/28/2013 8:36:20 AM
LastWriteTime  : 8/17/2013 1:51:12 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/vmware-fonts2
LastAccessTime : 12/28/2013 8:55:01 AM
LastWriteTime  : 12/28/2013 8:55:01 AM
Length         : 4096
UserId         : 0

FullName       : /tmp/.
LastAccessTime : 6/28/2014 9:42:56 PM
LastWriteTime  : 6/28/2014 9:39:44 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/.ICE-unix
LastAccessTime : 6/28/2014 3:00:50 PM
LastWriteTime  : 6/28/2014 3:00:50 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/vmware-config1
LastAccessTime : 4/26/2013 2:22:52 PM
LastWriteTime  : 4/26/2013 2:22:52 PM
Length         : 4096
UserId         : 0

FullName       : /tmp/..
LastAccessTime : 6/28/2014 3:00:51 PM
LastWriteTime  : 6/28/2014 3:00:50 PM
Length         : 4096
UserId         : 0

PS C:\> Get-SFTPDirectoryList -Index 0 -Path /tmp | gm

   TypeName: Renci.SshNet.Sftp.SftpFile

Name              MemberType Definition
----              ---------- ----------
Delete            Method     void Delete()
Equals            Method     bool Equals(System.Object obj)
GetHashCode       Method     int GetHashCode()
GetType           Method     type GetType()
MoveTo            Method     void MoveTo(string destFileName)
SetPermissions    Method     void SetPermissions(int16 mode)
ToString          Method     string ToString()
UpdateStatus      Method     void UpdateStatus()
Attributes        Property   Renci.SshNet.Sftp.SftpFileAttributes Attributes {get;set;}
Extensions        Property   System.Collections.Generic.IDictionary[string,string] Extensions {get;set;}
FullName          Property   string FullName {get;set;}
GroupCanExecute   Property   bool GroupCanExecute {get;set;}
GroupCanRead      Property   bool GroupCanRead {get;set;}
GroupCanWrite     Property   bool GroupCanWrite {get;set;}
GroupId           Property   int GroupId {get;set;}
IsBlockDevice     Property   bool IsBlockDevice {get;}
IsCharacterDevice Property   bool IsCharacterDevice {get;}
IsDirectory       Property   bool IsDirectory {get;}
IsNamedPipe       Property   bool IsNamedPipe {get;}
IsRegularFile     Property   bool IsRegularFile {get;}
IsSocket          Property   bool IsSocket {get;}
IsSymbolicLink    Property   bool IsSymbolicLink {get;}
LastAccessTime    Property   datetime LastAccessTime {get;set;}
LastAccessTimeUtc Property   datetime LastAccessTimeUtc {get;set;}
LastWriteTime     Property   datetime LastWriteTime {get;set;}
LastWriteTimeUtc  Property   datetime LastWriteTimeUtc {get;set;}
Length            Property   long Length {get;}
Name              Property   string Name {get;set;}
OthersCanExecute  Property   bool OthersCanExecute {get;set;}
OthersCanRead     Property   bool OthersCanRead {get;set;}
OthersCanWrite    Property   bool OthersCanWrite {get;set;}
OwnerCanExecute   Property   bool OwnerCanExecute {get;set;}
OwnerCanRead      Property   bool OwnerCanRead {get;set;}
OwnerCanWrite     Property   bool OwnerCanWrite {get;set;}
UserId            Property   int UserId {get;set;}

When working with files we can move, delete, upload, and download a specified files on a SFTP:

  • Get-SFTPFile – Download a specified file from a remote SFTP session.
  • Move-SFTPFile – Moves a specified file in a remote hosts through SFTP (Can be used to rename a file)
  • Remove-SFTPFile – Deletes a specified file in a remote hosts through SFTP.
  • Set-SFTPFile – Uploads a specified file to a given path using SFTP.

We can also create and delete directories on a target system:

  • New-SFTPDirectory – Creates a directory in a remote hosts through SFTP.
  • Remove-SFTPDirectory – Deletes a specified directory in a remote hosts through SFTP.

The Posh-SSH module should cover most of the basic needs. Each of the sessions include the session object that provides additional methods and properties. Most commands also return objects with additional methods and properties not shown by default that can be leveraged by an advanced user. I hope you find the module useful and if you come up with a new command or a bug fix do not hesitate to contribute.

Filed in: Articles, Community, Online Only Tags: , , ,

162 Responses to "Posh-SSH: Open Source SSH PowerShell Module"

  1. Olivier says:

    Many thanks for this great module.
    When I create a New-SSHSession, I don’t have the ProxyServer and ProxyPort paramaters available (proxyType and ProxyCredential are available)… Do you have any idea?
    Many thanks in advance

    • Carlos Perez says:

      I found the problem and fixed it. You should use the latest version from the Git Hub site.

      • George K says:

        This module works great!!
        When using New-SSHSession through a proxy, the -Port parameter works, however when I use New-SSHSession on my local network, it does not work.
        I have several SSH servers and some of them use a different port other than port 22. Maybe I’m doing something wrong. Here is an example of how I use it:

        $kf = “C:\Users\George\Documents\MyPrivateKeyRSA”
        $pi = New-Object System.Management.Automation.PSCredential(“pi”, (ConvertTo-SecureString “my-key-passphrase” -AsPlainText -Force))

        New-SSHSession -ComputerName eddy -Port 443 -Credential($pi) -KeyFile $kf -ConnectionTimeOut 120000

        It connects, but to not to port 443.

        Here is the netstat result:

        Invoke-SSHCommand -Index 0 -Command “sudo netstat -tulapn”

        Host : eddy
        Output : Active Internet connections (servers and established)
        Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
        tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 18401/sshd
        tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 18401/sshd
        tcp 0 80 192.168.5.212:22 192.168.5.100:21608 ESTABLISHED 7611/sshd: pi [priv
        udp 0 0 192.168.5.212:123 0.0.0.0:* 2369/ntpd
        udp 0 0 127.0.0.1:123 0.0.0.0:* 2369/ntpd
        udp 0 0 0.0.0.0:123 0.0.0.0:* 2369/ntpd

        ExitStatus : 0

        As you can see, it connected to port 22 and not 443.
        Am I doing something wrong?

        • Alex says:

          Hey George,
          Can you help me out with how to generate the public/private key for my windows machine? I’m assuming that I generate a private key and use that for the -Keyfile paramter, then add the public key to the authorized hosts file on my linux box. Is that the right approach? If so, where do I start to generate that key pair?

          -Alex

          • Carlos Perez says:

            You would need to generate the keys on server running OpenSSH or the comercial SSH.com product. The module at the moment does not support key generation.

  2. Jim says:

    Hello Mr. Perez,

    First, I wanted to thank you for the time taken to create such a gem in the Windows environment.

    However, this is literally the only webpage I can find online with information pertaining to this module. My question is this:

    Can Get-SCPFolder be utilized to copy only new or modified files? It seems to copy the entire folder regardless if the files already exist in the destination directory. Hopefully I am overlooking an easy method to do this. Your feedback, direction, and/or opinions would be highly grateful and appreciated. Thank you in advance.

    Best Regards,
    Jim Carpenter

  3. Carlos Perez says:

    The SCPFolder cmdlet will overwrite all files at the target, sadly the library I’m using does not provide much control on this.

    • Jim says:

      Thank you for your response. The cmdlet is still highly useful, especially in my mixed environment and unique security rules. Your efforts are highly appreciated. One day it would be nice to have similar functionality as the /MIR opt in robocopy; and the /log opt too 🙂

      I have recently began writing c# code, but mostly wpf; so I do not believe I have the required skillset to professionally write code for your project yet, but if you are interested I can figure things out quite easily and am willing to assist in any way I can. However, specific direction towards a goal would be helpful. i.e. assist with documentation or creating a GUI for it, etc.. Whatever you feel is needed for the project.

      Best Regards,
      Jim Carpenter

  4. SysAdmin-E says:

    Thank you for this module. I use it along with VMware PowerCLI to lists the VMs running on my VMware and Linux KVM hosts. Below is a snippet of how I used this module. I don’t claim to be the best scripter, but I was able to accomplish what I needed to do.

    Foreach ($strKVMHost in $InputFile2KVMHosts)
    {
    New-SSHSession -ComputerName $strKVMHost -Credential ($objCredLinuxAdmin)
    If((Get-SSHSession | measure).Count)
    {
    Invoke-SSHCommand -Index 0 -Command “virsh list –all” | Out-File -Append $strFileOutputPath1
    Remove-SSHSession -Index 0
    }
    Else
    {
    “ERROR ***** Linux KVM host $strKVMHost not accessible. ***** ERROR” | Out-File -Append $strFileOutputPath1
    }
    }

  5. Sven says:

    Hi Carlos

    Is there an possibility to send sudo su

    and

    I use kerberos auth but cant connect due to I need to imput the user in the format domain\user
    but I receive New-SSHSession : Permission denied (password).

    thanks

    regards

    Sven

    • Carlos Perez says:

      Is it actually requesting from the KDC a ticket and validating the Kerberos information in the SPN or is it just acting as a PAM module and validating the username and password only? currently the module does not support the first scenario.

  6. Vilas says:

    Hi Carlos,

    Your work on this module is commended.

    I need another favor from you. I am using PowerShell Ver 2 and this module wont work on it. Unfortunately am not allowed to upgrade my powershell version. Could yo please let me know is there any way I can make use of this module in PowerShell version 2.

    Thanks in advance

  7. Chris says:

    Hello,
    first, thx for your great work ! i’m testing it !
    i wanted to test the Cisco way but it seem that the $session don’t have a Session method, i mean, when i do : $stream = $session.Session.CreateShellStream(“dumb”, 0, 0, 0, 0, 1000)
    it return me an error :
    Can’t call a method in a nulled expression (translated by me lol)

    have you an idea to fix it ?
    best regards
    Chris

  8. Richard says:

    I’m having a problem when using the below command. It pops up a Credential Request for the user “mqmon” and it makes me put in a password. Whether the password is correct or not it then uses the keyfile and transfers the file. how do I get rid of the pop up ?

    thanks

    PS C:\Users\richsab> Get-SCPFile -LocalFile testfile.dat -RemoteFile “test.file.dat” -ComputerName 10.198.133.11 -Credential (Get-Credential mqmon) -Keyfile .\id_rsa -verbose

    VERBOSE: Using SSH Key authentication for connection.
    VERBOSE: Using key with passphrase.
    VERBOSE: Connection succesfull
    VERBOSE: Downloading testfile.dat

  9. Carlos Perez says:

    That is do to the Get-Credential cmdlet executing first. When using a key file the credential object is used differently, the username will identify the user for the key and the password will be used as the passphrase for the key. Try saving the credentials in a variable and then use that variable in the credential parameter as many times as you like so you do not get prompted each and every time.

  10. Howard says:

    Firstly, great module you have here.. this is going to save a lot of time for me! Secondly, Is it possible to run “sudo cp”, if the account is configured to do so without requiring a password?

  11. christophe says:

    Is there a way to handle Exeptions?

    try {
    $SSHSession = New-SSHSession -ComputerName uxs11z1 -Credential $MyCredentials
    }
    catch [Exeption]
    {
    write-host $_.Exception.GetType().FullName;
    write-host $_.Exception.Message;

    Write-Output “Credentials are not correct or fingerprint key is not accepted or ….”
    }

    • Carlos Perez says:

      Try and Catch would be the best way, just tried it and it worked without the [exception] type in the catch statement.

      • christophe says:

        Ok, it works but there is no way of telling why the program jumped to the catch statement.
        Was it the fingerprint-key, was it the username and/or password wrong, something else? ….

      • christophe says:

        sorry, i found it
        if( $newSshSession.GetType().FullName -match “string”)
        {
        Write-Output $newSshSession
        }

  12. christophe says:

    Can we disable the output from Remove-SSHSession -Index $index
    Now it returns true even without the -verbose parameter

  13. christophe says:

    I’m trying to change a password through the /etc/shadow file on a unix system.
    so i need an encrypted string
    what I did is I let the unix server generate a encrypted password form a string.
    then used that string to set the password.
    The only problem is whenever i use an @ in my password it only uses the part before the @ as password
    anyone has a solution of explanation how this happens?

    [String]$newPassword = “hallo@mypassword”
    [String]$commandGetPassword = “perl -e ‘print crypt(“+'”‘ + $newPassword +'”, “userTo”)’+”‘”
    $returnValueGetPassword = Invoke-SSHCommand -SSHSession $newSshSession -Command $commandGetPassword

    • Carlos Perez says:

      No clue there. You do know that it is a very very bad practice to edit the shadow file directly? you can create a stream like in the example for the cisco device and use the proper passwd command and wait for the prompt for the password and its verification and write the new one to the stream.

      • christophe says:

        Hello, I tried this for the Red Hat and it works
        but for Solaris/Sparc
        Invoke-SSHCommand -SSHSession $newSshSession -Command “echo root:${newPassword} | chpasswd”

        • christophe says:

          I also tried this:
          $return = Invoke-SSHCommand -SSHSession $newSshSession -Command “passwd user1; newPassWord; newPassWord”

          but i get this:
          Output :
          Host : testinghost
          ExitStatus : 127
          Error : Permission denied
          bash: newPassWord: command not found
          bash: newPassWord: command not found

          however when do this with putty it works

          • christophe says:

            I fixed the problem:
            $session = Get-SSHSession -Index $($newSshSession.Index)
            $stream = $session.Session.CreateShellStream(“dumb”, 0, 0, 0, 0, 1000)
            $stream.Write(“passwd user1n")
            $stream.Write("password00
            n”)
            $stream.Write(“password00`n”)
            $stream.Read()

  14. christophe says:

    Is there a way to set up password-less communication?

  15. gw says:

    I’m a windows admin and looking to use scriptblock and argumentlist with “invoke-SSHCommand” , but I dont see any example. I know have used invoke-command with these parameters on windows.

  16. Máté says:

    Hi! I’m a Linux sysadmin but I’m using Windows as my desktop (Windows 10 more specifically). The new cmd.exe as far as I saw understands most Linux terminal controls, tunnels resize events through to the remote bash shell as it is supposed to.

    Is there any hope of receiving true interactive shells in Posh-SSH, now that there’s no need to write a terminal emulator, as it has been the practice on Windows for the past decade?

    Also, could we get some examples, how to set up the Windows Credentials in order to be able to log in passwordless to remote machines? (With saved passwords or with keyfiles? I already know how to to this under $(HOME)/.ssh/ with OpenSSH, but I am curious how I would do this with Posh-SSH.)

    Keep up the good work! Respect!

  17. rlb says:

    Great work Carlos! I appreciate your work on this. You have removed a technical barrier for me and made my transition from a Windows guy to a network guy much easier.

  18. mltorley says:

    I’m having trouble connecting to my servers using a keyfile AND port 222.
    If I use the -KeyFile switch, posh ignores the value of the -Port switch and tries to connect on 22.

    I’ve tried various iterations of this
    New-SSHSession -computername xxx.xxx.xxx.xxx -port 222 -keyfile c:\networks\skeleton.key

    I have tried using -credential (get-credential root), passing it the credential, etc.

    I’ve tried it without the keyfile, and connected on 222.

  19. Jon says:

    Moderator: please delete my last, the issue was with the credentials, not the communications. Thanks!

  20. Mcube says:

    I was just experimenting with this module and discovered that there is no error thrown if you try to Invoke-SSHCommand on an index that you have already done a Remove-SSHSession on.
    Is this by design or oversight?

  21. fra says:

    my guess is that is not working windows -> windows where the is DOMAIN\user . It get the username and not the domain when it tries to login via ssh

  22. Julien Berg says:

    Hello Mr Perez,,
    Thank you for this module.
    However, i meet a problem : When i want to connect to a SSH session and i receive this error : New-SSHSession : Invalid private key file.

    I don’t understand this error code.
    Please can you help me!

    Thank you

  23. Martin Yardley says:

    Hi,

    Great module! I’m trying to use the SFTP functionality and receiving the error New-SFTPSession : Server string is null or empty.

    New-SFTPSession -ComputerName 123.456.789.123 -Credential (Get-Credential FTPUSER) -Verbose | fl
    VERBOSE: Using Username and Password authentication for connection.
    VERBOSE: Connecting to 123.456.789.123 with user FTPUSER
    New-SFTPSession : Server string is null or empty.
    At line:1 char:1
    + New-SFTPSession -ComputerName 123.456.789.123 -Credential (Get-Credential FTP- …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [New-SFTPSession], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,SSH.NewSftpSession

    I’m using the cmdlet as directed in the documentation… is this a bug or am I missing something here?

    Many Thanks!

    Martin

  24. Theo says:

    Great module. I immediately put it to use at restarting failed Tivoli ITM agents. Love it. My Linux admin calls my script ‘wansible’.

  25. Chris says:

    First of all this one is a great pice of software!

    I works perfectly when I just just local IPs like:
    New-SSHSession -ComputerName “10.0.1.101” -Credential $mycreds

    But when I try it while yousing the -ProxyServer switch it aborts:
    New-SSHSession -ComputerName “5.5.5.5” -Credential $mycreds -ProxyServer “192.168.0.1” -ProxyPort 8080 -ProxyType “HTTP”

    The error message:
    New-SSHSession : Object reference not set to an instance of an object.

    + New-SSHSession -ComputerName “5.5.5.5” -Credential $mycreds -ProxyServer “192. …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [New-SSHSession], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,SSH.NewSshSession

    Any idea? Seems like the -ProxyServer switch is not implemented.

  26. Jeremy says:

    New-SSHSession establishes a connection, but Invoke-SSHCommand hangs, and I mean I can’t ctrl-c to break it, it completely hangs.

    • Carlos Perez says:

      Can you provide more info on what device are you connecting to and what command? if the command then prompts for input it will hang. I’m working on an update where I will add a timeout option.

  27. Hung Vu says:

    Hello Carlos,

    Thank you for the great module. I missed the following features how can we add them in:

    1. Invoke-SSHCommand: It accepts -sshSession and -Index and works well. How about host names? For instance: -computer host1, host2, host3. That would be more comfortable to use.

    2. New-SSHSession: If a connection is already exist an additional one will be created. Perhaps it would be enough to establish one session only.

    Regards
    Hung

    • Carlos Perez says:

      One can have multiple connections to a host under different account depending on the tasks, by limiting the connection to only one per hosts I would be removing that flexibility.

  28. DannyDiPietro says:

    This is a fantastic script/program. Thank you for taking the time to create it. I was wondering if there was a way you can suggest to automate the login process? What I am trying to accomplish is have a script use this module to login to our various Cisco switches and download their running and start configs on a weekly basis. I know there are far better uses for this module than just doing this, but for now this is our primary goal.

    The trouble I’m running into is that the credential dialogue box prevents this from being run as a script. Or at least I can’t figure out how to pass a username and password to the new-sshsession cmdlet. I understand the security risks of having a password in plain text, but that aside, how would you recommend this being accomplished.

    Thank you

    • Ben Conrad says:

      Use the 2 functions here: http://poshcode.org/474

      export-pscredential
      import-pscredential

      To run your scripts you will want to run export-pscredential as the service account that is used to run the scheduled task. That same service account can read the password, but no other account can read the password. works great.

      Ben

  29. Yusuf Ozturk says:

    Hi Carlos,

    I want to send SSH Key File content instead of SSH Key File Path. Because I get Key Files from database and I don’t want to store it on local computer due to security reasons.

    I will modify project to allow key content but that will be a good feature for other users as well I guess. So you can add that functionality to next release maybe.

    Btw, many thanks for this module. Great job, very good solution for a Microsoft “gap”.

    Regards,

    Yusuf

    • MattT says:

      Maybe you could read the data in from the database, and then write it to a temporary file for PoshSSH to read, and wipe when finished? Depending on how you have them stored, doing so would probably range from trivially easy to slightly annoying.

    • mltorley says:

      Solved the problem I was having with setting the port while using a keyfile.
      in sessions.cs, lines 447 and 453 should read
      connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, sshkey);

      They were missing _port

  30. Carlos Perez says:

    Thanks for pointing that out. I will make sure it is fixed in 1.7. Next version is a almost a full re-write

  31. Carlos Perez says:

    Yusuf will look in to it but no promises, right now the parameter sets are Proxy or no proxy so a third parameter set would be a bit complicated in C# but looking at alternatives to achieve it.

  32. Christian says:

    Great module, that really fills a gap in Powershell.

    One minor thing: It would be nice, if “-AcceptKey $true” would not only accept the connection if the fingerprint is unknown, but also if there is already a fingerprint, that differs from the one being presented in the new connection.

    /Christian

    • Carlos Perez says:

      That meant to work that way by design so as to prevent MitM attacks. All SSH solutions work the same way since this is the way to protect from you giving your credentials to a malicious host.

  33. Theresa says:

    I use the New-SshSession and Invoke-SshCommand cmdlets to ssh to a linux server and execute few commands. The script is not sourcing my .profile file. IS this a bug or something?

    New-SshSession -ComputerName cagent01
    $A= Invoke-SshCommand -InvokeOnAll -Quiet -Command ‘. ~/.bash_profile; echo “$ORACLE_HOME”‘
    $Result = Invoke-SshCommand -InvokeOnAll -Quiet -Command ‘./start’
    write-host “Path is $A”
    Remove-SshSession -RemoveAll

    This script is not displaying the ORACLE_HOME and the Bamboo plan that runs on this server fails due to this.

    • Theresa says:

      btw, thanks for the module. Its awesome

      • Theresa says:

        nevermind I see what was missing. Am running this script remote, meaning run though non interative shyell and it uses .bashrc not .bash_profile.
        So i sourced /etc/profile in the .bashrc so the script now reads the ORACLE_HOME.
        Thanks,

        • Carlos Perez says:

          You can also use the stream method described for Cisco devices. That created an interactive shell as a Stream object. it requires more coding to use but may be of help in your case.

  34. nemoi says:

    Hi, Carlos. Thank you for the great work.
    I try to use your module to connect to IBM server’s IMM card (Integrated Management Module). With plink/putty I do it with “-t” switch (forces tty-allocation).
    I didn’t find something same parameter in Invoke-SSHCommand cmdlet.
    I tried “The Cisco way” from your example and didn’t success too, I get an empty output …
    I saw another methods in $session.Session object – CreateCommand(), RunCommand(), CreateShell(), may be I need one of them ?

  35. Ben Conrad says:

    Carlos,

    This is a the best (free) ssh module for PowerShell available. I’ve been using this a lot with our Cisco NXOS devices, we are using the stream and it’s working well.

    One thing I’d like to be able to get rid of is that the input command is echoed to the stream. For example, If I send ‘show ver’ the first line I get back is ‘show ver’ and I have to write code to ignore that first line.

    Can you make a change to not echo the input command?

    Thanks,

    Ben

    • Ben Conrad says:

      Here is a better example, I’m only really interested in the output of show clock but I get the command, the output and the prompt:

      PS E:\> $stream.write(“show clock`n”)
      PS E:\> $stream.read()
      show clock
      04:06:24.143 UTC Tue Mar 17 2015
      la01sansw1#

      • joshua says:

        If you’re only interested in the output, why use the stream at all?

        $Response = Invoke-SSHCommand -Index 0 -Command “show ver”
        $Response.Output

      • Carlos Perez says:

        sadly it is the way the library is, it is actually emulating an xterm that is why you see the command echoed back and the prompt.

  36. Atle Holm says:

    $sftpUser = “user”
    $sftpPass = ConvertTo-SecureString -String “pass” -AsPlainText -Force
    $sftpCred = new-object -typename System.Management.Automation.PSCredential -argumentlist $sftpUser, $sftpPass
    $sftpSession = New-SFTPSession -ComputerName 51.226.164.12 -Credential $sftpCred

    Set-SFTPFile -SFTPSession $sftpSession -LocalFile “E:\CSV to sftp\send file1.csv” -RemotePath “/files/register” -Overwrite

    $sftpSession.Disconnect()
    Set-SFTPFile : Object reference not set to an instance of an object

  37. Sam says:

    Can this be used as an interactive shell (i.e. replacing Putty)?

    • Máté says:

      Unfortunately not, but I am looking forward to this feature also. Vote for subterminal support on the github project site in hope of getting support for it.

  38. bvi1998 says:

    Hi,
    I need to ssh from a Windows server using Powershell using the SSH modules. However, I am using Kerberos and get access denied. Is there any way around this? I do not know much about Kerberos, but I do know I have a ticket which is passed to the Linux host, bypassing the need for my login information.
    Thanks!

  39. rick says:

    Powershell has “enter-pssession”. I’m testing your commands but didn’t see a command like “enter-sshsession”. I want to be able to remote to the server and type commands there. Not sure if that is possible.

  40. TomFloor says:

    Hey Carlos, I’m trying to set up an SFTP session, using a username and a keyfile. In the examples above, there’s a passphrase on the keyfile, but I got a keyfile without a passphrase from a 3rd party vendor. You’ve explained how authentication with keyfiles work, where the username and the passphrase are stored using Get-Credential, but it appears that System.Management.Automation.PSCredential does not accept an empty password. When I set a random passphrase I get “New-SFTPSession : Invalid private key file.”, but when I don’t set I get “ConvertTo-SecureString : Cannot bind argument to parameter ‘String’ because it is an empty string.”. How do you set up a new SFTP connection when there’s no passphrase on the keyfile?

    Btw, I’ve tested the username/keyfile using WinSCP and I can connect to the SFTP server. Thanks!

  41. Dan Meier says:

    Thanks for this module.

    When I use $SessionObj = New-SSHSession -ComputerName $cname -Credential $cred -AcceptKey $true -ErrorAction Stop I always get an exception:
    A positional parameter cannot be found that accepts argument ‘True’

    • MattT says:

      Looks like -AcceptKey is just a switch. It doesn’t look for a value, simply having it there sets it true.

  42. Sergey says:

    Hello!

    Great product, thank you very much!

    Just one thing: Set-SCPFile example on this page uses parameter -RemoteFile instead of -RemotePath.

  43. Taouche says:

    Hi,

    thanks for this module, since the last version, I have this error with the Invoke-SshCommand :

    Exception calling “EndExecute” with “1” argument(s): “Command ‘**********************”
    At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Posh-SSH\Posh-SSH.psm1:245 char:17
    + $Output = $cmd.EndExecute($Async)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SshOperationTimeoutException

    Any idea please ?

  44. thank you for the great and wonderful tool. however you cannot call out a command which includes quotes.
    let us say the command i want to run is
    vim-cmd proxysvc/remove_service “/mob” “httpsWithRedirect”
    this will not work with this method. is there anyway u can help me with it. this will greatly help me to automate the vmware esxi hosts security hardening.

  45. Kevin says:

    I’m having an issue running New-SSHSession. I’m not sure if the user (a system account) can run this or not. I can run it as myself, but system users don’t seem to be able to?

    PS>TerminatingError(New-SSHSession): “Session operation has timed out”
    New-SSHSession : Session operation has timed out

  46. Nima says:

    I want to run commands related to Openwrt in my C# application.I use SharpSSH libraries to run the commands.They work fine in running other commands e.g. free,cat,df etc… but return with not found for others like uci and wifi.Here is my code runs without any error:

    SshExec n = new SshExec(“192.168.3.1”, “root”, “tplinkwr841n”);
    n.Connect();
    string t = “”;
    string er = “”;
    n.RunCommand(“uci set wireless.@wifi-iface[1].disabled=1”, ref t, ref er);

    After running er has below value:

    “ash: uci: not found”

    also running other commands like wifi have similar result.I don’t have such a problem using putty. How can I run these commands in my c# application?

    • MattT says:

      Nima,
      Have you tried passing it the absolute path? You may not be in an instance of ash with the path environment variable set. On my openwrt it’s /sbin/uci

  47. Máté says:

    Hi Carlos,

    I am a happy user of Posh-SSH and wanted to share a news with you.

    http://www.phoronix.com/scan.php?page=news_item&px=Windows-SSH-Official

    How do you see this relate to your module? I am darned happy to see mainline support for SSH in Windows, but it does seem to overlap with Posh-SSH a great deal. The underlying tech for this new feature will be OpenSSH, not SSH.Net. Guess it was a choice following up on the new direction of both MS embracing OSS, and also the fact that the past year of OpenSSH development focused on mdularizing the code to make it easier to use as a library.

    Thoughts?

    • Carlos Perez says:

      Not related but happy to see MS focus on adding the support, they have more resources and time than me 🙂 What comes to mind when I saw it was “It is about darn time!”

  48. Eshe says:

    Hello,

    I have a scenario where I need to create a session on host2, but have to first go through host1. Has anyone done this successfully?

  49. Jon Hewitt says:

    FYI, I was using a proxy to try use your install one liner. I had to use the following, if it helps others:

    $webclient = New-Object System.Net.WebClient
    $webclient.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
    iex (New-Object $webclient).DownloadString(“https://gist.github.com/darkoperator/6152630/raw/c67de4f7cd780ba367cccbc2593f38d18ce6df89/instposhsshdev”)

  50. Joe says:

    I am able to install this module and start a new ssh session within powershell which is AWESOME. I have even run simple SSH commands and it works great.

    I’m running into an issue when I attempt to run an Invoke-SSHCommand that contains double quotes in the command it will fail to run because it only views the first complete set of double quotes as the ssh command. I have therefore created a variable, so when I run the $command1 it will display the correct command needed to execute. Thinking I had a workaround i run the below command and it will execute with no errors in the powershell 4 window but it will give a status code of 127. I found that it won’t actually execute the command on the remote server.

    $command1=”"echo vmx.fullpath = “/bin/vmx" >> /etc/vmware/config“”
    Invoke-SSHCommand -index 0 -Command $command1

    What is a status code of 127? What is the best way to Invoke-SSHCommand when the command contains double quotes?

  51. Matt A says:

    I have no clue what I’m doing wrong. I’ve used Powershell quite extensively for work and such, but this is an error I get when I run your handy dandy installation shell.

    Import-Module : The specified module ‘posh-ssh’ was not loaded because no valid module file was found in any module directory.
    At line:17 char:1
    + Import-Module -Name posh-ssh
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ResourceUnavailable: (posh-ssh:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

    The directories are in the Modules folder as they should be, all source code, tests and such.

    • Matt A says:

      Meh. Somehow my $env:PSModulePath was not set to that personalized directory you placed the Posh-SSH and Posh-SSH-Master files. I moved the files, it works fine.

      Thanks for the hard work!

    • Matt A says:

      Okay, so the reason I tried to port to Posh-SSH over SSH-Sessions module is because I was having an issue looping and trying to connect to multiple servers, in which only the last server in the array would get connected. I’ve found I have the same issue with Posh-SSH now, so I would like to know if you have any guidance on this. The first scenario fails, whereas if I hard code three connections in sequence they work fine. This makes little sense to me.

      Scenario 1: Dynamic SSH sessions

      $hostNames = (Read-Host “Please Enter the Host Names for Sudo-All (newline delimited)”).Split(“`n”)

      foreach($name in $hostNames){
      $name = $name.Trim(” “)
      New-SshSession -ComputerName $name -Credential $Creds -AcceptKey
      }

      Generates the following EXCEPT for the last $name in $hostNames

      New-SshSession : The requested name is valid, but no data of the requested type was found
      At D:\Powershell\Sudo-All.ps1:11 char:5
      + New-SshSession -ComputerName $name -Credential $Creds
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : NotSpecified: (:) [New-SSHSession], SocketException
      + FullyQualifiedErrorId : System.Net.Sockets.SocketException,SSH.NewSshSession

      ____________________________________

      However, this works perfectly fine.

      New-SshSession -ComputerName host1-Credential $Creds -AcceptKey
      New-SshSession -ComputerName host2 -Credential $Creds -AcceptKey
      New-SshSession -ComputerName host3 -Credential $Creds -AcceptKey

      Where I Am using the same exact 3 hosts for testing. Any guidance???

      • Matt A says:

        Tried to get savvy and use “C-like” looping, still to no avail and the same error with the last computer getting the connection while the first two fail.

        $i = $hostNames.Count
        while($i -ne 0)
        {
        New-SSHSession -ComputerName $hostNames[$i-1] -Credential $Creds -AcceptKey
        $i = $i – 1;
        }

        • Carlos Perez says:

          Only thing that comes to mind is a a race condition is happening. Have you tried putting sleep interval between connections of 1 or 2 seconds and see what happens?

  52. Ben says:

    I’m trying to put the password in the script and not enter it manually in the pop up window. How does the New-SSHSession -credential paramater work in regards to giving it both password and username? I know in plink -l is username and -pw is for password.

  53. Jeroen says:

    Dear Carlos,

    Could you tell me if reverse SSH is possible? If SSH terminology ssh -R 19999:localhost:22
    Note the -R parameter.

    Many thanks
    Jeroen

  54. yaro says:

    When I create a new ssh session and then run
    Invoke-SshCommand -ComputerName server1 -Command ‘uname -a’
    I get
    server1 had an error:

    What could be the cause for that?

    • Carlos Perez says:

      Because the comand Invoke-SSHCommand does not have a computer name parameter but requires the session Id of the session you created.

  55. yaro says:

    I create sshsession with
    New-SSHSession -computername server1 -username xxx -password yyy
    $result = $SSHsessions.server1.RunCommand(‘uname -a’).result
    $SSHHost = Invoke-SSHcomman -InvokeOnAll -command ‘uname -a’
    $connected = $result.trim(‘/home/’) … some code

    Now Get-SSHsession | fl
    gives me only computername:server1 and connected: true

    My Invoke-SSHcommand definitelly gives me -computername but no -sessionID which just got me to look into the name of the module and it turns up I use SSH-Sessions not Posh-SSH so posting in the wrong place. Sorry.

  56. Simon Zhang says:

    awesome! I just installed this module and it is great! I believe this module will make my daily work much easier, thanks for your great job!

    Simon

  57. Oliver says:

    This plugin is awesome. I am trying to use ssh keys for authentication. I have the key setup on the SSH server that I am connecting to. How do I tell the cmdlet where the key is on the connecting windows machine?

  58. Simon Zhang says:

    Hi Guru,

    does start-job can call Invoke-SSHCommand? thanks

    $sshsession=get-sshsession
    Invoke-SSHCommand -Sessionid $sshsession.sessionid -Command “touch newfile” and it was successful,

    but I want to use start-job to do it,

    start-job -scriptblock {param($sshid) Invoke-SSHCommand -sessionid $sshid -Command “touch newfile”} -Args $sshsession.SessionId

    it completes but no newfile,

    do you know what could be the cause?

    btw, using powershell how invoke-sshcommand can let time consuming command running in the background? really appreciate!

    Simon

    • Yusuf Ozturk says:

      Hi Simon,

      You should create new session in Start-Job script block because you can not access the parent session inside job. What you do here is simply sending an integer inside job.

      Regards,
      Yusuf
      PowerShell MVP

  59. Xabier Altube says:

    Hi,

    First fo all , thanks for the tool and congrats for it.

    I’m using POSH-SSH for automatizing a file transfer to an external server via SFTP.
    I have a PS1 file executed every day by an scheduled task.
    I use the “Set-SFTPfile” command, but for some reason it looks like there are cases were it fails the trasnfer.

    Is there any way to get the return code of the command so that I can check if the file has been properly transferred or not?

    Best regards.

  60. Diogo Santos says:

    Hi evereyone…

    Insite a linux server, i have a script.sh that execute some tasks in the server, and I need to execute this script by Powershell, to run in the Linux Server.

    How can I execute this script?

    I tried use:
    Invoke-SSHCommand -Index 0 -Command “chmod -x teste.sh”
    Invoke-SSHCommand -Index 0 -Command “teste.sh”
    Invoke-SSHCommand -Index 0 -Command “./teste.sh”

    But no one execute the tasks inside the server,

    Anyone can help me, please?

    Best regards,
    Diogo.

  61. Stuart Willson says:

    Hello,

    I’ve been having a go at using this module, but the output I’m getting isn’t coming out like is shown in the examples above. For example, if I send an ls-l command to my test server I get the result back all on a single line:

    Output : {total 56K, drwx—— 3 root root 4.0K Sep 21 10:52 ., drwxr-xr-x 22 root root 4.0K Apr 27 07:17 ..,-rw——- 1 root root 3.3K Oct 7 10:05 .bash_history…}

    Can anyone tell me how to get the output to list on multiple lines, please?

    Many thanks,

    Stuart

  62. Josh says:

    Carlos,

    Thank you very much for this project. I’m hoping we can add this to our toolset. I am having trouble actually passing commands. Getting connected seems easy enough (no key exchange, just username and password stored in $creds) This is what we are seeing.

    New-SSHSession 172.16.3.7 -Credential $creds

    SessionId Host Connected
    ——— —- ———
    0 172.16.3.7 True

    Z:\Powershell> Invoke-SSHCommand -Command “show status” -SessionId 0

    Exception calling “BeginExecute” with “0” argument(s): “An established connection was aborted by the server.”
    At C:\Users\nemesis\Documents\WindowsPowerShell\Modules\Posh-SSH\Posh-SSH.psm1:348 char:17
    + $Async = $cmd.BeginExecute()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SshConnectionException

    Exception calling “EndExecute” with “1” argument(s): “Either the IAsyncResult object did not come from the corresponding async
    method on this type, or EndExecute was called multiple times with the same IAsyncResult.”
    At C:\Users\nemesis\Documents\WindowsPowerShell\Modules\Posh-SSH\Posh-SSH.psm1:265 char:25
    + $Output = $_.cmd.EndExecute($_.Async)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

    Host : 172.16.3.7
    Output : {}
    ExitStatus : 0

    • Josh says:

      I was able to resolve my own issue.

      Even though my credentials were stored in $creds = Get-Credential the password was not being passed properly. I’m guess it has to do with the short output you get when connecting to SonicWall devices. For example:

      Copyright (c) 2015 Dell | SonicWALL, Inc.

      Using username ‘admin’.
      Password:

      I was able to work around this issue by passing the password again

      $creds = Get-Credential
      New-SSHSession 172.16.3.7 -credential $creds
      $SSHStream = New-SSHShellStream -Index 0
      $SSHStream.WriteLine(“PASSWORD”)
      $SSHStream.WriteLine(“configure”)
      $SSHStream.WriteLine(“user guest”)
      $SSHStream.WriteLine(“guest name guest123 profile “”Guest Wireless”” password password123″)
      $SSHStream.WriteLine(“enable”)
      $SSHStream.WriteLine(“commit”)
      $SSHStream.read()

      Quick and messy script for connecting to a Sonicwall and adding a Guest Wireless Account.

      I hope this helps someone.

  63. Rathore says:

    It’s a great library, I’m planning to use.

    is there a way to pull output from ssh console before finishing command execution?

    The below lines returns some set of data which can take 30 seconds to 1200(not exactly sure)
    $ret = Invoke-SSHCommand -SSHSession $ssh -Command “python3.4 SomeUtility.py” -TimeOut 1200

    so, before timeout or getting result back I want to look into output what is going on the screen.

    let me know if there a way to get live output from ssh console.

    Thanks,
    Rathore

  64. StipMan says:

    First off, Thanks for all you’ve done.

    I do have an issue I’d like to raise though. I’m connecting to some EMC storage and normal commands execute properly but I’ve noticed that commands that have an _ (underscore) in them fail with an exitStatus of 127. Is there some workaround I could use to get past this issue? Have you seen it before?

  65. Kevin says:

    Is Posh-SSH affected by the recent OpenSSH vulnerability that was fixed in OpenSSH 7.1p2 on Jan 14, 2016?

    http://arstechnica.com/security/2016/01/bug-that-can-leak-crypto-keys-just-fixed-in-widely-used-openssh/

    http://www.openssh.com/txt/release-7.1p2

    On a side note, thanks for Posh-SSH. It has been very helpful.

  66. Tyson Flint says:

    I believe you fixed this issue for SFTP in the past. I am now getting it for Get-SCPFile. Can you apply the same fix to Get-SCPFIle as you dit for Get-SFTPFile?
    •Address issue when progress message could get stuck in the PowerShell window after upload or download of a files was finished.

    The file copy progress bar shows up for me in Dell’s PowerGUI editor, but remains open at zero percent progress even after the SCP file copy finished. Perhaps add a -NoProgressBar parameter?

    Thanks

  67. Pavel says:

    Hello and good day!

    I have a problem with writing my script using this cool module (POSH-SSH) in PowerGUI Script Editor.

    The problem with executing command in script editor PowerGUI:
    New-SSHSession -ComputerName $Host_name -Credential (Get-Credential) -AcceptKey:$true

    Error of executing (PowerGUI):
    New-SSHSession : Permission denied (password).
    At line:1 char:1
    + New-SSHSession -ComputerName $Host_name -Credential (Get-Credential) …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [New-SSHSession], SshAuthenticationException
    + FullyQualifiedErrorId : Renci.SshNet.Common.SshAuthenticationException,SSH.NewSshSession

    But if i execute this command via powershell.exe the result is good. New session is created.

    Result of command (powershell.exe):

    cmdlet Get-Credential at command pipeline position 1
    Supply values for the following parameters:
    Credential

    SessionId Host Connected
    ——— —- ———
    0 146.225.33.11 True

    Version of module POSH-SSH: 1.7.4

    PowerShell Version:
    Major Minor Build Revision
    —– —– —– ——–
    5 0 10240 16384

    OS Version:
    Major Minor Build Revision
    —– —– —– ——–
    10 0 10240 0

    Please can you help me with this problem!

    Thanks in advance!

  68. Tracy says:

    I am trying to use set-scpfile with a key file that has no pass phrase. I put the command below but the problem is that it is still prompting me for credentials. I plan to use this to run as a scheduled task and i dont want to encode the user account and pass in the script thus the key file. What am i doing wrong.

    Command:
    set-scpfile -LocalFile $ofile -RemotePath $ufile -ComputerName $comp -KeyFile “C:\Temp\portal” -AcceptKey $true -Verbose

    • Carlos Perez says:

      have you tried providing an empty password credential object, still very bad practice to use any key without a passphrase?

  69. Andi says:

    Hi

    I try to use posh-ssh with powershell to execute a command on a host.
    But I allways get this output message:

    Output : {Extra params found in CLI, this is not supported, exiting the CLI session:}
    ExitStatus : 1

    I don’t know what the problem is.

    Any ideas?

    Regards,
    Andi

    • Carlos Perez says:

      Without further details on what type of host and the command I can’t really help with so little info. Looks like an error of the command ran and not the module it self. but without details on the host and command not sure.

      • Andi says:

        I solved it with the following code:
        $session = Get-SSHSession -Index 0
        $stream = $session.Session.CreateShellStream(“dumb”, 0, 0, 0, 0, 1000)
        $stream.WriteLine(“TEST”)

        The host was a cisco device.

  70. Sugapriya says:

    Hi,
    I have installed the POSH-SSH module .But i tired to install SSH-Sessions but most of the time It got failed(assembly loaded error).So can you please tell what is the difference between POSH and SSH-Session. And any one have the link to download the SSH-Session.Zip means help me.

  71. Faris says:

    Thanks for the wonderfull work.
    I was able to communicate with my Physical Blade and Storage and Get the WWPN using this module, parse it with some regex and other powershell technices, then connect to my Brocade Switch and Do the Aliases and Zoning on the SAN Switch

    its configure your network via powershell. later on I can share the script.
    Thanks again

  72. Mike says:

    Hi,
    Thanks for the great work on this. I ran some tests on a host and it did everything I expected/needed. However, when I added a proxy and port I got a null reference error like:

    PS C:\Users\user> New-SFTPSession -ComputerName sftphost.com -Credential (Get-Credential) -ProxyServer myproxy.com -ProxyPort 80 -Verbose

    cmdlet Get-Credential at command pipeline position 1
    Supply values for the following parameters:
    Credential
    VERBOSE: Using SSH Username and Password authentication for connection.
    New-SFTPSession : Object reference not set to an instance of an object.
    At line:1 char:1
    + New-SFTPSession -ComputerName host.host.com -Credential (Get-Cre …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [New-SFTPSession], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,SSH.NewSftpSession

    I tested on a host that does not require a proxy as well as a host that does and I get the same error. Is there something I am missing? Thanks again!

    • Mike says:

      Looks like the -ProxyCredential variable is causing the issue. If you leave it out completely you get the null error. If you pass it in with any value, it works. Looks like it is in ConnectionInfoGenerator.cs line 63

      • Carlos Perez says:

        thanks will take a look and hopefully have it fixed for the next release.

        • Mike says:

          Thanks Carlos,

          I think I found the issue (at least for my use case, it was ConnectionInfoGenerator.cs line 144). I was able to grab it from the repo, make some changes, and recompile to get it to work. I was not sure about committing back to the repo (kinda new to git and C#) but would be happy to if you want to review my changes. Either way thanks for the reply and help.

  73. goudeuk says:

    Hello

    First of all, many thanks for writing posh-ssh.

    I have installed it on windows 7 and I can ssh to linux machines with no problems, however
    when I try to ssh to another windows computer I always get this error:

    new-sshsession: No connection could be made because the target machine actively refused it.

    please note that firewall is disabled on the target machine.

    Any suggestions please?

    thank you

    • Carlos Perez says:

      and is the Windows computer running a third party SSH server? Windows does not come with SSH server since MS still has not shipped one with the product.

  74. Zhong says:

    Hi,

    When I manually connect to this ftp site using FileZilla, I get a dialog box that ask me to trust this certificate and carry on connecting. Is that why I’m getting “New-SFTPSession : Socket read operation has timed out after 5000 milliseconds.” error ? Even after I used -AcceptKey, it still timed out.

    PS C:\> $Session = New-SFTPSession -ComputerName XXX.XXX.XXX.XXX -port 18003 -Credential (Get-Credential FTPUSERS) -Verbose -AcceptKey
    VERBOSE: Using SSH Username and Password authentication for connection.
    New-SFTPSession : Socket read operation has timed out after 5000 milliseconds.
    At line:1 char:12
    + $Session = New-SFTPSession -ComputerName XXX.XXX.XXX.XXX -port 18003 …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : OperationTimeout: (Renci.SshNet.SftpClient:SftpClient) [New-SFTPSession], SshOperationTi
    meoutException

    In general, on a site that ask me to trust a certificate, do I need to create a trusted host with New-SSHTrustedHost ?

    I have 2 fingerprints, Fingerprint (SHA-256), and Fingerprint (SHA-1), on the certificate.

    I tried to create a SSHTrustedHost with both fingerprints, same error.

    Desperately need some help.

    Thanks in advance.

  75. Jo King says:

    Hi great module!

    How can I connect to a (Linux-based) sshd with a client certificate?

  76. Peter Rhoades says:

    I can connect to server via New-SFTPSession. I can access the “Connected” “Host” “Sessionid” properties. But when I try to run Set-SFTPFile using -SFTPSession [and my “$sessionid”] I get “Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: Index”

    • Carlos Perez says:

      When doing Set-SFTPFile the -SFTPSession option takes only a object for the session not the ID

      For the ID use SesionID

  77. curropar says:

    Hi!

    Great module! Just started to use it, and it’s exciting! Wondering if you’ve plans, or thought about, an Enter-SSHSession cmdlet, so you can execute commands interactively. Beause, you know, I’m lazy and I want to avoid to open another tool, if I can do it with just one…

    One thing more: default output is this:

    PS C:\Windows\system32> Invoke-SSHCommand 0 “ls / -l”

    Host : mycentosbox
    Output : {total 450, drwxr-xr-x 2 root root 4096 Oct 26 20:50 backup, drwxr-xr-x 2 root root 4096 Oct 11 13:20 bin, drwxr-xr-x 4 root root 1024 Oct 3 2014 boot…}
    ExitStatus : 0

    Not nice, as I don’t get the output in the stream of my PS console… Let’s see how it looks like with a select:

    PS C:\Windows\system32> Invoke-SSHCommand 0 “ls / -l” | select output

    Output
    ——
    {total 450, drwxr-xr-x 2 root root 4096 Oct 26 20:50 backup, drwxr-xr-x 2 root root 4096 Oct 11 13:20 bin, drwxr-xr-x 4 root root 1024 Oct 3 2014 boot…}

    Nop, not there yet. Another try:

    PS C:\Windows\system32> Invoke-SSHCommand 0 “ls / -l” | select -ExpandProperty output
    total 450
    drwxr-xr-x 2 root root 4096 Oct 26 20:50 backup
    drwxr-xr-x 2 root root 4096 Oct 11 13:20 bin
    drwxr-xr-x 4 root root 1024 Oct 3 2014 boot
    drwxr-xr-x 12 root root 3500 Oct 23 04:02 dev
    drwxr-xr-x 85 root root 4096 Oct 25 04:04 etc
    drwxr-xr-x 5 root root 4096 Jul 27 10:27 home
    [and so on…]

    Yes, that’s what I was looking for! It would be so great if this were the default output… – wink, wink… 😉

    Again, thanks for your work and time!!

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: