NetCmdlets: Creating a Persistent SSH Session
Sometimes you need a persistent SSH session to execute sequential commands that rely upon the results of the previous commands. NetCmdlets makes it easy to create a persistent SSH session to run sequential commands. In order to create a persistent SSH session you will need to make use of 4 things:
- The Connect-SSH cmdlet
- The Invoke-SSH cmdlet
- The Disconnect-SSH cmdlet
- The -ShellPrompt parameter
The key thing to remember here is to always use the -ShellPrompt parameter when you need a persistent session. The -ShellPrompt parameter instructs the cmdlets to connect to the SSH server and utilize the shell to execute commands. If the -ShellPrompt parameter is not used, then the cmdlets will use the Sexec protocol which terminates the connection after executing the command and does not maintain a persistent session.
For demonstration purposes, the following script will connect to a remote server, print the current working directory, change the current directory, and list the current working directory again. This demonstrates that the session has been maintained between the Invoke-SSH calls because a new connection would start in the home directory. Assume that the shellprompt for the server is “test>”.
PS> $conn = Connect-SSH -Server myserver -User myuser -Password mypassword
-ShellPrompt "test>"
Do you want to trust the certificate presented?
The server has presented the key below.
Fingerprint: 59:52:C8:DB:C8:3A:FE:CF:9D:02:E3:31:3A:2C:11:E4
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y
PS> Invoke-SSH -Connection $conn -Command "pwd"
Text EOL
---- ---
/home/test... True
test> False
PS> Invoke-SSH -Connection $conn -Command "cd SomeDir"
Text EOL
---- ---
test> False
PS> Invoke-SSH -Connection $conn -Command "pwd"
Text EOL
---- ---
/home/test/SomeDir... True
test> False
PS> Disconnect-SSH -Connection $conn
It should also be noted that the -ShellPrompt parameter can be specified in the Invoke-SSH cmdlet in case a command that you are executing causes the shell prompt to change. For example, see the following script.
PS> $conn = Connect-SSH -Server myserver -User myuser -Password mypassword
-ShellPrompt "test>"
Do you want to trust the certificate presented?
The server has presented the key below.
Fingerprint: 59:52:C8:DB:C8:3A:FE:CF:9D:02:E3:31:3A:2C:11:E4
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y
PS> Invoke-SSH -Connection $conn -Command "ChangeShellPromptCommand" -ShellPrompt "NewPrompt>"
Text EOL
---- ---
NewPrompt> False
Failure to specify the new shell prompt when you execute a command that changes the prompt will result in a time out error as the cmdlet will not recognize the new prompt.
We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.