-
Notifications
You must be signed in to change notification settings - Fork 7
/
ssh_key.go
72 lines (62 loc) · 1.63 KB
/
ssh_key.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
package ssh
import (
"io/ioutil"
"log"
"os/user"
"strings"
"github.com/JamesClonk/easy-vpn/provider"
)
func GetEasyVpnKeyId(p provider.API, keyName string) (keyId string) {
key := string(readKeyFile(p.GetConfig().PublicKeyFile))
// first lets get all currently installed ssh-keys
keys, err := p.GetInstalledSshKeys()
if err != nil {
log.Println("Could not retrieve list of installed SSH-Keys")
log.Fatal(err)
}
// then check to see if easy-vpn ssh-key is already installed
keyInstalled := false
for _, key := range keys {
if key.Name == keyName {
keyId = key.Id
keyInstalled = true
break
}
}
// if it is already installed, update it to make sure its public-key is up-to-date
if keyInstalled {
keyId, err = p.UpdateSshKey(keyId, keyName, key)
if err != nil {
log.Println("Could not update SSH-Key")
log.Fatal(err)
}
} else { // otherwise, install as a new ssh-key
keyId, err = p.InstallNewSshKey(keyName, key)
if err != nil {
log.Println("Could not install SSH-Key")
log.Fatal(err)
}
}
return keyId
}
func readKeyFile(filename string) []byte {
data, err := ioutil.ReadFile(sanitizeFilename(filename))
if err != nil {
log.Println("Could not read ssh key file: " + filename)
log.Fatal(err)
}
return data
}
func sanitizeFilename(filename string) string {
// replace beginning tilde (~) character with path to users home directory
if strings.HasPrefix(filename, `~`) {
usr, err := user.Current()
if err != nil {
log.Println("Could not get information about current user")
log.Fatal(err)
}
home := usr.HomeDir
filename = strings.Replace(filename, `~`, home, 1)
}
return filename
}