Friday, February 24, 2017

Take it Easy: How to Automate SSH-ing with Powershell

Being away from blogging a while, since I have been on vacation after my VCP exam, now it's time back to my blogging. Today let's see how we can automate SSH-ing with powershell. Instead of connecting to each ssh hosts (eg, your routers/switches or linux servers), you can make the powershell snippets and insert the linux commands with plink.exe. Most of the time, you can use 2 methods to do ssh connection via powershell. You can use either of these methods.
1) Using plink.exe which is a command line version of putty.
2) Using one of the SSH Powershell Modules which are available on Powershell Gallery


There are other ssh modules and I use this SSH-Sessions Module written by Joakim Svendsen which uses SSH.NET library & Microsoft .Net framework.
Here, I use 2 linux hosts which are running ssh services. I use Windows 10 and Windows 7 with Powershell base version to connect to these hosts. The IP addresses in my lab are:
Host Names         IP Addresses
=======          ========
example1.local     10.170.0.50
example2.local     10.170.0.51
Windows10.local  10.170.0.10
Windows7.local    10.170.0.11
1) Using Plink.exe
Using Plink.exe is simple and straight-forward. You can download latest version of plink.exe from here. Both password and Key Authentication are supported. Now I'm going to do it with the password. (Key Auth is the same with different parameters. If you use this, you need to generate key with puttygen.exe and copy public key to ssh hosts.)


You need to put the plink.exe in the current powershell directory (here C:\psTest). The command is:
Get-Content .\linux_servers.txt | foreach { Invoke-Command -Command { & echo y | .\plink.exe $_ -l root -pw 'SDAF^&^' -P 22 -m myLinuxScript.txt; Write-Host -fore yellow "$_ host finished." }}


I'll explain each parameter in this command.
Get-Content  .\linux_server.txt => Read the IP addresses or hostnames from linux_servers.txt file. You need to put these IP addresses line-by-line in this file in the same directory as plink.exe.


& .\plink.exe "root@$_" -l root -pw 'SDAF^&^' -P 22 -m myLinuxScript;   => This will ssh the each host with root user account (-l option) and password SDAF^&^ and port 22. All ssh commands written in myLinuxScript are executed. I put the following command in this txt file.
service sshd status
See Fig-1.
Fig-1: Using plink.exe for Powershell ssh-ing

2) Using the SSH modules written from SSH.NET Library
This powershell module is written by Joakim Svendsen using the library written in .Net 4.0 which is hosted in CodePlex.
If you have Windows Management Framework 5 or higher (WMF 5 is available for Windows 7 and up), you can install this module from the PowerShell gallery (A Microsoft Online Repository for Powershell). The WMF 5.0 is installed on Windows 10 by default.
Now, I am going to test on my Windows 10 machine. I will also test on my Windows 7 machine later in this article.


1) Install SSH from Powershell Gallery. Since my machine is Windows 10 you can find and install modules with:
Find-Module *ssh*
Now, we can install our chosen SSH Module.
Install-Module SSHSessions
It will prompt you to install from untrusted repository (use it at your own risk). You will also need to open powershell from elevated command prompt or otherwise error occurs. See Fig-2.
Fig-2: Install SSHSession Powershell Module
2) You can do new ssh connections with
New-SshSessions -ComputerName 10.170.0.50 -Credential (Get-Credential)
It will prompt you for ssh username & password.
You can check the current connected ssh sessions wit
Get-SshSession


3) To enter interactive ssh shell, use the following command
Enter-SshSession -ComputerName 10.170.0.50
Now, you can type ssh commands in linux shell. Type exit to exit from shell.


4) You can remove the current ssh session by this command.
Remove-SshSession -ComputerName 10.170.0.50
Alternatively you can remove all currently connected ssh sessions by this command.
Remove-SshSessions -RemoveAll
Check Fig-3 for your reference.
Fig-3: Interactive SSH session in Powershell
4) You can also simultaneously run a command on multiple servers/devices. Just use the command:
Invoke-SshCommand -Command "user add MyUser-1" -InvokeOnAll -Quiet
This will create the user 'MyUser-1' on both linux servers. See Fig-4.
Fig-4: Running commands on multiple hosts

For my Windows 7 machine, there are 2 modules each available for different .Net framework versions (3.5 and 4.0, check the author's article for respective download zip file.
For me, I tested with Windows 7 with .Net 4.0 and so I downloaded and use SSH-SessionsPSv3.zip file. You will need to install .Net Framework 4.0 first, then you continue the next steps.


1) Copy your downloaded file to your module directory. Usually, it is C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules. See Fig-5.
Fig-5: Copy SSHSessions Module to default Module Directory
2) Import the modules into current powershell session.
Import-Module SSHSessions
The next commands are the same as I tested on my Windows 10 machine except step 2 where you cannot use -Credential parameter because it is unsupported until the module v1.6 in Powershell Gallery. So, you have to use the explicit username & password when you make a new connection. See Fig-6 for complete test.
Fig-6: Running commands on multiple hosts

3 comments:

  1. You can bypass SSH key cache message by echo y | .\plink.exe user@myserver.com -pm mypassword < command.txt >log.txt

    <command.txt to input multiple command in the file and pass it to plink.

    It works like a charm. I will give a try this SSH module a go too.

    ReplyDelete
  2. نوعی از میزبانی وب از جمله اقتصادی ترین نوع روش های وب هاستینگ است. در این روش چندین وب سایت روی یک سرور مستقر هستند که تعداد آنها ممکن است به هزاران وب سایت برسد. گفتنی است خرید هاست اشتراکی ارزان این روش به میزبانی مجازی یا میزبانی مشتق شده نیز شناخته شده است. هاست پرسرعت برای وردپرس بیشترین وب سایت‌ها در اینترنت از این سرویس استفاده میکنند. این سرویس میتواند مدیریت شده یا مدیریت نشده باشد که سرویس مدیریت شده آن پشتیبانی بهتری ارائه می دهد.

    ReplyDelete

Note: Only a member of this blog may post a comment.