【问题标题】:How can I make my GCloud Function open a new SSH connection to consume a SFTP server?如何让我的 GCloud Function 打开新的 SSH 连接以使用 SFTP 服务器?
【发布时间】:2021-05-26 16:44:11
【问题描述】:

我的设置需要 Google 函数来执行一些操作并将结果上传到 SFTP 服务器。我目前正在使用基本的sftpcrypto/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 hostname 会返回 Unable to negotiate... 错误

还有其他方法可以做到这一点吗?我正在考虑上传我自己的 known_hosts 文件,但这听起来不是一个很好的解决方案。

【问题讨论】:

    标签: go ssh google-cloud-functions sftp


    【解决方案1】:

    我可能过度设计了它。

    像这样设置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)
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      相关资源
      最近更新 更多