Invoking commands in Linux systems via SSH with the help of Powershell

Invoking commands in Linux systems via SSH with the help of Powershell

In one of my projects, I was needed to write a script that will send SMS messages. We already had Linux server with GSM-modem that accepted commands sent by SSH. So, I was only needed to connect from Windows system to Linux with SSH protocol.

I tried to use the SSH-Session module for Powershell, but it have some issues when sending commands. So I started to work with Posh-SSH module.

 

Lets install Posh-SSH:

 

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

Downloading latest version of Posh-SSH from https://github.com/darkoperator/Posh-SSH/archive/master.zip
File saved to C:\Users\user1\AppData\Local\Temp\Posh-SSH.zip
Uncompressing the Zip file to C:\Users\user1\Documents\WindowsPowerShell\Modules
Renaming folder
Module has been installed

 

Restart Powershell session and try to add module into environment:

Import-Module posh-ssh

For my task I needed the following commands:

  • New-SSHSession
  • Invoke-SshCommand
  • Get-SSHSession
  • Remove-SshSession

From the names of commands it's clear what they do: initialize connection to SSH server, invoke command, get object of connection, close connection.

 

New-SSHSession need credentials to connect, so you must get them with Get-Credential commandlet.

Here is my simple construction for using of module:

Import-Module posh-ssh;

$credential = Get-Credential;
New-SSHSession -ComputerName 10.11.12.201 -Credential $credential;

Invoke-SshCommand -index 0 -Command ;
# -index 0 - thats id of connection. Usually 0. You can get this id with Get-SSHSession.

Get-SSHSession | Remove-SshSession;

script (en), powershell (en)

  • Hits: 10564
Add comment

Related Articles