使用GCloud Function打开SSH连接以访问SFTP服务器的方法是什么?
时间:2024-02-16
浏览:232
作者:佚名
哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《使用GCloud Function打开SSH连接以访问SFTP服务器的方法是什么?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
问题内容
我的设置需要 google 函数来执行一些操作并将结果上传到 sftp 服务器。我目前正在使用基本的 sftp 和 crypto/ssh 包来实现此目的。在本地,经过一些调试,我能够检索服务器的公钥。
当然,部署到 gcloud 时没有任何效果。
这就是处理我的函数上的连接
func Connect(host string, port string, user string, password string) (*ssh.Client, error) {
hostKey := getHostKey(host)
var auths []ssh.AuthMethod
// Use password authentication if provided
if password != "" {
auths = append(auths, ssh.Password(password))
}
config := &ssh.ClientConfig{
User: user,
HostKeyCallback: ssh.FixedHostKey(hostKey),
Auth: auths,
}
cipherOrder := config.Ciphers
config.Ciphers = append(cipherOrder, "aes128-cbc", "3des-cbc")
sshConn, err := ssh.Dial("tcp", host+":"+port, config)
if err != nil {
return nil, err
}
return sshConn, nil
}
func getHostKey(host string) ssh.PublicKey {
file, err := os.Open("/root/.ssh/known_hosts")
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to read known_hosts file: %v\n", err)
os.Exit(1)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) != 3 {
continue
}
if strings.Contains(fields[0], host) {
var err error
hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing %q: %v\n", fields[2], err)
os.Exit(1)
}
break
}
}
if hostKey == nil {
fmt.Fprintf(os.Stderr, "No hostkey found for %s", host)
os.Exit(1)
}
return hostKey
}
known_hosts 文件不存在。我没有服务器的公钥,但使用 filezilla 我可以很好地连接到它。
我必须指定这些密码,因为准系统 ssh 主机名 会返回 unable to negotiate... 错误
还有其他方法可以做到这一点吗?我正在考虑上传我自己的 known_hosts 文件,但这听起来不是一个很好的解决方案。
正确答案
我可能过度设计它了。
像这样设置 ssh.clientconfig 解决了问题:
config := &ssh.clientconfig{
user: user,
auth: auths,
hostkeycallback: ssh.insecureignorehostkey(),
}
无论如何,我还找到了一个更好的软件包来轻松处理 ssh 连接,simplessh。
conn, _ := simplessh.ConnectWithPassword(host, user, pass) client, _ := sftp.NewClient(conn.SSHClient)
今天关于《使用GCloud Function打开SSH连接以访问SFTP服务器的方法是什么?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
