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

Golang ssh.Dial函数代码示例

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

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



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

示例1: SSHClient

// SSHClient returns an ssh.Client object that could be used to ssh to the
// server. Requires that port 22 is accessible for SSH.
func (s *Server) SSHClient() (*ssh.Client, error) {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	if s.sshclient == nil {
		if s.provider.PrivateKey() == "" {
			log.Printf("resource file %s did not contain the ssh key\n", s.provider.savePath)
			return nil, errors.New("missing ssh key")
		}

		// parse private key and make config
		key, err := ssh.ParsePrivateKey([]byte(s.provider.PrivateKey()))
		if err != nil {
			log.Printf("failure to parse the private key: %s\n", err)
			return nil, err
		}
		sshConfig := &ssh.ClientConfig{
			User: s.UserName,
			Auth: []ssh.AuthMethod{
				ssh.PublicKeys(key),
			},
		}

		// dial in to the server, allowing certain errors that indicate that the
		// network or server isn't really ready for ssh yet; wait for up to
		// 5mins for success
		hostAndPort := s.IP + ":22"
		s.sshclient, err = ssh.Dial("tcp", hostAndPort, sshConfig)
		if err != nil {
			limit := time.After(5 * time.Minute)
			ticker := time.NewTicker(1 * time.Second)
		DIAL:
			for {
				select {
				case <-ticker.C:
					s.sshclient, err = ssh.Dial("tcp", hostAndPort, sshConfig)
					if err != nil && (strings.HasSuffix(err.Error(), "connection timed out") || strings.HasSuffix(err.Error(), "no route to host") || strings.HasSuffix(err.Error(), "connection refused")) {
						continue DIAL
					}
					// worked, or failed with a different error: stop trying
					ticker.Stop()
					break DIAL
				case <-limit:
					ticker.Stop()
					err = errors.New("giving up waiting for ssh to work")
					break DIAL
				}
			}
			if err != nil {
				return nil, err
			}
		}
	}
	return s.sshclient, nil
}
开发者ID:sb10,项目名称:vrpipe,代码行数:56,代码来源:cloud.go


示例2: Connect

func (S *SshParm) Connect() (*ssh.Client, error) {
	var (
		cfg *ssh.ClientConfig
	)

	if S.SSHAuthType == SSHAuthType_Certificate {
		cfg = &ssh.ClientConfig{
			User: S.SSHUser,
			Auth: []ssh.AuthMethod{
				PublicKeyFile(S.SSHKeyLocation),
			},
		}
	} else {
		cfg = &ssh.ClientConfig{
			User: S.SSHUser,
			Auth: []ssh.AuthMethod{
				ssh.Password(S.SSHPassword),
			},
		}
	}

	client, e := ssh.Dial("tcp", S.SSHHost, cfg)
	return client, e

}
开发者ID:arfian,项目名称:live,代码行数:25,代码来源:ssh.go


示例3: dialSuccess

func (client NativeClient) dialSuccess() bool {
	if _, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", client.Hostname, client.Port), &client.Config); err != nil {
		log.Debugf("Error dialing TCP: %s", err)
		return false
	}
	return true
}
开发者ID:jkingyens,项目名称:machine,代码行数:7,代码来源:client.go


示例4: waitForVmSsh

// Simply waits for ssh to come up
func waitForVmSsh(d *schema.ResourceData) error {
	l := log.New(os.Stderr, "", 0)

	l.Printf("Waiting for VM ssh: %s", d.Get("name"))

	config := &ssh.ClientConfig{
		User: "root",
		Auth: []ssh.AuthMethod{
			ssh.Password(d.Get("root_password").(string)),
		},
	}

	for {
		select {
		case <-time.After(waitForVM * time.Second):
			return fmt.Errorf("VM ssh wasn't up in %d seconds", waitForVM)
		case <-time.Tick(vmCheckInterval * time.Second):
			conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", d.Get("ipv4")), config)
			if err != nil {
				if strings.Contains(err.Error(), "connection refused") {
					l.Println("SSH isn't up yet")
					continue
				} else {
					l.Printf("SSH Error, ignored: %s", err.Error())
					continue
				}
			}
			conn.Close()
			l.Println("SSH alive and kicking")
			return nil
		}
	}

	return errors.New("Ssh wait should never get here")
}
开发者ID:thermeon,项目名称:terraform-provider-bigv,代码行数:36,代码来源:resource_vm.go


示例5: NewVagrantNode

//NewVagrantNode intializes a node in vagrant testbed
func NewVagrantNode(name, port, privKeyFile string) (*VagrantNode, error) {
	var (
		vnode      *VagrantNode
		err        error
		signer     ssh.Signer
		privateKey []byte
	)

	if privateKey, err = ioutil.ReadFile(privKeyFile); err != nil {
		return nil, err
	}

	if signer, err = ssh.ParsePrivateKey(privateKey); err != nil {
		return nil, err
	}

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

	vnode = &VagrantNode{Name: name}
	if vnode.client, err = ssh.Dial("tcp", fmt.Sprintf("127.0.0.1:%s", port), config); err != nil {
		return nil, err
	}

	return vnode, nil
}
开发者ID:balajisiva,项目名称:netplugin,代码行数:31,代码来源:vagrantnode.go


示例6: Init

func (this *Scp) Init(target_server, user, identity string) (*Scp, error) {

	this.Server = target_server
	this.User = user
	this.Identity = identity

	AuthKey, err := PublicKeyFile(this.Identity)

	if nil != err {
		return nil, err
	}

	this.clientConfig = &ssh.ClientConfig{
		User: this.User,
		Auth: []ssh.AuthMethod{AuthKey},
	}

	ParallelController[this.Server].Connection <- token
	this.client, err = ssh.Dial("tcp", this.Server+":22", this.clientConfig)

	if nil != err {
		return nil, errors.New("Failed to dial: " + err.Error())
	}

	return this, nil
}
开发者ID:krishna2nd,项目名称:goll,代码行数:26,代码来源:Scp.go


示例7: ExampleSession_RequestPty

func ExampleSession_RequestPty() {
	// Create client config
	config := &ssh.ClientConfig{
		User: "username",
		Auth: []ssh.AuthMethod{
			ssh.Password("password"),
		},
	}
	// Connect to ssh server
	conn, err := ssh.Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()
	// Create a session
	session, err := conn.NewSession()
	if err != nil {
		log.Fatalf("unable to create session: %s", err)
	}
	defer session.Close()
	// Set up terminal modes
	modes := ssh.TerminalModes{
		ssh.ECHO:          0,     // disable echoing
		ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}
	// Request pseudo terminal
	if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
		log.Fatalf("request for pseudo terminal failed: %s", err)
	}
	// Start remote shell
	if err := session.Shell(); err != nil {
		log.Fatalf("failed to start shell: %s", err)
	}
}
开发者ID:CodeJuan,项目名称:deis,代码行数:35,代码来源:example_test.go


示例8: ExampleDial

func ExampleDial() {
	// An SSH client is represented with a ClientConn. Currently only
	// the "password" authentication method is supported.
	//
	// To authenticate with the remote server you must pass at least one
	// implementation of AuthMethod via the Auth field in ClientConfig.
	config := &ssh.ClientConfig{
		User: "username",
		Auth: []ssh.AuthMethod{
			ssh.Password("yourpassword"),
		},
	}
	client, err := ssh.Dial("tcp", "yourserver.com:22", config)
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer session.Close()

	// Once a Session is created, you can execute a single command on
	// the remote side using the Run method.
	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("/usr/bin/whoami"); err != nil {
		panic("Failed to run: " + err.Error())
	}
	fmt.Println(b.String())
}
开发者ID:CodeJuan,项目名称:deis,代码行数:34,代码来源:example_test.go


示例9: NewConnection

func NewConnection(host string, port int, username string, password string, key_path string) (*ssh.Client, error) {
	var config *ssh.ClientConfig
	if USEKEY {
		public_key, err := getKeyFromFile(key_path)
		if err != nil {
			log.Panic(err)
		}
		config = &ssh.ClientConfig{
			User: username,
			Auth: []ssh.AuthMethod{
				ssh.PublicKeys(public_key),
			},
		}
	} else {
		config = &ssh.ClientConfig{
			User: username,
			Auth: []ssh.AuthMethod{
				ssh.Password(password),
			},
		}
	}

	client, err := ssh.Dial("tcp", host+":"+strconv.Itoa(port), config)
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	return client, err
}
开发者ID:newxan,项目名称:gopistrano,代码行数:31,代码来源:client.go


示例10: DownLoadDirectoryRecurrsively

func DownLoadDirectoryRecurrsively(hostAndPort string, username string,
	password string, remoteSourceDirectory string, localTargetDirectory string) error {

	remoteSourceDirectoryLength := len(remoteSourceDirectory)

	authMethodSlice := make([]ssh.AuthMethod, 0)
	authMethodSlice = append(authMethodSlice, ssh.Password(password))

	clientConfig := ssh.ClientConfig{
		User: username,
		Auth: authMethodSlice,
	}
	connection, err := ssh.Dial("tcp", hostAndPort, &clientConfig)
	if err != nil {
		return err
	}
	defer connection.Close()

	// open an SFTP session over an existing ssh connection.
	client, err := sftp.NewClient(connection)
	if err != nil {
		return err
	}
	defer client.Close()

	// walk a directory
	walk := client.Walk(remoteSourceDirectory)
	for walk.Step() {
		if err := walk.Err(); err != nil {
			return err
		}

		if walk.Stat().IsDir() {
			directoryPath := localTargetDirectory + walk.Path()[remoteSourceDirectoryLength:]
			if err := os.MkdirAll(directoryPath, os.ModePerm); err != nil {
				return err
			}
		} else {
			filePath := localTargetDirectory + walk.Path()[remoteSourceDirectoryLength:]
			file, err := client.Open(walk.Path())
			if err != nil {
				return err
			}
			defer file.Close()

			outputFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, os.ModePerm)
			if err != nil {
				return err
			}
			defer outputFile.Close()

			_, err = file.WriteTo(outputFile)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
开发者ID:cloudawan,项目名称:cloudone_utility,代码行数:60,代码来源:sftp_client.go


示例11: TestClientConnection

func (suite *ServerSuite) TestClientConnection() {

	// Get signer
	signer, err := ssh.ParsePrivateKey([]byte(clientPrivateKey))
	if err != nil {
		suite.Fail("Private key could not be parsed" + err.Error())
	}

	// Configure client connection
	config := &ssh.ClientConfig{
		User: "admin",
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(signer),
		},
	}

	// Create client connection
	client, err := ssh.Dial("tcp", "127.0.0.1:9022", config)
	if err != nil {
		suite.Fail(err.Error())
		return
	}
	defer client.Close()

	// Open channel
	channel, requests, err := client.OpenChannel("/echo", []byte{})
	if err != nil {
		suite.Fail(err.Error())
		return
	}
	go ssh.DiscardRequests(requests)
	defer channel.Close()
}
开发者ID:blacklabeldata,项目名称:sshh,代码行数:33,代码来源:server_test.go


示例12: TestHandlerError

func (suite *ServerSuite) TestHandlerError() {

	// Configure client connection
	config := &ssh.ClientConfig{
		User: "jonny.quest",
		Auth: []ssh.AuthMethod{
			ssh.Password("bandit"),
		},
	}

	// Create client connection
	client, err := ssh.Dial("tcp", "127.0.0.1:9022", config)
	if err != nil {
		suite.Fail(err.Error())
		return
	}
	defer client.Close()

	// Open channel
	channel, requests, err := client.OpenChannel("/bad", []byte{})
	if err != nil {
		suite.Fail(err.Error())
		return
	}
	go ssh.DiscardRequests(requests)
	defer channel.Close()
}
开发者ID:blacklabeldata,项目名称:sshh,代码行数:27,代码来源:server_test.go


示例13: TestUnknownChannel

func (suite *ServerSuite) TestUnknownChannel() {

	// Get signer
	signer, err := ssh.ParsePrivateKey([]byte(clientPrivateKey))
	if err != nil {
		suite.Fail("Private key could not be parsed" + err.Error())
	}

	// Configure client connection
	config := &ssh.ClientConfig{
		User: "admin",
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(signer),
		},
	}

	// Create client connection
	client, err := ssh.Dial("tcp", "127.0.0.1:9022", config)
	if err != nil {
		suite.Fail(err.Error())
		return
	}
	defer client.Close()

	// Open channel
	_, _, err = client.OpenChannel("/shell", []byte{})
	suite.NotNil(err, "server should not accept shell channels")
}
开发者ID:blacklabeldata,项目名称:sshh,代码行数:28,代码来源:server_test.go


示例14: main

func main() {

	config := &ssh.ClientConfig{
		User: "meuUsuario",
		Auth: []ssh.AuthMethod{
			ssh.Password("minhaSenha"),
		},
	}

	client, err := ssh.Dial("tcp", "meuservidor.com:22", config)
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}

	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}

	defer session.Close()

	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("/usr/bin/whoami"); err != nil {
		panic("Failed to run: " + err.Error())
	}
	fmt.Println(b.String())
}
开发者ID:viliamjr,项目名称:lab,代码行数:28,代码来源:sshClient.go


示例15: connect

// Creates a ssh connection between the local machine and the remote server.
func (p *project) connect(config *ssh.ClientConfig) {

	fmt.Println("Trying connection...")

	conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", p.hostname.name, p.port.name), config)
	errorUtil.CheckError("Failed to dial: ", err)
	fmt.Println("Connection established.")

	session, err := conn.NewSession()
	errorUtil.CheckError("Failed to build session: ", err)
	defer session.Close()

	// Loops over the slice of commands to be executed on the remote.
	for step := range p.typ.program.setup {

		if p.typ.program.setup[step] == "post-update configuration" {
			p.secureCopy(conn)
		} else if p.typ.program.setup[step] == p.projectname.name+".dev" {
			p.makeDirOnLocal(step)
		} else if p.typ.program.setup[step] == "git clone" {
			p.gitOnLocal(step)
		} else {
			p.installOnRemote(step, conn)
		}
	}
}
开发者ID:talofo,项目名称:k-env-setup,代码行数:27,代码来源:k-installer.go


示例16: ExamplePublicKeys

func ExamplePublicKeys() {
	// A public key may be used to authenticate against the remote
	// server by using an unencrypted PEM-encoded private key file.
	//
	// If you have an encrypted private key, the crypto/x509 package
	// can be used to decrypt it.
	key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa")
	if err != nil {
		log.Fatalf("unable to read private key: %v", err)
	}

	// Create the Signer for this private key.
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		log.Fatalf("unable to parse private key: %v", err)
	}

	config := &ssh.ClientConfig{
		User: "user",
		Auth: []ssh.AuthMethod{
			// Use the PublicKeys method for remote authentication.
			ssh.PublicKeys(signer),
		},
	}

	// Connect to the remote server and perform the SSH handshake.
	client, err := ssh.Dial("tcp", "host.com:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %v", err)
	}
	defer client.Close()
}
开发者ID:40a,项目名称:ejson,代码行数:32,代码来源:example_test.go


示例17: remoteCmdOutput

// remoteCmdOutput runs the given command on a remote server at the given hostname as the given user.
func remoteCmdOutput(username, hostname, cmd string, privateKey []byte) (b []byte, err error) {
	p, err := ssh.ParseRawPrivateKey(privateKey)
	if err != nil {
		return b, err
	}
	s, err := ssh.NewSignerFromKey(p)
	if err != nil {
		return b, err
	}
	pub := ssh.PublicKeys(s)
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{pub},
	}
	client, err := ssh.Dial("tcp", hostname, clientConfig)
	if err != nil {
		return b, errors.New("ERROR: Failed to dial: " + err.Error())
	}
	defer client.Close()
	session, err := client.NewSession()
	if err != nil {
		return b, errors.New("ERROR: Failed to create session: " + err.Error())
	}
	defer session.Close()
	b, err = session.Output(cmd)
	if err != nil {
		return b, fmt.Errorf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
	}
	return b, nil
}
开发者ID:cinderalla,项目名称:goship,代码行数:31,代码来源:goship.go


示例18: createSession

func (ih *InputHandler) createSession(config *InputEntry) (session *ssh.Session, err error) {

	var authMethod []ssh.AuthMethod
	var key *ssh.Signer
	if !config.Cred.IsPasswordAuth() {
		key, err = ih.parsePrivateKey(config.Cred.Identity)
		if err != nil {
			return
		}
		authMethod = []ssh.AuthMethod{ssh.PublicKeys(*key)}
	} else {
		authMethod = []ssh.AuthMethod{ssh.Password(config.Cred.Pass)}
	}

	sshConfig := new(ssh.ClientConfig)
	sshConfig.User = config.Cred.User
	sshConfig.Auth = authMethod

	port := uint16(22)
	if config.Port != 0 {
		port = config.Port
	}
	hostNameString := fmt.Sprintf("%s:%d", config.Host, port)
	client, err := ssh.Dial("tcp", hostNameString, sshConfig)
	if err != nil {
		return
	}

	session, err = client.NewSession()
	return
}
开发者ID:tri-star,项目名称:mixtail,代码行数:31,代码来源:input_handler.go


示例19: ExampleClient_Listen

func ExampleClient_Listen() {
	config := &ssh.ClientConfig{
		User: "username",
		Auth: []ssh.AuthMethod{
			ssh.Password("password"),
		},
	}
	// Dial your ssh server.
	conn, err := ssh.Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()

	// Request the remote side to open port 8080 on all interfaces.
	l, err := conn.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		log.Fatalf("unable to register tcp forward: %v", err)
	}
	defer l.Close()

	// Serve HTTP with your SSH server acting as a reverse proxy.
	http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}
开发者ID:CodeJuan,项目名称:deis,代码行数:26,代码来源:example_test.go


示例20: Client

func Client(ip_port, user, password string, command map[string]string) {
	PassWd := []ssh.AuthMethod{ssh.Password(password)}
	Conf := ssh.ClientConfig{User: user, Auth: PassWd}
	Client, err := ssh.Dial("tcp", ip_port, &Conf)
	if err == nil {
		fmt.Println(ip_port, "connect status:success")
	} else {
		fmt.Print(ip_port, "connect error:", err)
		return
	}
	defer Client.Close()
	for _, cmd := range command {
		if session, err := Client.NewSession(); err == nil {
			defer session.Close()
			var Result bytes.Buffer
			session.Stderr = &Result
			session.Stdout = &Result
			err = session.Run(cmd)
			if err == nil {
				fmt.Println(ip_port, "run command:", cmd, "run status:Ok")
			} else {
				fmt.Println(ip_port, "run error:", err)
			}
			fmt.Println(ip_port, "run result:\n", Result.String())
		}
	}
}
开发者ID:benlightning,项目名称:fabux,代码行数:27,代码来源:fabssh.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang ssh.DiscardRequests函数代码示例发布时间:2022-05-28
下一篇:
Golang sha3.ShakeSum256函数代码示例发布时间: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