當前位置: 首頁>>代碼示例>>Golang>>正文


Golang ssh.PublicKeys函數代碼示例

本文整理匯總了Golang中code/google/com/p/go/crypto/ssh.PublicKeys函數的典型用法代碼示例。如果您正苦於以下問題:Golang PublicKeys函數的具體用法?Golang PublicKeys怎麽用?Golang PublicKeys使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了PublicKeys函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: connect

// connect is a private function to set up the ssh connection. It is called at the beginning of every public
// function.
func (config *Config) connect() (*ssh.Session, error) {

	sshconfig := &ssh.ClientConfig{
		User: config.User,
	}

	if config.User == "" {
		u, err := user.Current()
		if err != nil {
			return nil, err
		}
		sshconfig.User = u.Username
	}

	if config.Password != "" {
		sshconfig.Auth = append(sshconfig.Auth, ssh.Password(config.Password))
	}

	// By default, we try to include ~/.ssh/id_rsa. It is not an error if this file
	// doesn't exist.
	keyfile := os.Getenv("HOME") + "/.ssh/id_rsa"
	pkey, err := parsekey(keyfile)
	if err == nil {
		sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
	}

	// Include any additional key files
	for _, keyfile = range config.KeyFiles {
		pkey, err = parsekey(keyfile)
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return nil, err
		}
		sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
	}

	host := config.Host
	if strings.Contains(host, ":") == false {
		host = host + ":22"
	}
	client, err := ssh.Dial("tcp", host, sshconfig)
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return nil, err
	}

	session, err := client.NewSession()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return nil, err
	}
	return session, err
}
開發者ID:rphillips,項目名稱:loom,代碼行數:61,代碼來源:loom.go

示例2: SshConf

// generates an ssh config that attempt ssh-agents and then authorizes from keyFile
// if keyFile is nil, we'll search for the usual suspects
// (~/.ssh/id_rsa, id_dsa)
func SshConf(user string, keyFile string) *ssh.ClientConfig {

	var auths []ssh.AuthMethod
	// ssh-agent auth goes first
	if agentPipe, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
		ag := agent.NewClient(agentPipe)
		agentSigners, err := ag.Signers()
		if err != nil {
			log.Printf("Error pulling signers from ssh-agent: %s", err)
		} else {
			if len(agentSigners) > 0 {
				auths = append(auths, ssh.PublicKeys(agentSigners...))
			}
		}
	}

	// provided keyfile or default keyfiles
	var keyFiles []string
	if keyFile != "" {
		keyFiles = []string{keyFile}
	} else {
		keyFiles = lookupKeyFiles()
	}
	signers := make([]ssh.Signer, 0, 0)
	for _, keyFile := range keyFiles {
		keyFileH, err := os.Open(keyFile)
		if err != nil {
			log.Printf("Error opening keyFile %s : %s", keyFile, err)
			continue
		}
		keyBytes, err := ioutil.ReadAll(keyFileH)
		keyFileH.Close()
		if err != nil {
			log.Printf("Error reading keyFile %s, skipping : %s", keyFile, err)
			continue
		}
		signer, err := ssh.ParsePrivateKey(keyBytes)
		if err != nil {
			log.Printf("Error parsing keyFile contents from %s, skipping: %s", keyFile, err)
		}
		signers = append(signers, signer)
	}
	auths = append(auths, ssh.PublicKeys(signers...))
	return &ssh.ClientConfig{
		User: user,
		Auth: auths,
	}
}
開發者ID:jbooth,項目名稱:dsh,代碼行數:51,代碼來源:ssh.go

示例3: ParsePrivateKey

func (self *Server) ParsePrivateKey(filePath string) error {
	if filePath == "" {
		return nil
	}

	keyBytes, err := ioutil.ReadFile(filePath)

	if err != nil {
		err = errors.New(fmt.Sprintf("Could not read ssh key \"%s\" : %s ", filePath, err.Error()))
		self.Error = err
		self.ErrorMsg = err.Error()
		return err
	}

	signer, err := ssh.ParsePrivateKey(keyBytes)

	if err != nil {
		err = errors.New(fmt.Sprintf("Could not parse ssh key \"%s\" : %s ", filePath, err.Error()))
		self.Error = err
		self.ErrorMsg = err.Error()
		return err
	}

	self.PrivateKeyPath = filePath
	self.AuthMethods = append(self.AuthMethods, ssh.PublicKeys(signer))

	return nil
}
開發者ID:digideskio,項目名稱:watchdog_ui,代碼行數:28,代碼來源:server.go

示例4: 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:johnzan,項目名稱:goship,代碼行數:31,代碼來源:goship.go

示例5: main

func main() {
	key, err := getKeyFile()
	if err != nil {
		panic(err)
	}
	config := &ssh.ClientConfig{
		User: "jaibheemsen",
		Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
	}
	client, err := ssh.Dial("tcp", "localhost:22", config)
	if err != nil {
		panic(err)
	}
	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(err.Error())
	}
	fmt.Println(b.String())
} //godoc -http=:1989 -index=true
開發者ID:jaibheem,項目名稱:trash,代碼行數:25,代碼來源:remote.go

示例6: 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:nota-ja,項目名稱:cli,代碼行數:32,代碼來源:cert_test.go

示例7: DialInConsole

//TODO 某種認證方法隻有一個會被使用,需要多次猜測
func DialInConsole(addr string, username string) (client *ssh.Client, err error) {
	//find cert file
	pathList := certFilePathList()
	authList := []ssh.AuthMethod{}
	for _, path := range pathList {
		clientKeyBytes, err := ioutil.ReadFile(path)
		if err != nil {
			if !os.IsNotExist(err) {
				return nil, fmt.Errorf("[DialInConsole] ioutil.ReadFile() err:%s", err)
			}
		} else {
			signer, err := ssh.ParsePrivateKey(clientKeyBytes)
			if err != nil {
				return nil, fmt.Errorf("[DialInConsole] ssh.ParsePrivateKey err:%s", err)
			}
			//clientKey := &keychain{signer}
			authList = append(authList, ssh.PublicKeys(signer))
		}
	}
	authList = append(authList, ssh.PasswordCallback(func() (secret string, err error) {
		fmt.Printf("[ssh] password for %[email protected]%s", username, addr)
		secret = string(gopass.GetPasswd())
		return
	}))
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: authList,
	}
	client, err = ssh.Dial("tcp", addr, clientConfig)
	if err != nil {
		return nil, fmt.Errorf("[DialInConsole] Failed to dial: %s", err.Error())
	}
	return
}
開發者ID:keysonZZZ,項目名稱:kmg,代碼行數:35,代碼來源:DialInConsole.go

示例8: main

func main() {
	cmd := "hostname"
	username := os.Args[1]
	hosts := os.Args[2:]
	results := make(chan string, 10)
	timeout := time.After(10 * time.Second)
	key, err := getKeyFile()
	panicIf(err)
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(key),
		},
	}

	for _, hostname := range hosts {
		go func(hostname string) {
			results <- executeCmd(cmd, hostname, config)
		}(hostname)
	}

	for _, _ = range hosts {
		select {
		case res := <-results:
			fmt.Println(res)
		case <-timeout:
			fmt.Println("Timed out!")
			return
		}
	}
}
開發者ID:pbyrne,項目名稱:tmp,代碼行數:31,代碼來源:perform_ssh.go

示例9: PrepareConfig

// PrepareConfig is used to turn the *SSHConfig provided into a
// usable *Config for client initialization.
func PrepareConfig(conf *SSHConfig) (*Config, error) {
	sshConf := &ssh.ClientConfig{
		User: conf.User,
	}
	if conf.KeyFile != "" {
		key, err := ioutil.ReadFile(conf.KeyFile)
		if err != nil {
			return nil, fmt.Errorf("Failed to read key file '%s': %v", conf.KeyFile, err)
		}
		signer, err := ssh.ParsePrivateKey(key)
		if err != nil {
			return nil, fmt.Errorf("Failed to parse key file '%s': %v", conf.KeyFile, err)
		}
		sshConf.Auth = append(sshConf.Auth, ssh.PublicKeys(signer))
	}
	if conf.Password != "" {
		sshConf.Auth = append(sshConf.Auth,
			ssh.Password(conf.Password))
		sshConf.Auth = append(sshConf.Auth,
			ssh.KeyboardInteractive(PasswordKeyboardInteractive(conf.Password)))
	}
	host := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
	config := &Config{
		SSHConfig:  sshConf,
		Connection: ConnectFunc("tcp", host),
	}
	return config, nil
}
開發者ID:JasonGiedymin,項目名稱:terraform,代碼行數:30,代碼來源:provisioner.go

示例10: dialClient

// Dials to setup tcp connection to remote host, used for memory information
func dialClient() {
	t_key, _ := getKeyFile()
	if err != nil {
		panic(err)
	}
	key = t_key

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

	t_client, err := ssh.Dial("tcp", remote_host+":"+ssh_port, config)
	if err != nil {
		fmt.Println("\n", "Failed to dial: "+err.Error())
		fmt.Println("Unable to establish connection to remote machine.")
		fmt.Println("Make sure that password-less connection is possible.")
		fmt.Println("************************************")
		mem_flag = false
		return
	}
	ssh_client = t_client
}
開發者ID:smalleni,項目名稱:etcd-load-generator,代碼行數:26,代碼來源:etcd_load.go

示例11: Dial

func (d *sshDialer) Dial(addr string) (connMuxer, error) {
	conf := ssh.ClientConfig{
		User:            "termite",
		Auth:            []ssh.AuthMethod{ssh.PublicKeys(d.identity)},
		HostKeyCallback: d.checkHost,
	}

	c, err := net.Dial("tcp", addr)
	if err != nil {
		return nil, err
	}

	defer func() {
		if c != nil {
			c.Close()
		}
	}()
	conn, chans, reqs, err := ssh.NewClientConn(c, addr, &conf)
	if err != nil {
		return nil, err
	}
	go ssh.DiscardRequests(reqs)
	go func() {
		for c := range chans {
			go c.Reject(ssh.Prohibited, "")
		}
	}()

	c = nil
	return &sshMuxer{conn}, nil
}
開發者ID:hanwen,項目名稱:termite,代碼行數:31,代碼來源:ssh-conn.go

示例12: getSftpClient

func getSftpClient(conf Config) []*sftp.Client {
	// process the keyfile
	buf, err := ioutil.ReadFile(conf.KeyFile)
	if err != nil {
		log.Fatalf("error in reading private key file %s\n", err)
	}
	key, err := ssh.ParsePrivateKey(buf)
	if err != nil {
		log.Fatalf("error in parsing private key %s\n", key)
	}
	// client config
	config := &ssh.ClientConfig{
		User: conf.User,
		Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
	}
	// connection
	clients := make([]*sftp.Client, 0)
	for _, r := range conf.Remotes {
		c, err := ssh.Dial("tcp", r, config)
		if err != nil {
			log.Fatalf("error in ssh connection %s\n", err)
		}
		// sftp handler
		sftp, err := sftp.NewClient(c)
		if err != nil {
			log.Fatalf("error in sftp connection %s\n", err)
		}
		clients = append(clients, sftp)
	}
	return clients
}
開發者ID:dictyBase,項目名稱:webhooks,代碼行數:31,代碼來源:push.go

示例13: Connect

func (c *SftpClient) Connect() error {
	auth := []ssh.AuthMethod{}
	if c.authMethod == "key" {
		key, _ := c.GetKey(c.keyPath)

		auth = []ssh.AuthMethod{
			ssh.PublicKeys(key),
		}
	} else if c.authMethod == "password" {
		auth = []ssh.AuthMethod{
			ssh.Password(c.password),
		}
	}
	config := &ssh.ClientConfig{
		User: c.username,
		Auth: auth,
	}
	sHost := strings.Join([]string{c.hostname, strconv.FormatInt(c.port, 10)}, ":")

	sshClient, err := ssh.Dial("tcp", sHost, config)
	if err != nil {
		return err
	}
	sftpClient, err := sftp.NewClient(sshClient)
	if err == nil {
		c.Client = sftpClient
	}
	return err
}
開發者ID:VukDukic,項目名稱:gotilla,代碼行數:29,代碼來源:sftputil.go

示例14: NewClient

func NewClient(user, address string, privateKey []byte) (*client, error) {
	c := &client{}

	config := &ssh.ClientConfig{
		User: user,
	}

	// Check if we've been given a byte slice from which to parse a key.
	if privateKey != nil {

		privateKeyParsed, err := ssh.ParsePrivateKey(privateKey)
		if err != nil {
			return c, err
		}

		config.Auth = []ssh.AuthMethod{
			ssh.PublicKeys(privateKeyParsed),
		}
	} else {

		sshAuthSock := os.Getenv(`SSH_AUTH_SOCK`)

		socket, err := net.Dial("unix", sshAuthSock)
		if err != nil {
			return c, err
		}

		sshAgent := agent.NewClient(socket)
		signers, err := sshAgent.Signers()
		if err != nil {
			return c, err
		}

		config.Auth = []ssh.AuthMethod{
			ssh.PublicKeys(signers...),
		}
	}

	client, err := ssh.Dial("tcp", address, config)
	if err != nil {
		return c, err
	}

	c.client = client

	return c, nil
}
開發者ID:jeremyjbowers,項目名稱:stocker,代碼行數:47,代碼來源:client.go

示例15: MakeKeyring

func MakeKeyring() ssh.AuthMethod {
	signer, err := makeSigner(os.Getenv("HOME") + "/.ssh/alex.sharov")
	if err != nil {
		panic(err)
	}

	return ssh.PublicKeys(signer)
}
開發者ID:nizsheanez,項目名稱:ria,代碼行數:8,代碼來源:ssh.go


注:本文中的code/google/com/p/go/crypto/ssh.PublicKeys函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。