首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SSH连接超时

SSH连接超时
EN

Stack Overflow用户
提问于 2015-07-22 05:00:44
回答 2查看 9.2K关注 0票数 14

我正在尝试使用golang.org/x/crypto/ssh来建立SSH连接,但我感到有点惊讶的是,我似乎无法找到如何超时NewSession函数(实际上我没有看到任何超时的方法)。当我试图连接到有问题的服务器时,它只挂了很长一段时间。我写了一些东西来使用select和一个time.After,但感觉就像一个黑客。我还没有尝试过的是将底层的net.Conn保存在结构中,然后继续执行Conn.SetDeadline()调用。还没有尝试过这一点,因为我不知道是否密码/ssh库覆盖了这个或类似的东西。

有谁能很好地用这个库超时死服务器?还是有人知道更好的图书馆?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-22 14:38:08

使用ssh包透明地处理此问题的一种方法是通过自定义net.Conn为您设置截止日期,从而创建具有空闲超时的连接。但是,这将导致后台读取到超时的连接,因此我们需要使用ssh保生命来保持连接处于打开状态。根据您的用例,只需使用ssh持活条作为死连接的警报就足够了。

代码语言:javascript
复制
// Conn wraps a net.Conn, and sets a deadline for every read
// and write operation.
type Conn struct {
    net.Conn
    ReadTimeout  time.Duration
    WriteTimeout time.Duration
}

func (c *Conn) Read(b []byte) (int, error) {
    err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
    if err != nil {
        return 0, err
    }
    return c.Conn.Read(b)
}

func (c *Conn) Write(b []byte) (int, error) {
    err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
    if err != nil {
        return 0, err
    }
    return c.Conn.Write(b)
}

然后,您可以使用net.DialTimeoutnet.Dialer来获取连接,并将其包装在Conn中,并将其传递给ssh.NewClientConn

代码语言:javascript
复制
func SSHDialTimeout(network, addr string, config *ssh.ClientConfig, timeout time.Duration) (*ssh.Client, error) {
    conn, err := net.DialTimeout(network, addr, timeout)
    if err != nil {
        return nil, err
    }

    timeoutConn := &Conn{conn, timeout, timeout}
    c, chans, reqs, err := ssh.NewClientConn(timeoutConn, addr, config)
    if err != nil {
        return nil, err
    }
    client := ssh.NewClient(c, chans, reqs)

    // this sends keepalive packets every 2 seconds
    // there's no useful response from these, so we can just abort if there's an error
    go func() {
        t := time.NewTicker(2 * time.Second)
        defer t.Stop()
        for range t.C {
            _, _, err := client.Conn.SendRequest("keepalive@golang.org", true, nil)
            if err != nil {
                return
            }
        }
    }()
    return client, nil
}
票数 19
EN

Stack Overflow用户

发布于 2017-08-19 04:28:01

ssh.ClientConfig上设置超时。

代码语言:javascript
复制
cfg := ssh.ClientConfig{
    User: "root",
    Auth: []ssh.AuthMethod{
        ssh.PublicKeys(signer),
    },
    HostKeyCallback: ssh.FixedHostKey(hostKey),
    Timeout:         15 * time.Second, // max time to establish connection
}

ssh.Dial("tcp", ip+":22", &cfg)

当您调用ssh.Dial时,超时将传递给net.DialTimeout

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31554196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档