forked from jfrog/artifactory-cli-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshLogin.go
90 lines (76 loc) · 2.21 KB
/
sshLogin.go
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package utils
import (
"io"
"fmt"
"bytes"
"regexp"
"strconv"
"io/ioutil"
"encoding/json"
"github.com/eyalbe4/artifactory-cli-go/Godeps/_workspace/src/golang.org/x/crypto/ssh"
)
func SshAuthentication(details *ArtifactoryDetails) {
_, host, port := parseUrl(details.Url)
fmt.Println("Performing SSH authentication...")
if details.SshKeyPath == "" {
Exit(ExitCodeError, "Cannot invoke the SshAuthentication function with no SSH key path. ")
}
buffer, err := ioutil.ReadFile(details.SshKeyPath)
CheckError(err)
key, err := ssh.ParsePrivateKey(buffer)
CheckError(err)
sshConfig := &ssh.ClientConfig{
User: "admin",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
}
hostAndPort := host + ":" + strconv.Itoa(port)
connection, err := ssh.Dial("tcp", hostAndPort, sshConfig)
CheckError(err)
defer connection.Close()
session, err := connection.NewSession()
CheckError(err)
defer session.Close()
stdout, err := session.StdoutPipe()
CheckError(err)
var buf bytes.Buffer
go io.Copy(&buf, stdout)
session.Run("cli-authenticate")
var result SshAuthResult
err = json.Unmarshal(buf.Bytes(), &result)
CheckError(err)
details.Url = AddTrailingSlashIfNeeded(result.Href)
details.SshAuthHeaders = result.Headers
fmt.Println("SSH authentication successful.")
}
func parseUrl(url string) (protocol, host string, port int) {
pattern1 := "^(.+)://(.+):([0-9].+)/$"
pattern2 := "^(.+)://(.+)$"
r, err := regexp.Compile(pattern1)
CheckError(err)
groups := r.FindStringSubmatch(url)
if len(groups) == 4 {
protocol = groups[1]
host = groups[2]
port, err = strconv.Atoi(groups[3])
if err != nil {
Exit(ExitCodeError, "URL: " + url + " is invalid. Expecting ssh://<host>:<port> or http(s)://...")
}
return
}
r, err = regexp.Compile(pattern2)
CheckError(err)
groups = r.FindStringSubmatch(url)
if len(groups) == 3 {
protocol = groups[1]
host = groups[2]
port = 80
return
}
return
}
type SshAuthResult struct {
Href string
Headers map[string]string
}