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

Golang ssh.PublicKeys函数代码示例

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

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



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

示例1: SSHConfig

// SSHConfig returns a function that can be used for the SSH communicator
// config for connecting to the instance created over SSH using the provided
// private key
func SSHConfig(username string) func(multistep.StateBag) (*ssh.ClientConfig, error) {
	return func(state multistep.StateBag) (*ssh.ClientConfig, error) {
		privateKey := state.Get("privateKey").(string) // ad hoc key
		privateKeyBastion := state.Get("privateKeyBastion").(string)

		signer, err := ssh.ParsePrivateKey([]byte(privateKey))
		if err != nil {
			return nil, fmt.Errorf("error setting up SSH config: %s", err)
		}

		authMethods := []ssh.AuthMethod{ssh.PublicKeys(signer)}

		// if we have a Bastion, that key should also be supported
		if privateKeyBastion != "" {
			signerBastion, err := ssh.ParsePrivateKey([]byte(privateKeyBastion))
			if err != nil {
				return nil, fmt.Errorf("error setting up SSH config for Bastion: %s", err)
			}

			authMethods = append(authMethods, ssh.PublicKeys(signerBastion))

		}

		return &ssh.ClientConfig{
			User: username,
			Auth: authMethods,
		}, nil
	}
}
开发者ID:brkt,项目名称:packer,代码行数:32,代码来源:ssh.go


示例2: NewClientConfig

// NewClientConfig returns a config using an ssh agent unless ident is not empty.
func NewClientConfig(ident string, user string) (*ClientConfig, error) {
	// I think this could be simplified by using PublicKeysCallback
	cfg := &ClientConfig{
		ClientConfig: &ssh.ClientConfig{
			User: user,
		},
	}

	if ident != "" {
		s, err := pemSigner(ident)
		if err != nil {
			return nil, err
		}

		cfg.ClientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(s)}

		return cfg, nil
	}

	a, s, err := agentSigners()
	if err != nil {
		return nil, err
	}

	cfg.a = *a
	cfg.ClientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(s...)}

	return cfg, nil
}
开发者ID:progrium,项目名称:remotectl,代码行数:30,代码来源:ssh.go


示例3: addKeyAuth

func addKeyAuth(auths []ssh.AuthMethod, keypath string) []ssh.AuthMethod {
	if len(keypath) == 0 {
		return auths
	}

	// read the file
	pemBytes, err := ioutil.ReadFile(keypath)
	if err != nil {
		log.Print(err)
		os.Exit(1)
	}

	// get first pem block
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		log.Printf("no key found in %s", keypath)
		return auths
	}

	// handle plain and encrypted keyfiles
	if x509.IsEncryptedPEMBlock(block) {
		prompt := fmt.Sprintf("Enter passphrase for key '%s': ", keypath)
		pass, err := getpass(prompt)
		if err != nil {
			return auths
		}
		block.Bytes, err = x509.DecryptPEMBlock(block, []byte(pass))
		if err != nil {
			log.Print(err)
			return auths
		}
		key, err := ParsePemBlock(block)
		if err != nil {
			log.Print(err)
			return auths
		}
		signer, err := ssh.NewSignerFromKey(key)
		if err != nil {
			log.Print(err)
			return auths
		}
		return append(auths, ssh.PublicKeys(signer))
	} else {
		signer, err := ssh.ParsePrivateKey(pemBytes)
		if err != nil {
			log.Print(err)
			return auths
		}
		return append(auths, ssh.PublicKeys(signer))
	}
}
开发者ID:nagual13,项目名称:rtop,代码行数:51,代码来源:sshhelper.go


示例4: NewSSHSession

func (n *Node) NewSSHSession() (session *ssh.Session, err error) {
	pkey, err := ioutil.ReadFile(n.SSHKeyFile)
	if err != nil {
		log.Println("ioutil.ReadFile(sshkey):", err)
		return session, err
	}

	s, err := ssh.ParsePrivateKey(pkey)
	if err != nil {
		log.Println("ssh.ParsePrivateKey():", err)
		return session, err
	}

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

	host := fmt.Sprintf("%s:%d", n.Host, n.Port)
	client, err := ssh.Dial("tcp", host, config)
	if err != nil {
		log.Println("ssh.Dial:", err)
		return session, err
	}

	session, err = client.NewSession()
	if err != nil {
		log.Println("cli.NewSession():", err)
		return session, err
	}

	return session, err
}
开发者ID:KLab,项目名称:gohakai,代码行数:35,代码来源:remote.go


示例5: TestCertLogin

func TestCertLogin(t *testing.T) {
	s := newServer(t)
	defer s.Shutdown()

	// Use a key different from the default.
	clientKey := testSigners["dsa"]
	caAuthKey := testSigners["ecdsa"]
	cert := &ssh.Certificate{
		Key:             clientKey.PublicKey(),
		ValidPrincipals: []string{username()},
		CertType:        ssh.UserCert,
		ValidBefore:     ssh.CertTimeInfinity,
	}
	if err := cert.SignCert(rand.Reader, caAuthKey); err != nil {
		t.Fatalf("SetSignature: %v", err)
	}

	certSigner, err := ssh.NewCertSigner(cert, clientKey)
	if err != nil {
		t.Fatalf("NewCertSigner: %v", err)
	}

	conf := &ssh.ClientConfig{
		User: username(),
	}
	conf.Auth = append(conf.Auth, ssh.PublicKeys(certSigner))
	client, err := s.TryDial(conf)
	if err != nil {
		t.Fatalf("TryDial: %v", err)
	}
	client.Close()
}
开发者ID:CNDonny,项目名称:scope,代码行数:32,代码来源:cert_test.go


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


示例7: NewSshClientConfig

func (cfg *ConfigT) NewSshClientConfig(privKeyPath string) error {
	var err error
	var clientKey []byte
	var signer ssh.Signer

	Goose.ClientCfg.Logf(4, "Reading SSH private key from %s", privKeyPath)

	clientKey, err = ioutil.ReadFile(privKeyPath)
	if err != nil {
		Goose.ClientCfg.Logf(1, "%s (%s)", ErrReadingSSHKeys, err)
		return ErrReadingSSHKeys
	}

	signer, err = ssh.ParsePrivateKey(clientKey)
	if err != nil {
		Goose.ClientCfg.Logf(1, "%s (%s)", ErrParsingSSHKeys, err)
		return ErrReadingSSHKeys
	}

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

	return nil
}
开发者ID:luisfurquim,项目名称:masterbot,代码行数:28,代码来源:ConfigT.NewSSHClientConfig.go


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


示例9: SSHConfig

// SSHConfig returns a function that can be used for the SSH communicator
// config for connecting to the instance created over SSH using the private key
// or password.
func SSHConfig(username, password string) func(multistep.StateBag) (*ssh.ClientConfig, error) {
	return func(state multistep.StateBag) (*ssh.ClientConfig, error) {

		privateKey, hasKey := state.GetOk("privateKey")
		if hasKey {

			signer, err := ssh.ParsePrivateKey([]byte(privateKey.(string)))
			if err != nil {
				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
			}
			return &ssh.ClientConfig{
				User: username,
				Auth: []ssh.AuthMethod{
					ssh.PublicKeys(signer),
				},
			}, nil

		} else {
			return &ssh.ClientConfig{
				User: username,
				Auth: []ssh.AuthMethod{
					ssh.Password(password),
					ssh.KeyboardInteractive(
						packerssh.PasswordKeyboardInteractive(password)),
				}}, nil
		}
	}
}
开发者ID:monkeylittleinc,项目名称:packer,代码行数:31,代码来源:ssh.go


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


示例11: sshConfig

func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
	config := state.Get("config").(*Config)
	var privateKey string

	var auth []gossh.AuthMethod

	if config.Comm.SSHPassword != "" {
		auth = []gossh.AuthMethod{
			gossh.Password(config.Comm.SSHPassword),
			gossh.KeyboardInteractive(
				ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),
		}
	}

	if config.Comm.SSHPrivateKey != "" {
		if priv, ok := state.GetOk("privateKey"); ok {
			privateKey = priv.(string)
		}
		signer, err := gossh.ParsePrivateKey([]byte(privateKey))
		if err != nil {
			return nil, fmt.Errorf("Error setting up SSH config: %s", err)
		}
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}
	return &gossh.ClientConfig{
		User: config.Comm.SSHUsername,
		Auth: auth,
	}, nil
}
开发者ID:arizvisa,项目名称:packer,代码行数:33,代码来源:ssh.go


示例12: New

// New returns a new SFTP remote Cache implementated.
func New(server, username, password, key string) (cache.Cache, error) {
	config := &ssh.ClientConfig{
		Timeout: time.Minute * 5,
		User:    username,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
		},
	}

	// private key authentication takes precedence
	if key != "" {
		signer, err := ssh.ParsePrivateKey([]byte(key))
		if err != nil {
			return nil, err
		}
		config.Auth[0] = ssh.PublicKeys(signer)
	}

	// create the ssh connection and client
	client, err := ssh.Dial("tcp", server, config)
	if err != nil {
		return nil, err
	}

	// open the sftp session using the ssh connection
	sftp, err := sftp.NewClient(client)
	if err != nil {
		client.Close()
		return nil, err
	}

	return &cacher{sftp, client}, nil
}
开发者ID:ZombieHippie,项目名称:drone-sftp-cache,代码行数:34,代码来源:sftp.go


示例13: initAuthMethod

// initAuthMethod initiates SSH authentication method.
func initAuthMethod() {
	var signers []ssh.Signer

	// If there's a running SSH Agent, try to use its Private keys.
	sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
	if err == nil {
		agent := agent.NewClient(sock)
		signers, _ = agent.Signers()
	}

	// Try to read user's SSH private keys form the standard paths.
	files := []string{
		os.Getenv("HOME") + "/.ssh/id_rsa",
		os.Getenv("HOME") + "/.ssh/id_dsa",
	}
	for _, file := range files {
		data, err := ioutil.ReadFile(file)
		if err != nil {
			continue
		}
		signer, err := ssh.ParsePrivateKey(data)
		if err != nil {
			continue
		}
		signers = append(signers, signer)

	}
	authMethod = ssh.PublicKeys(signers...)
}
开发者ID:roblillack,项目名称:sup,代码行数:30,代码来源:ssh.go


示例14: initialize

func initialize() {
	privkey_fname := util.AppBaseFileName() + ".privkey"
	privkey_bytes, err := ioutil.ReadFile(privkey_fname)
	if err != nil {
		log.Panicf("privkey load error: %s", err)
	}
	signer, err := ssh.ParsePrivateKey(privkey_bytes)
	if err != nil {
		log.Panicf("privkey parse error: %s", err)
	}
	clientConfig = &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(signer),
		},
	}
	hostlist_fname := util.AppBaseFileName() + ".hostlist"
	f, err := os.Open(hostlist_fname)
	if err != nil {
		log.Panicf("hostlist open error: %s", err)
	}

	defer f.Close()
	scanner := bufio.NewScanner(f)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		hostlist = append(hostlist, scanner.Text())
	}
}
开发者ID:gourytch,项目名称:gowowuction,代码行数:29,代码来源:auc-merge.go


示例15: sshClientConfig

func sshClientConfig(user string, checker *HostKeyChecker, addr string) (*gossh.ClientConfig, error) {
	agentClient, err := SSHAgentClient()
	if err != nil {
		return nil, err
	}

	signers, err := agentClient.Signers()
	if err != nil {
		return nil, err
	}

	cfg := gossh.ClientConfig{
		User: user,
		Auth: []gossh.AuthMethod{
			gossh.PublicKeys(signers...),
		},
	}

	if checker != nil {
		cfg.HostKeyCallback = checker.Check
		cfg.HostKeyAlgorithms = checker.GetHostKeyAlgorithms(addr)
	}

	return &cfg, nil
}
开发者ID:jonboulle,项目名称:fleet,代码行数:25,代码来源:ssh.go


示例16: ConnectAndRun

func (r *Runner) ConnectAndRun(host, command string, options *ConnectionOptions) (string, error) {
	signer, err := ssh.ParsePrivateKey(options.PrivateKeyPEM)
	if err != nil {
		return "", err
	}

	config := &ssh.ClientConfig{
		User: options.Username,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(signer),
		},
	}
	client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, options.Port), config)
	if err != nil {
		return "", fmt.Errorf("failed to dial: %s", err)
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		return "", fmt.Errorf("failed to create session: ", err)
	}
	defer session.Close()

	var stdoutBytes bytes.Buffer
	session.Stdout = &stdoutBytes
	session.Stderr = os.Stderr
	if err := session.Run(command); err != nil {
		return "", fmt.Errorf("failed while running command: %s", err)
	}
	return stdoutBytes.String(), nil
}
开发者ID:rosenhouse,项目名称:proctor,代码行数:32,代码来源:shell.go


示例17: sshKeyAuth

// sshKeyAuth is a helper function to get the ssh key auth struct needed
func (obj *Remotes) sshKeyAuth() (ssh.AuthMethod, error) {
	if obj.sshPrivIdRsa == "" {
		return nil, fmt.Errorf("Empty path specified!")
	}
	p := ""
	// TODO: this doesn't match strings of the form: ~james/.ssh/id_rsa
	if strings.HasPrefix(obj.sshPrivIdRsa, "~/") {
		usr, err := user.Current()
		if err != nil {
			log.Printf("Remote: Can't find home directory automatically.")
			return nil, err
		}
		p = path.Join(usr.HomeDir, obj.sshPrivIdRsa[len("~/"):])
	}
	if p == "" {
		return nil, fmt.Errorf("Empty path specified!")
	}
	// A public key may be used to authenticate against the 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(p)
	if err != nil {
		return nil, err
	}

	// Create the Signer for this private key.
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		return nil, err
	}

	return ssh.PublicKeys(signer), nil
}
开发者ID:purpleidea,项目名称:mgmt,代码行数:34,代码来源:remote.go


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


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


示例20: readPrivateKey

func readPrivateKey(pk string) (ssh.AuthMethod, error) {
	key, _, err := pathorcontents.Read(pk)
	if err != nil {
		return nil, fmt.Errorf("Failed to read private key %q: %s", pk, err)
	}

	// We parse the private key on our own first so that we can
	// show a nicer error if the private key has a password.
	block, _ := pem.Decode([]byte(key))
	if block == nil {
		return nil, fmt.Errorf("Failed to read key %q: no key found", pk)
	}
	if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
		return nil, fmt.Errorf(
			"Failed to read key %q: password protected keys are\n"+
				"not supported. Please decrypt the key prior to use.", pk)
	}

	signer, err := ssh.ParsePrivateKey([]byte(key))
	if err != nil {
		return nil, fmt.Errorf("Failed to parse key file %q: %s", pk, err)
	}

	return ssh.PublicKeys(signer), nil
}
开发者ID:devendraPSL,项目名称:terraform-api,代码行数:25,代码来源:provisioner.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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