forked from scriptrunner/ActionPacks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvoke-SSH.ps1
83 lines (71 loc) · 2.76 KB
/
Invoke-SSH.ps1
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
75
76
77
78
79
80
81
82
83
<#
.SYNOPSIS
Executes commands or shell scripts at a remote host via ssh batch mode.
.DESCRIPTION
Executes commands or shell scripts at a remote host via ssh batch mode.
.PARAMETER UserName
The user name that is used to authenticate at the remote host.
.PARAMETER RemoteHost
The machine name or IP address of the remote host.
.PARAMETER Commands
The commands to execute at the remote host.
.PARAMETER ShellScriptPath
EXPERIMENTAL: File path of the shell script at the ScriptRunner service host.
.PARAMETER Encoding
The encoding of the shell script file.
.PARAMETER PrintScriptContent
Display the content of shell script.
.PARAMETER Port
The port of ssh service at the remote host.
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[string]$UserName,
[Parameter(Mandatory=$true)]
[string]$RemoteHost,
[Parameter(Mandatory=$true, ParameterSetName='Commands')]
[string[]]$Commands,
[Parameter(Mandatory=$true, ParameterSetName='ShellScript')]
[string]$ShellScriptPath,
[Parameter(ParameterSetName='ShellScript')]
[string]$Encoding = 'UTF8',
[Parameter(ParameterSetName='ShellScript')]
[switch]$PrintScriptContent,
[ValidateRange(1,65535)]
[int]$Port = 22
)
if ($PSCmdlet.ParameterSetName -eq 'Commands'){
foreach ($command in $Commands) {
"$UserName@$RemoteHost `$ $command"
& cmd.exe '/c' "ssh.exe 2>&1 -p $Port -o `"BatchMode yes`" $UserName@$RemoteHost $command"
if($LASTEXITCODE -ne 0){
throw "SSH failed with ExitCode '$LASTEXITCODE'."
}
}
}
elseif ($PSCmdlet.ParameterSetName -eq 'ShellScript') {
if(Test-Path -Path $ShellScriptPath -ErrorAction SilentlyContinue){
"### E X P E R I M E N T A L ###"
$sh = Get-Content -Path $ShellScriptPath -Encoding $Encoding -Raw | ForEach-Object -Process { $_ -replace "`r`n","`n" }
$scriptName = (Split-Path -Path $ShellScriptPath -Leaf).Replace(" ", [string]::Empty)
$cmdSequence = "rm -fr ~/tmp_asr && mkdir -p ~/tmp_asr && cat >> ~/tmp_asr/$scriptName && sed -i 's/\r$//g' ~/tmp_asr/$scriptName && chmod +x ~/tmp_asr/$scriptName && ~/tmp_asr/$scriptName && rm -fr ~/tmp_asr"
if($PrintScriptContent.IsPresent){
"##### $scriptName #####"
$sh
"##### EOF '$scriptName' #####"
"`nRun $UserName@$RemoteHost `"$cmdSequence`" ...`n"
}
$sh | & ssh.exe -p $Port -o `"BatchMode yes`" $UserName@$RemoteHost "$cmdSequence"
if($LASTEXITCODE -ne 0){
throw "SSH failed with ExitCode '$LASTEXITCODE'."
}
}
else {
throw "Path '$ShellScriptPath' does not exist."
}
}
else{
throw "Invalid ParameterSet '$($PSCmdlet.ParameterSetName)'."
}