【问题标题】:Establishing the connection to a Redshift cluster in a golang app, using ODBC via SSH tunnel (using the AWS Redshift ODBC Driver)使用 ODBC 通过 SSH 隧道(使用 AWS Redshift ODBC 驱动程序)在 golang 应用程序中建立与 Redshift 集群的连接
【发布时间】:2022-12-15 09:22:34
【问题描述】:
目标
我需要从我的 golang 应用程序查询 Redshift 集群。该集群不对公众开放,所以我想使用 SSH 通过堡垒主机访问所述集群。
现状
问题
这个问题非常微不足道。当集群可供公众使用并可从 Internet 访问时,alexbramain 的库将完成它的工作。然而,当集群位于墙后时,问题就来了。
库的代码被翻译成C(系统调用),我无法真正调试它。虽然,例如,使用 mysql 可以注册您的自定义拨号器,但 ODBC 似乎不是这种情况。
即使隧道处于活动状态,出于某种原因向本地主机提供 ODBC DSN 也不起作用。 SQLRETURN 始终为 -1 (api/zapi_unix.go)。
问题
有人有过这样的经历吗?您是如何解决通过 go 应用程序从互联网访问集群的问题的?
谢谢!
【问题讨论】:
标签:
go
ssh
network-programming
odbc
amazon-redshift
【解决方案1】:
听起来您正在尝试使用 SSH 隧道通过堡垒主机连接到您的 Redshift 集群。当集群不可公开访问时,这是一种常见的设置。
为了建立 SSH 隧道,您需要使用支持 SSH 隧道的库或工具。 Go 的此类库之一是 sshtunnel,您可以使用它来建立 SSH 隧道,然后使用该隧道通过 ODBC 驱动程序连接到您的 Redshift 集群。
下面是一个示例,说明如何使用 sshtunnel 和 ODBC 驱动程序建立 SSH 隧道并连接到 Redshift 集群:
// Import the sshtunnel and ODBC packages
import (
"github.com/alexbrainman/sshtunnel"
"github.com/alexbrainman/odbc"
)
func main() {
// Create an SSH tunnel to the bastion host
tunnel, err := sshtunnel.Open(
"localhost:5439", // The local port to bind the tunnel to
"bastion-host:22", // The bastion host and port
"user", // The SSH user
"ssh-key", // The SSH private key
)
if err != nil {
// Handle error
}
defer tunnel.Close() // Close the tunnel when done
// Connect to the Redshift cluster using the ODBC driver
db, err := odbc.Connect("DSN=Redshift", "", "")
if err != nil {
// Handle error
}
defer db.Close() // Close the connection when done
// Use the connection to query the Redshift cluster
rows, err := db.Query("SELECT * FROM table")
if err != nil {
// Handle error
}
defer rows.Close() // Close the rows when done
// Process the query results
// ...
}