File: client.go

package info (click to toggle)
golang-github-containers-gvisor-tap-vsocks 0.8.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 800 kB
  • sloc: sh: 95; makefile: 59
file content (66 lines) | stat: -rw-r--r-- 1,313 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main

import (
	"fmt"
	"net"
	"os"
	"time"

	"golang.org/x/crypto/ssh"
)

type client struct {
	Conn   net.Conn
	Config *ssh.ClientConfig
}

func newClient(conn net.Conn, user string, key string) (*client, error) {
	config, err := newConfig(user, key)
	if err != nil {
		return nil, fmt.Errorf("Error getting config for native Go SSH: %s", err)
	}

	return &client{
		Conn:   conn,
		Config: config,
	}, nil
}

func newConfig(user string, keyFile string) (*ssh.ClientConfig, error) {
	key, err := os.ReadFile(keyFile)
	if err != nil {
		return nil, err
	}
	privateKey, err := ssh.ParsePrivateKey(key)
	if err != nil {
		return nil, err
	}
	return &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{ssh.PublicKeys(privateKey)},
		// #nosec G106
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		Timeout:         time.Minute,
	}, nil
}

func (client *client) output(command string) (string, error) {
	c, chans, reqs, err := ssh.NewClientConn(client.Conn, "", client.Config)
	if err != nil {
		return "", err
	}
	conn := ssh.NewClient(c, chans, reqs)
	session, err := conn.NewSession()
	if err != nil {
		_ = conn.Close()
		return "", err
	}
	defer conn.Close()
	defer session.Close()

	output, err := session.CombinedOutput(command)
	if err != nil {
		return "", err
	}
	return string(output), nil
}