本文整理汇总了Golang中golang.org/x/crypto/ssh.NewClientConn函数的典型用法代码示例。如果您正苦于以下问题:Golang NewClientConn函数的具体用法?Golang NewClientConn怎么用?Golang NewClientConn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewClientConn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Dial
func (config BeaconConfig) Dial() (*ssh.Client, error) {
workerPrivateKeyBytes, err := ioutil.ReadFile(string(config.WorkerPrivateKey))
if err != nil {
return nil, fmt.Errorf("failed to read worker private key: %s", err)
}
workerPrivateKey, err := ssh.ParsePrivateKey(workerPrivateKeyBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse worker private key: %s", err)
}
tsaAddr := fmt.Sprintf("%s:%d", config.Host, config.Port)
conn, err := net.DialTimeout("tcp", tsaAddr, 10*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to connect to TSA:", err)
}
clientConfig := &ssh.ClientConfig{
User: "beacon", // doesn't matter
HostKeyCallback: config.checkHostKey,
Auth: []ssh.AuthMethod{ssh.PublicKeys(workerPrivateKey)},
}
clientConn, chans, reqs, err := ssh.NewClientConn(conn, tsaAddr, clientConfig)
if err != nil {
return nil, fmt.Errorf("failed to construct client connection:", err)
}
return ssh.NewClient(clientConn, chans, reqs), nil
}
示例2: executeCmd
func executeCmd(cmd, hostname string, config *ssh.ClientConfig, timeout time.Duration) (string, error) {
// Dial up TCP connection to remote machine.
conn, err := net.Dial("tcp", hostname+":22")
if err != nil {
return "", fmt.Errorf("Failed to ssh connect to %s. Make sure \"PubkeyAuthentication yes\" is in your sshd_config: %s", hostname, err)
}
defer util.Close(conn)
util.LogErr(conn.SetDeadline(time.Now().Add(timeout)))
// Create new SSH client connection.
sshConn, sshChan, req, err := ssh.NewClientConn(conn, hostname+":22", config)
if err != nil {
return "", fmt.Errorf("Failed to ssh connect to %s: %s", hostname, err)
}
// Use client connection to create new client.
client := ssh.NewClient(sshConn, sshChan, req)
// Client connections can support multiple interactive sessions.
session, err := client.NewSession()
if err != nil {
return "", fmt.Errorf("Failed to ssh connect to %s: %s", hostname, err)
}
var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf
if err := session.Run(cmd); err != nil {
return "", fmt.Errorf("Errored or Timeout out while running \"%s\" on %s: %s", cmd, hostname, err)
}
return stdoutBuf.String(), nil
}
示例3: sshOnConn
func sshOnConn(conn net.Conn, h conf.Host) (*ssh.Client, error) {
var auths []ssh.AuthMethod
if h.Pass != "" {
auths = append(auths, ssh.Password(h.Pass))
auths = append(auths, ssh.KeyboardInteractive(kbdInteractive(h.Pass)))
}
if h.Key != "" {
k := &keyring{}
err := k.loadPEM([]byte(h.Key))
if err != nil {
return nil, err
}
for _, k := range k.keys {
s, _ := ssh.NewSignerFromKey(k)
auths = append(auths, ssh.PublicKeys(s))
}
}
config := &ssh.ClientConfig{
User: h.User,
Auth: auths,
}
debugln("handshake & authenticate")
cc, nc, reqs, err := ssh.NewClientConn(conn, conn.RemoteAddr().String(), config)
if err != nil {
return nil, err
}
client := ssh.NewClient(cc, nc, reqs)
return client, nil
}
示例4: SSHDialTimeout
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 {
<-t.C
if _, _, err := client.Conn.SendRequest("[email protected]", true, nil); err != nil {
return
}
}
}()
return client, nil
}
示例5: reconnect
func (c *comm) reconnect() (err error) {
if c.conn != nil {
c.conn.Close()
}
// Set the conn and client to nil since we'll recreate it
c.conn = nil
c.client = nil
c.conn, err = c.config.Connection()
if err != nil {
// Explicitly set this to the REAL nil. Connection() can return
// a nil implementation of net.Conn which will make the
// "if c.conn == nil" check fail above. Read here for more information
// on this psychotic language feature:
//
// http://golang.org/doc/faq#nil_error
c.conn = nil
log.Printf("reconnection error: %s", err)
return
}
sshConn, sshChan, req, err := ssh.NewClientConn(c.conn, c.address, c.config.SSHConfig)
if err != nil {
log.Printf("handshake error: %s", err)
}
if sshConn != nil {
c.client = ssh.NewClient(sshConn, sshChan, req)
}
c.connectToAgent()
return
}
示例6: DialClient
//DialClient returns two channels where one returns a ssh.Client and the other and error
func DialClient(dial, expire time.Duration, ip string, conf *ssh.ClientConfig, retry <-chan struct{}) (*ssh.Client, error) {
flux.Report(nil, fmt.Sprintf("MakeDial for %s for dailing at %+s and expiring in %+s", conf.User, dial, expire))
cons := make(chan *ssh.Client)
errs := make(chan error)
var con net.Conn
var sc ssh.Conn
var chans <-chan ssh.NewChannel
var req <-chan *ssh.Request
var err error
flux.GoDefer("MakeDial", func() {
con, err = net.DialTimeout("tcp", ip, dial)
if err != nil {
flux.Report(err, fmt.Sprintf("MakeDial:Before for %s net.DailTimeout", ip))
errs <- err
return
}
sc, chans, req, err = ssh.NewClientConn(con, ip, conf)
if err != nil {
flux.Report(err, fmt.Sprintf("MakeDial:After for %s ssh.NewClientConn", ip))
errs <- err
return
}
flux.Report(nil, fmt.Sprintf("MakeDial initiating NewClient for %s", ip))
cons <- ssh.NewClient(sc, chans, req)
return
})
expiration := threshold(expire)
go func() {
for _ = range retry {
expiration = threshold(expire)
}
}()
select {
case err := <-errs:
flux.Report(err, fmt.Sprintf("NewClient Ending!"))
return nil, err
case som := <-cons:
flux.Report(nil, fmt.Sprintf("NewClient Created!"))
expiration = nil
return som, nil
case <-expiration:
flux.Report(nil, fmt.Sprintf("MakeDial Expired for %s!", ip))
defer con.Close()
if sc != nil {
sc.Close()
}
return nil, ErrTimeout
}
}
示例7: connect
func connect(username, host string, authMethod ssh.AuthMethod, timeout time.Duration) (*Client, error) {
if username == "" {
user, err := user.Current()
if err != nil {
return nil, fmt.Errorf("Username wasn't specified and couldn't get current user: %v", err)
}
username = user.Username
}
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{authMethod},
}
host = addPortToHost(host)
conn, err := net.DialTimeout("tcp", host, timeout)
if err != nil {
return nil, err
}
sshConn, chans, reqs, err := ssh.NewClientConn(conn, host, config)
if err != nil {
return nil, err
}
client := ssh.NewClient(sshConn, chans, reqs)
c := &Client{SSHClient: client}
return c, nil
}
示例8: NewRemotePassAuthRunnerWithTimeouts
// NewRemotePassAuthRunnerWithTimeouts is one of functions for creating remote
// runner. Use this one instead of NewRemotePassAuthRunner if you need to setup
// nondefault timeouts for ssh connection
func NewRemotePassAuthRunnerWithTimeouts(
user, host, password string, timeouts Timeouts,
) (*Remote, error) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(password)},
}
dialer := net.Dialer{
Timeout: timeouts.ConnectionTimeout,
Deadline: time.Now().Add(timeouts.ConnectionTimeout),
KeepAlive: timeouts.KeepAlive,
}
conn, err := dialer.Dial("tcp", host)
if err != nil {
return nil, err
}
connection := &timeBoundedConnection{
Conn: conn,
readTimeout: timeouts.SendTimeout,
writeTimeout: timeouts.ReceiveTimeout,
}
sshConnection, channels, requests, err := ssh.NewClientConn(
connection, host, config,
)
if err != nil {
return nil, err
}
return &Remote{ssh.NewClient(sshConnection, channels, requests)}, nil
}
示例9: TryDial
func (s *server) TryDial(config *ssh.ClientConfig) (*ssh.Client, error) {
sshd, err := exec.LookPath("sshd")
if err != nil {
s.t.Skipf("skipping test: %v", err)
}
c1, c2, err := unixConnection()
if err != nil {
s.t.Fatalf("unixConnection: %v", err)
}
s.cmd = exec.Command(sshd, "-f", s.configfile, "-i", "-e")
f, err := c2.File()
if err != nil {
s.t.Fatalf("UnixConn.File: %v", err)
}
defer f.Close()
s.cmd.Stdin = f
s.cmd.Stdout = f
s.cmd.Stderr = &s.output
if err := s.cmd.Start(); err != nil {
s.t.Fail()
s.Shutdown()
s.t.Fatalf("s.cmd.Start: %v", err)
}
s.clientConn = c1
conn, chans, reqs, err := ssh.NewClientConn(c1, "", config)
if err != nil {
return nil, err
}
return ssh.NewClient(conn, chans, reqs), nil
}
示例10: DialSSHTimeout
func DialSSHTimeout(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 := &SSHConn{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 3 seconds
// there's no useful response from these, so we can just abort if there's an error
go func() {
t := time.NewTicker(KEEPALIVE_INTERVAL)
defer t.Stop()
for {
<-t.C
_, _, err := client.Conn.SendRequest("[email protected]", true, nil)
if err != nil {
log.Fatalf("Remote server did not respond to keepalive.")
return
}
}
}()
return client, nil
}
示例11: reconnect
func (c *comm) reconnect() error {
// Close previous connection.
if c.conn != nil {
c.Close()
}
var err error
c.conn, err = c.config.Connection()
if err != nil {
// Explicitly set this to the REAL nil. Connection() can return
// a nil implementation of net.Conn which will make the
// "if c.conn == nil" check fail above. Read here for more information
// on this psychotic language feature:
//
// http://golang.org/doc/faq#nil_error
c.conn = nil
c.config.Logger.Error("reconnection error", "error", err)
return err
}
sshConn, sshChan, req, err := ssh.NewClientConn(c.conn, c.address, c.config.SSHConfig)
if err != nil {
c.config.Logger.Error("handshake error", "error", err)
c.Close()
return err
}
if sshConn != nil {
c.client = ssh.NewClient(sshConn, sshChan, req)
}
c.connectToAgent()
return nil
}
示例12: reconnect
func (ctx *ExecContext) reconnect() (err error) {
if ctx.hostname != "" {
ctx.isReconnecting = true
username := ctx.username
addr := fmt.Sprintf("%s:%d", ctx.hostname, ctx.port)
ctx.unlock()
agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
ctx.lock()
ctx.isReconnecting = false
return err
}
defer agentConn.Close()
ag := agent.NewClient(agentConn)
auths := []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)}
config := &ssh.ClientConfig{
User: username,
Auth: auths,
}
conn, err := net.DialTimeout("tcp", addr, networkTimeout)
if err != nil {
ctx.lock()
ctx.isReconnecting = false
return err
}
timeoutConn := &Conn{conn, networkTimeout, networkTimeout}
c, chans, reqs, err := ssh.NewClientConn(timeoutConn, addr, config)
if err != nil {
ctx.lock()
ctx.isReconnecting = false
return err
}
client := ssh.NewClient(c, chans, reqs)
// Send periodic keepalive messages
go func() {
t := time.NewTicker(networkTimeout / 2)
defer t.Stop()
for {
<-t.C
_, _, err := client.Conn.SendRequest("[email protected]", true, nil)
if err != nil {
ctx.lock()
if ctx.sshClient == client {
ctx.isConnected = false
}
ctx.unlock()
return
}
}
}()
ctx.lock()
ctx.isReconnecting = false
ctx.sshClient = client
}
ctx.isConnected = true
return nil
}
示例13: dialWithTimeout
// The function ssh.Dial doesn't have timeout mechanism for dial so this function is used
func dialWithTimeout(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
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}
示例14: DialThrough
// DialThrough will create a new connection from the ssh server sc is connected to. DialThrough is an SSHDialer.
func (sc *SSHClient) DialThrough(net, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {
conn, err := sc.conn.Dial(net, addr)
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}
示例15: dial
func (opts *sshOpts) dial(config *ssh.ClientConfig) (*ssh.Client, error) {
addr := opts.Hostname + ":" + strconv.Itoa(opts.Port)
timeout := opts.Timeout * float64(time.Second)
conn, err := net.DialTimeout("tcp", addr, time.Duration(timeout))
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}