github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgSsh/DialInConsole.go (about) 1 package kmgSsh 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 8 "code.google.com/p/go.crypto/ssh" 9 "github.com/howeyc/gopass" 10 ) 11 12 type consoleAskPassword struct { 13 user string 14 addr string 15 } 16 17 func (p consoleAskPassword) Password() (password string, err error) { 18 fmt.Printf("[ssh] password for %s@%s", p.user, p.addr) 19 password = string(gopass.GetPasswd()) 20 return password, nil 21 } 22 23 //TODO 某种认证方法只有一个会被使用,需要多次猜测 24 func DialInConsole(addr string, username string) (client *ssh.Client, err error) { 25 //find cert file 26 pathList := certFilePathList() 27 authList := []ssh.AuthMethod{} 28 for _, path := range pathList { 29 clientKeyBytes, err := ioutil.ReadFile(path) 30 if err != nil { 31 if !os.IsNotExist(err) { 32 return nil, fmt.Errorf("[DialInConsole] ioutil.ReadFile() err:%s", err) 33 } 34 } else { 35 signer, err := ssh.ParsePrivateKey(clientKeyBytes) 36 if err != nil { 37 return nil, fmt.Errorf("[DialInConsole] ssh.ParsePrivateKey err:%s", err) 38 } 39 //clientKey := &keychain{signer} 40 authList = append(authList, ssh.PublicKeys(signer)) 41 } 42 } 43 authList = append(authList, ssh.PasswordCallback(func() (secret string, err error) { 44 fmt.Printf("[ssh] password for %s@%s", username, addr) 45 secret = string(gopass.GetPasswd()) 46 return 47 })) 48 clientConfig := &ssh.ClientConfig{ 49 User: username, 50 Auth: authList, 51 } 52 client, err = ssh.Dial("tcp", addr, clientConfig) 53 if err != nil { 54 return nil, fmt.Errorf("[DialInConsole] Failed to dial: %s", err.Error()) 55 } 56 return 57 }