SSH.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<#
    .SYNOPSIS
    Executes an SSH command using SSH.Net from http://sshnet.codeplex.com/
 
#>

function Invoke-SSHCommand {
    [CmdletBinding(DefaultParameterSetName='SpecifyConnectionFields', HelpUri='https://sshnet.codeplex.com/')]
    param(
        [Parameter(ParameterSetName='SpecifyConnectionFields', Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ComputerName,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [scriptblock]
        $ScriptBlock,

        [Parameter(ParameterSetName='SpecifyConnectionFields', Mandatory=$False)]
        [ValidateNotNullOrEmpty()]
        [int]
        $Port,

        [Parameter(ParameterSetName='SpecifyConnectionFields', Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [PSCredential]
        $Credential,

        [Parameter(Mandatory=$False)]
        [ValidateNotNullOrEmpty()]
        [String]
        $KeyString,

        [Parameter(ParameterSetName='UseConnectionObject', Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [Hashtable]
        $Connection
    )

    if($Connection) {
        $ComputerName = $Connection.ComputerName
        $Port = $Connection.Port
        $Password = $Connection.Password | ConvertTo-SecureString -asPlainText -Force
        if ($Connection.UserName -ne $null) { $Credential = New-Object System.Management.Automation.PSCredential($Connection.UserName, $Password)}
    }


    if(!$Port) {
        $Port = 22
    }

    if ($KeyString)
    {
        Write-Verbose "Using key file for authentication"
        $TempKeyFile = "$env:temp\id_rsa.key"
        Set-Content -Path $TempKeyFile -Value $KeyString  -Force | Write-Verbose
        $Key = New-Object Renci.SshNet.PrivateKeyFile($TempKeyFile)
        $SSHConnection = New-Object Renci.SshNet.SshClient($Computer, $Port, $Credential.UserName, $Key)
        Remove-Item -Path $TempKeyFile -force

    }
    else
    {
        Write-Verbose "Using password for authentication"
        $SSHConnection = New-Object Renci.SshNet.SshClient($ComputerName, $Port, $Credential.UserName, $Credential.GetNetworkCredential().Password)
    }

    $SSHConnection.Connect()
    $ResultObject = $SSHConnection.RunCommand($ScriptBlock.ToString())

    Write-Output $ResultObject
}

Export-ModuleMember *