One way to handle this transparently with the ssh package, is to create a connection with an idle timeout via a custom net.Conn
which sets deadlines for you. However, this will cause the background Reads on a connection to timeout, so we need to use ssh keepalives to keep the connection open. Depending on your use case, simply using ssh keepalives as an alert for a dead connection may suffice.
// 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)
}
You can then use net.DialTimeout
or a net.Dialer
to get the connection, wrap it in your Conn
with timeouts, and pass it into 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
}
NewClient()
with aConn
youSetDeadline()
on is The Way(tm). Commenting not answering 'cause I don't have special familiarity with thessh
package. The output ofgrep -R Deadline src/golang.org/x/crypto/ssh
makes me think the package won't get in your way but won't do it for you; the only mentions appear related to ssh port forwarding.SetDeadline()
works, but I gotta say something like a timeout missing from a library meant for making connections seems like a major oversight.. Not to sound ungrateful or anything and maybe if I have the time I will see if I can help include itssh.NewClientConn
at all nor does it return a nil Client. That is the main cause of my problem anyways, it is trying to callNewSession
with a dead server that is passing as alive.ssh.NewClientConn
returns ok, then the server isn't really dead since it can complete the ssh handshake.net/http
to write services returning JSON, and you can imagine convenience methods to make it easier to build those, butnet/http
(on its own) doesn't provide them;net/http
has to be hooked up toencoding/json
with other code.