我正在尝试使用golang.org/x/crypto/ssh来建立SSH连接,但我感到有点惊讶的是,我似乎无法找到如何超时NewSession函数(实际上我没有看到任何超时的方法)。当我试图连接到有问题的服务器时,它只挂了很长一段时间。我写了一些东西来使用select和一个time.After,但感觉就像一个黑客。我还没有尝试过的是将底层的net.Conn保存在结构中,然后继续执行Conn.SetDeadline()调用。还没有尝试过这一点,因为我不知道是否密码/ssh库覆盖了这个或类似的东西。
有谁能很好地用这个库超时死服务器?还是有人知道更好的图书馆?
发布于 2015-07-22 14:38:08
使用ssh包透明地处理此问题的一种方法是通过自定义net.Conn为您设置截止日期,从而创建具有空闲超时的连接。但是,这将导致后台读取到超时的连接,因此我们需要使用ssh保生命来保持连接处于打开状态。根据您的用例,只需使用ssh持活条作为死连接的警报就足够了。
// 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.DialTimeout或net.Dialer来获取连接,并将其包装在Conn中,并将其传递给ssh.NewClientConn。
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
}发布于 2017-08-19 04:28:01
在ssh.ClientConfig上设置超时。
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。
https://stackoverflow.com/questions/31554196
复制相似问题