• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ssh.NewClient函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/crypto/ssh.NewClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewClient函数的具体用法?Golang NewClient怎么用?Golang NewClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewClient函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: 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
}
开发者ID:ReinhardHsu,项目名称:platform,代码行数:32,代码来源:test_unix_test.go


示例2: 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
}
开发者ID:Jonty,项目名称:concourse-bin,代码行数:33,代码来源:beacon_config.go


示例3: 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
}
开发者ID:saltmueller,项目名称:skia-buildbot,代码行数:30,代码来源:ssh.go


示例4: 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
}
开发者ID:asimihsan,项目名称:arqinator,代码行数:28,代码来源:sftp.go


示例5: 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
}
开发者ID:quixoten,项目名称:vault,代码行数:33,代码来源:communicator.go


示例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
	}
}
开发者ID:influx6,项目名称:proxies,代码行数:61,代码来源:helpers.go


示例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
}
开发者ID:bvnarayan,项目名称:simplessh,代码行数:30,代码来源:simplessh.go


示例8: 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
}
开发者ID:vincentaubert,项目名称:vault,代码行数:33,代码来源:communicator.go


示例9: 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
}
开发者ID:LCLS,项目名称:GPUManager,代码行数:27,代码来源:SSHConnection.go


示例10: 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
}
开发者ID:s-kostyaev,项目名称:runcmd,代码行数:37,代码来源:remote.go


示例11: 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
}
开发者ID:calmh,项目名称:mole,代码行数:33,代码来源:ssh.go


示例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
}
开发者ID:tillberg,项目名称:bismuth,代码行数:59,代码来源:bismuth.go


示例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
}
开发者ID:cloudawan,项目名称:cloudone_utility,代码行数:12,代码来源:ssh_client.go


示例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

}
开发者ID:kureikain,项目名称:sup,代码行数:13,代码来源:ssh.go


示例15: Hop

func Hop(through *ssh.Client, toaddr string, c *ssh.ClientConfig) (*ssh.Client, error) {
	hopconn, err := through.Dial("tcp", toaddr)
	if err != nil {
		return nil, err
	}

	conn, chans, reqs, err := ssh.NewClientConn(hopconn, toaddr, c)
	if err != nil {
		return nil, err
	}

	return ssh.NewClient(conn, chans, reqs), nil
}
开发者ID:rwcarlsen,项目名称:cloudlus,代码行数:13,代码来源:condorbots.go


示例16: 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
}
开发者ID:hiroakis,项目名称:go-check-plugins,代码行数:13,代码来源:check-ssh.go


示例17: Dial

func (d *realSSHDialer) Dial(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {
	conn, err := net.DialTimeout(network, addr, config.Timeout)
	if err != nil {
		return nil, err
	}
	conn.SetReadDeadline(time.Now().Add(30 * time.Second))
	c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
	if err != nil {
		return nil, err
	}
	conn.SetReadDeadline(time.Time{})
	return ssh.NewClient(c, chans, reqs), nil
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:13,代码来源:ssh.go


示例18: NewClient

func NewClient(clientNetConn net.Conn, clientConfig *ssh.ClientConfig) *ssh.Client {
	if clientConfig == nil {
		clientConfig = &ssh.ClientConfig{
			User: "username",
			Auth: []ssh.AuthMethod{
				ssh.Password("secret"),
			},
		}
	}

	clientConn, clientChannels, clientRequests, clientConnErr := ssh.NewClientConn(clientNetConn, "0.0.0.0", clientConfig)
	Expect(clientConnErr).NotTo(HaveOccurred())

	return ssh.NewClient(clientConn, clientChannels, clientRequests)
}
开发者ID:Reejoshi,项目名称:cli,代码行数:15,代码来源:test_helpers.go


示例19: NewRemoteKeyAuthRunnerWithTimeouts

// NewRemoteKeyAuthRunnerWithTimeouts is one of functions for creating remote
// runner. Use this one instead of NewRemoteKeyAuthRunner if you need to setup
// nondefault timeouts for ssh connection
func NewRemoteKeyAuthRunnerWithTimeouts(
	user, host, key string, timeouts Timeouts,
) (*Remote, error) {
	if _, err := os.Stat(key); os.IsNotExist(err) {
		return nil, err
	}

	pemBytes, err := ioutil.ReadFile(key)
	if err != nil {
		return nil, err
	}

	signer, err := ssh.ParsePrivateKey(pemBytes)
	if err != nil {
		return nil, errors.New("can't parse pem data: " + err.Error())
	}

	config := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
	}

	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
}
开发者ID:s-kostyaev,项目名称:runcmd,代码行数:51,代码来源:remote.go


示例20: Client

func (c *Communicator) Client() (*ssh.Client, error) {
	if c.client != nil {
		return c.client, nil
	}

	// create ssh client.
	client, err := ssh.Dial("tcp", c.Config.HostOrDefault()+":"+c.Config.PortOrDefault(), c.ClientConfig)
	if err != nil {
		return nil, err
	}
	c.clientConns = append(c.clientConns, client)

	// If it has a upstream server?
	for c.UpstreamConfig != nil {
		// It is next server config to connect.
		var config *Config = nil

		// Does the upstream server need proxy to connet?
		proxy := c.UpstreamConfig.PopProxyConfig()
		if proxy != nil {
			config = proxy
		} else {
			config = c.UpstreamConfig
			c.UpstreamConfig = nil
		}

		// dial to ssh proxy
		connection, err := client.Dial("tcp", config.HostOrDefault()+":"+config.PortOrDefault())
		if err != nil {
			return nil, err
		}
		c.clientConns = append(c.clientConns, connection)

		conn, chans, reqs, err := ssh.NewClientConn(connection, config.HostOrDefault()+":"+config.PortOrDefault(), c.ClientConfig)
		if err != nil {
			return nil, err
		}
		client = ssh.NewClient(conn, chans, reqs)
		c.clientConns = append(c.clientConns, client)

		if err != nil {
			return nil, err
		}
	}

	c.client = client
	return c.client, nil
}
开发者ID:kohkimakimoto,项目名称:gluassh,代码行数:48,代码来源:communicator.go



注:本文中的golang.org/x/crypto/ssh.NewClient函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ssh.NewClientConn函数代码示例发布时间:2022-05-28
下一篇:
Golang ssh.MarshalAuthorizedKey函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap