|
| 1 | +package e2e |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "io/ioutil" |
| 6 | + "log" |
| 7 | + "net" |
| 8 | + "os" |
| 9 | + |
| 10 | + "golang.org/x/crypto/ssh" |
| 11 | + "golang.org/x/crypto/ssh/agent" |
| 12 | +) |
| 13 | + |
| 14 | +type SSHClient struct { |
| 15 | + *ssh.ClientConfig |
| 16 | +} |
| 17 | + |
| 18 | +// NewSSHClientOrDie tries to create an ssh client. |
| 19 | +// If $SSH_AUTH_SOCK is set, the use the ssh agent to create the client, |
| 20 | +// otherwise read the private key directly. |
| 21 | +func NewSSHClientOrDie(keypath string) *SSHClient { |
| 22 | + var authMethod ssh.AuthMethod |
| 23 | + |
| 24 | + sock := os.Getenv("SSH_AUTH_SOCK") |
| 25 | + if sock != "" { |
| 26 | + log.Println("Creating ssh client with ssh agent") |
| 27 | + sshAgent, err := net.Dial("unix", sock) |
| 28 | + if err != nil { |
| 29 | + panic(err) |
| 30 | + } |
| 31 | + |
| 32 | + authMethod = ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers) |
| 33 | + } else { |
| 34 | + log.Println("Creating ssh client with private key") |
| 35 | + key, err := ioutil.ReadFile(keypath) |
| 36 | + if err != nil { |
| 37 | + panic(err) |
| 38 | + } |
| 39 | + |
| 40 | + signer, err := ssh.ParsePrivateKey(key) |
| 41 | + if err != nil { |
| 42 | + panic(err) |
| 43 | + } |
| 44 | + |
| 45 | + authMethod = ssh.PublicKeys(signer) |
| 46 | + } |
| 47 | + |
| 48 | + sshConfig := &ssh.ClientConfig{ |
| 49 | + User: "core", // TODO(yifan): Assume all nodes are container linux nodes for now. |
| 50 | + Auth: []ssh.AuthMethod{authMethod}, |
| 51 | + HostKeyCallback: ssh.InsecureIgnoreHostKey(), |
| 52 | + } |
| 53 | + |
| 54 | + return &SSHClient{sshConfig} |
| 55 | +} |
| 56 | + |
| 57 | +func (c *SSHClient) SSH(host, cmd string) (stdout, stderr []byte, err error) { |
| 58 | + client, err := ssh.Dial("tcp", host+":22", c.ClientConfig) // TODO(yifan): Assume all nodes are listening on :22 for ssh requests for now. |
| 59 | + if err != nil { |
| 60 | + return nil, nil, err |
| 61 | + } |
| 62 | + defer client.Conn.Close() |
| 63 | + |
| 64 | + session, err := client.NewSession() |
| 65 | + if err != nil { |
| 66 | + return nil, nil, err |
| 67 | + } |
| 68 | + defer session.Close() |
| 69 | + |
| 70 | + outBuf := bytes.NewBuffer(nil) |
| 71 | + errBuf := bytes.NewBuffer(nil) |
| 72 | + session.Stdout = outBuf |
| 73 | + session.Stderr = errBuf |
| 74 | + |
| 75 | + err = session.Run(cmd) |
| 76 | + |
| 77 | + stdout = bytes.TrimSpace(outBuf.Bytes()) |
| 78 | + stderr = bytes.TrimSpace(errBuf.Bytes()) |
| 79 | + |
| 80 | + return stdout, stderr, err |
| 81 | +} |
0 commit comments