-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnect-SSHTunnel.ps1
More file actions
229 lines (209 loc) · 6.88 KB
/
Copy pathConnect-SSHTunnel.ps1
File metadata and controls
229 lines (209 loc) · 6.88 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Target,
[Parameter(Position = 1)]
[string]$RemotePort = "3306",
[Parameter(Position = 2)]
[int]$LocalPort = 0,
[Parameter()]
[string]$RemoteHost = "localhost"
)
# Load config
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$scriptDir\Get-ScriptConfig.ps1"
$config = Get-ScriptConfig
if (-not $config) {
Write-Host "Please configure config.json before using SSH commands." -ForegroundColor Red
exit 1
}
# Get servers from config
$servers = @{}
$serverKeyFiles = @{}
$serverUsers = @{}
if ($config.ssh.servers) {
foreach ($key in $config.ssh.servers.PSObject.Properties.Name) {
$servers[$key] = $config.ssh.servers.$key.hostname
if ($config.ssh.servers.$key.keyFile) {
$serverKeyFiles[$key] = $config.ssh.servers.$key.keyFile
}
if ($config.ssh.servers.$key.user) {
$serverUsers[$key] = $config.ssh.servers.$key.user
}
}
}
# Get database ports from config
$dbPorts = @{}
if ($config.ssh.databasePorts) {
foreach ($key in $config.ssh.databasePorts.PSObject.Properties.Name) {
$dbPorts[$key] = $config.ssh.databasePorts.$key
}
}
# If RemotePort is passed as a named DB type, resolve it
if ($dbPorts.ContainsKey($RemotePort.ToLower())) {
$RemotePort = $dbPorts[$RemotePort.ToLower()]
if ($LocalPort -eq 0) {
$LocalPort = $RemotePort
}
}
else {
# Try to parse as integer
try {
$RemotePort = [int]$RemotePort
}
catch {
Write-Host "Invalid port: $RemotePort" -ForegroundColor Red
Write-Host "Use a port number or one of: $($dbPorts.Keys -join ', ')" -ForegroundColor Yellow
exit 1
}
}
# Set local port if not specified
if ($LocalPort -eq 0) {
$LocalPort = $RemotePort
}
# Resolve hostname, key file, and user
$keyFile = $null
$configUser = $null
if ($servers.ContainsKey($Target)) {
$Server = $servers[$Target]
if ($serverKeyFiles.ContainsKey($Target)) {
$keyFile = $serverKeyFiles[$Target]
}
if ($serverUsers.ContainsKey($Target)) {
$configUser = $serverUsers[$Target]
}
}
else {
$Server = $Target
}
# Get credentials directory
$credsDir = Join-Path $scriptDir "creds"
# Check for key file authentication
$keyFilePath = $null
if ($keyFile) {
# Support both absolute paths and relative paths (in creds directory)
if ([System.IO.Path]::IsPathRooted($keyFile)) {
$keyFilePath = $keyFile
}
else {
$keyFilePath = Join-Path $credsDir $keyFile
}
if (-not (Test-Path $keyFilePath)) {
Write-Host "Key file not found: $keyFilePath" -ForegroundColor Red
exit 1
}
}
# Get password credentials (not needed if using key file)
$username = $null
$password = $null
$cred = $null
if (-not $keyFile) {
$credFile = $config.ssh.credentialFile
if (-not $credFile) {
$credFile = "ssh-credentials.xml"
}
$credPath = Join-Path $credsDir $credFile
if (-not (Test-Path $credPath)) {
Write-Host "Credential file not found: $credPath" -ForegroundColor Red
exit 1
}
$cred = Import-Clixml $credPath
$username = $cred.UserName
$password = $cred.GetNetworkCredential().Password
}
else {
# For key file auth, we need a username from config or credential file
if ($configUser) {
$username = $configUser
}
else {
$credFile = $config.ssh.credentialFile
if ($credFile) {
$credPath = Join-Path $credsDir $credFile
if (Test-Path $credPath) {
$cred = Import-Clixml $credPath
$username = $cred.UserName
}
}
}
if (-not $username) {
Write-Host "Username required. Add 'user' to server config in config.json" -ForegroundColor Red
exit 1
}
}
Write-Host "Tunnel: localhost:$LocalPort -> ${RemoteHost}:${RemotePort} (via $Server)" -ForegroundColor Cyan
# Detect available SSH backends
$useWSL = $false
$wsl = Get-Command wsl -ErrorAction SilentlyContinue
if ($wsl) {
$wslCheck = wsl echo "ok" 2>&1
if ($wslCheck -eq "ok") {
$useWSL = $true
}
}
# Use Windows native SSH for key-based auth (avoids WSL permission issues with /mnt/c paths)
if ($keyFile) {
$winSsh = Get-Command ssh.exe -ErrorAction SilentlyContinue
if ($winSsh) {
& ssh.exe -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -i $keyFilePath -N -L "${LocalPort}:${RemoteHost}:${RemotePort}" "$username@$Server"
}
elseif ($useWSL) {
$escapedPath = $keyFilePath -replace '\\', '/'
$wslKeyPath = (wsl wslpath -u "'$escapedPath'").Trim()
wsl bash -c "ssh -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -i '$wslKeyPath' -N -L ${LocalPort}:${RemoteHost}:${RemotePort} $username@$Server"
}
else {
try {
Import-Module Posh-SSH -ErrorAction Stop
$session = New-SSHSession -ComputerName $Server -KeyFile $keyFilePath -AcceptKey
New-SSHLocalPortForward -SSHSession $session -BoundHost "127.0.0.1" -BoundPort $LocalPort -RemoteAddress $RemoteHost -RemotePort $RemotePort | Out-Null
Start-Sleep -Seconds 999999
}
catch {
Write-Host "Tunnel setup failed: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
finally {
if ($session) {
Remove-SSHSession -SessionId $session.SessionId | Out-Null
}
}
}
}
elseif ($useWSL) {
$hasSshpass = wsl bash -c "command -v sshpass >/dev/null 2>&1 && echo 'yes' || echo 'no'"
if ($hasSshpass -match 'no') {
Write-Host "Installing sshpass in WSL..." -ForegroundColor Yellow
wsl bash -c "sudo apt-get update && sudo apt-get install -y sshpass"
}
wsl bash -c "SSHPASS='$password' sshpass -e ssh -o StrictHostKeyChecking=no -N -L ${LocalPort}:${RemoteHost}:${RemotePort} $username@$Server"
}
else {
$nativeSsh = Get-Command ssh.exe -ErrorAction SilentlyContinue
if ($nativeSsh) {
$sshArgs = @(
"-o", "StrictHostKeyChecking=no",
"-o", "IdentitiesOnly=yes",
"-N",
"-L", "${LocalPort}:${RemoteHost}:${RemotePort}",
"$username@$Server"
)
& ssh.exe @sshArgs
}
else {
try {
Import-Module Posh-SSH -ErrorAction Stop
$session = New-SSHSession -ComputerName $Server -Credential $cred -AcceptKey
New-SSHLocalPortForward -SSHSession $session -BoundHost "127.0.0.1" -BoundPort $LocalPort -RemoteAddress $RemoteHost -RemotePort $RemotePort | Out-Null
Start-Sleep -Seconds 999999
}
catch {
Write-Host "Tunnel setup failed: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
finally {
if ($session) {
Remove-SSHSession -SessionId $session.SessionId | Out-Null
}
}
}
}