本文整理匯總了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
}
示例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,
}
}
示例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
}
示例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
}
示例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
示例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()
}
示例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
}
示例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
}
}
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例15: MakeKeyring
func MakeKeyring() ssh.AuthMethod {
signer, err := makeSigner(os.Getenv("HOME") + "/.ssh/alex.sharov")
if err != nil {
panic(err)
}
return ssh.PublicKeys(signer)
}