Run command via SSH
(command string, env *env.Env)
| 81 | |
| 82 | // Run command via SSH |
| 83 | func (ssh *SSH) sshRunCommand(command string, env *env.Env) ([]byte, error) { |
| 84 | // Get signer from private key |
| 85 | signer, _ := sshClient.ParsePrivateKey(ssh.SSH_PRIVATE_KEY) |
| 86 | |
| 87 | // Convert timeout param |
| 88 | timeoutSeconds, _ := strconv.Atoi(env.SSH_CONNECT_TIMEOUT) |
| 89 | timeoutDuration := time.Duration(timeoutSeconds) * time.Second |
| 90 | |
| 91 | // SSH client config |
| 92 | config := &sshClient.ClientConfig{ |
| 93 | User: ssh.SSH_USER, |
| 94 | HostKeyCallback: sshClient.InsecureIgnoreHostKey(), // StrictHostKeyChecking=no |
| 95 | Timeout: time.Duration(timeoutDuration), // ConnectTimeout |
| 96 | Auth: []sshClient.AuthMethod{ |
| 97 | sshClient.Password(env.SSH_PASSWORD), |
| 98 | }, |
| 99 | } |
| 100 | |
| 101 | // SSH auth config |
| 102 | if signer != nil { |
| 103 | config.Auth = []sshClient.AuthMethod{ |
| 104 | sshClient.PublicKeys(signer), |
| 105 | sshClient.Password(env.SSH_PASSWORD), |
| 106 | } |
| 107 | } else { |
| 108 | log.Println("[WARN] Private key not found") |
| 109 | if len(env.SSH_PASSWORD) == 0 { |
| 110 | log.Println("[WARN] Password not set") |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // Establishing TCP connection |
| 115 | client, err := sshClient.Dial("tcp", fmt.Sprintf("%s:%s", ssh.SSH_HOST, ssh.SSH_PORT), config) |
| 116 | if err != nil { |
| 117 | log.Println("[WARN] Failed establishing tcp connection") |
| 118 | return nil, fmt.Errorf("Failed establishing tcp connection: %w", err) |
| 119 | } |
| 120 | defer client.Close() |
| 121 | |
| 122 | // Creating SSH session |
| 123 | session, err := client.NewSession() |
| 124 | if err != nil { |
| 125 | log.Println("[WARN] Failed creating ssh session") |
| 126 | return nil, fmt.Errorf("Failed creating ssh session: %w", err) |
| 127 | } |
| 128 | defer session.Close() |
| 129 | |
| 130 | // Run command |
| 131 | var stdoutBuf bytes.Buffer |
| 132 | var stderrBuf bytes.Buffer |
| 133 | session.Stdout = &stdoutBuf |
| 134 | session.Stderr = &stderrBuf |
| 135 | err = session.Run(command) |
| 136 | if len(stderrBuf.Bytes()) > 0 { |
| 137 | return stderrBuf.Bytes(), fmt.Errorf("Execution error (error output is not empty)") |
| 138 | } |
| 139 | return stdoutBuf.Bytes(), err |
| 140 | } |
no outgoing calls
no test coverage detected