连接到远程主机
(sshHost string, sshPort int, sshUserName, sshPassword string, idRsa string)
| 1008 | |
| 1009 | // 连接到远程主机 |
| 1010 | func connectionDial(sshHost string, sshPort int, sshUserName, sshPassword string, idRsa string) (clientConn *ssh.Client, err error) { |
| 1011 | // initialize SSH connection |
| 1012 | var clientConfig *ssh.ClientConfig |
| 1013 | if sshPort <= 0 { |
| 1014 | sshPort = 22 |
| 1015 | } |
| 1016 | |
| 1017 | if len(sshPassword) > 0 { |
| 1018 | |
| 1019 | if len(strings.TrimSpace(sshPassword)) == 0 { |
| 1020 | SmartIDELog.Error(i18n.GetInstance().Common.Err_password_none) |
| 1021 | } |
| 1022 | |
| 1023 | clientConfig = &ssh.ClientConfig{ |
| 1024 | User: sshUserName, |
| 1025 | Auth: []ssh.AuthMethod{ |
| 1026 | ssh.Password(sshPassword), |
| 1027 | }, |
| 1028 | Timeout: 10 * time.Second, // 10 秒超时 |
| 1029 | // 解决 “ssh: must specify HostKeyCallback” 的问题 |
| 1030 | HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { |
| 1031 | return nil |
| 1032 | }, |
| 1033 | } |
| 1034 | |
| 1035 | } else { // 如果用户不输入用户名和密码,则尝试使用ssh key pair的方式链接远程服务器 |
| 1036 | var key []byte |
| 1037 | //var hostKey ssh.PublicKey |
| 1038 | if idRsa == "" { |
| 1039 | homePath, err := os.UserHomeDir() |
| 1040 | CheckError(err) |
| 1041 | filePath := filepath.Join(homePath, "/.ssh/id_rsa") |
| 1042 | key, err = os.ReadFile(filePath) |
| 1043 | CheckError(err, "unable to read ssh private key:") |
| 1044 | } else { |
| 1045 | key = []byte(idRsa) |
| 1046 | } |
| 1047 | |
| 1048 | // Create the Signer for this private key. |
| 1049 | signer, err := ssh.ParsePrivateKey(key) |
| 1050 | CheckError(err, "unable to parse private key:") |
| 1051 | |
| 1052 | clientConfig = &ssh.ClientConfig{ |
| 1053 | User: sshUserName, |
| 1054 | Auth: []ssh.AuthMethod{ |
| 1055 | // Use the PublicKeys method for remote authentication. |
| 1056 | ssh.PublicKeys(signer), |
| 1057 | }, |
| 1058 | HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { |
| 1059 | // use OpenSSH's known_hosts file if you care about host validation |
| 1060 | return nil |
| 1061 | }, |
| 1062 | } |
| 1063 | |
| 1064 | } |
| 1065 | |
| 1066 | addr := fmt.Sprintf("%v:%v", sshHost, sshPort) |
| 1067 | return ssh.Dial("tcp", addr, clientConfig) |
no test coverage detected