How to Use Powershell Script to Execute Linux Shell -POSH


This article demonstrates how to use Powershell POSH-SSH module to login Linux Machine and Execute Shell Commands
Posh-SSH is a PowerShell module for Windows, which allows you to establish SSH connections as well as SCP functionality to remote computers. Let's dig in...

WHY?
I've been learning about AWS Linux instances and automation. I used Terraform for a spin up AWS instances and execute scripts. But, Also often think about what if create a web console to do such a task from local pc.
I will write how to automate AWS using Terraform Later. Now I'll show how to create a web console to execute Linux shell using PowerShell script.
To achieve this,
1. Create Powershell Script to SSH AWS Linux instances
2. Create ASP.NET web console

Create a PowerShell script - POSH

Step 01: To verify whether POSH-SSH installed
Find-Module Posh-SSH

Step 02:  Install Posh-SSH
Get-Command -Module Posh-SSH

Step 03: Once It's installed All you need to Know Posh CommandI'll Be Link all the POSH-SSH Command to Learn...
https://github.com/5sfayas/POSH-SHH


Since I did not create any web console yet, though, I'll add a Simple Powershell Script.
The below code will be changed as per the web console. So, Please  follow up the tutorial as I go

Write-Host "Please Enter your parameter to ping"
$cloud=Read-Host

#connect to controller

$nopasswd = new-object System.Security.SecureString
$Crendential= New-Object System.Management.Automation.PSCredential ("ubuntu", $nopasswd)
  
#SSH Session is created connect aws instance using private key
$ssh=New-SSHSession –ComputerName ec2-13-232-138-59.ap-south-1.compute.amazonaws.com -KeyFile 'D:\w\tom.pem' -Credential $Crendential


#Script which deployed in aws instance and which also take parameters
$command="sh new.sh $cloud"
Write-Host "Pinging....."

#This is Write the output to powershell
$result=Invoke-SSHCommand -SSHSession $ssh -Command $command | select Output -ExpandProperty Output | Out-String
Write-Host " Ping is: $result"

#End ssh session
$end_result=Remove-SSHSession -SSHSession $ssh

Let's Create Web Console To Exexute Shell

All you Have to do is insert parameter and click right away

Here's the ASP.NET code which was written in..

find this in repo  https://github.com/5sfayas/POSH-SHH/blob/master/POSH-SSH/Ping_Tool.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;

namespace Final_CloudApp
{
    public partial class Ping_Tool : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        //****Function start*****************
        public void ping(string cloud, string parameter)
        {

            //Location of the script
            string script = @cloud;
            TextBox3.Text = string.Empty;

            // Initialize PowerShell engine
            var shell = PowerShell.Create();

            // Add the script to the PowerShell object
            shell.Commands.AddCommand(script, false);

            //Name of the parameter as in the script
            shell.Commands.AddParameter("com1", source); //Parameter-0
            shell.Commands.AddParameter("com2", dest);//Parameter-1

            // Execute the script
            var results = shell.Invoke();

            // Note : use |out-string for console-like output
            if (results.Count > 0)
            {
                // We use a string builder ton create our result text
                var builder = new StringBuilder();

                foreach (var psObject in results)
                {
                    // Convert the Base Object to a string and append it to the string builder.
                    // Add \r\n for line breaks
                    builder.Append(psObject.BaseObject.ToString() + "\r\n");
                }

                // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
                // TextBox2.Text = Server.HtmlEncode(builder.ToString());
                TextBox3.Text = (builder.ToString());
            }

        }
        //Function Finish

        protected void Button1_Click(object sender, EventArgs e)
        {
           
                ping("C:\\D drive\\Ransara\\aws_ping.ps1", TextBox2.Text);
           
        }
    }
}



then fully modify your PowerShell script like below
find this in repo  https://github.com/5sfayas/POSH-SHH/blob/master/POSH-SSH/execute_shell1.ps1

[CmdletBinding()]
param(
    [parameter(position=0)]
    [string]$cloud,
)


#connect to controller

$nopasswd = new-object System.Security.SecureString
$Crendential= New-Object System.Management.Automation.PSCredential ("ubuntu", $nopasswd)
 
#SSH Session is created connect aws instance using private key
$ssh=New-SSHSession –ComputerName ec2-13-232-138-59.ap-south-1.compute.amazonaws.com -KeyFile 'D:\w\tom.pem' -Credential $Crendential
#Script which deployed in aws instance and which also take parameters
$command="sh new.sh $cloud"
Write-Host "Pinging....."

#This is Write the output to powershell
$result=Invoke-SSHCommand -SSHSession $ssh -Command $command | select Output -ExpandProperty Output | Out-String
Write-Host " Ping is: $result"

#End ssh session
$end_result=Remove-SSHSession -SSHSession $ssh
 
, , ,

No comments:

Post a Comment