SSHClient SSHClient
(user, password, host, key string, port int, cipherList []string)
| 11 | |
| 12 | //SSHClient SSHClient |
| 13 | func SSHClient(user, password, host, key string, port int, cipherList []string) (*ssh.Client, error) { |
| 14 | var ( |
| 15 | auth []ssh.AuthMethod |
| 16 | addr string |
| 17 | clientConfig *ssh.ClientConfig |
| 18 | client *ssh.Client |
| 19 | config ssh.Config |
| 20 | err error |
| 21 | ) |
| 22 | // get auth method |
| 23 | auth = make([]ssh.AuthMethod, 0) |
| 24 | if key == "" { |
| 25 | auth = append(auth, ssh.Password(password)) |
| 26 | } else { |
| 27 | |
| 28 | pemBytes := []byte(key) |
| 29 | var signer ssh.Signer |
| 30 | if password == "" { |
| 31 | signer, err = ssh.ParsePrivateKey(pemBytes) |
| 32 | } else { |
| 33 | // 使用私钥解析密码 |
| 34 | signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(password)) |
| 35 | } |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | auth = append(auth, ssh.PublicKeys(signer)) |
| 40 | } |
| 41 | |
| 42 | if len(cipherList) == 0 { |
| 43 | config = ssh.Config{ |
| 44 | Ciphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128", "aes128-cbc", "3des-cbc", "aes192-cbc", "aes256-cbc"}, |
| 45 | } |
| 46 | } else { |
| 47 | config = ssh.Config{ |
| 48 | Ciphers: cipherList, |
| 49 | } |
| 50 | } |
| 51 | clientConfig = &ssh.ClientConfig{ |
| 52 | User: user, |
| 53 | Auth: auth, |
| 54 | Timeout: 30 * time.Second, |
| 55 | Config: config, |
| 56 | HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { |
| 57 | return nil |
| 58 | }, |
| 59 | } |
| 60 | |
| 61 | // connet to ssh |
| 62 | addr = fmt.Sprintf("%s:%d", host, port) |
| 63 | |
| 64 | if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | return client, nil |
| 68 | } |
| 69 | |
| 70 | //SessionConnect SessionConnect |