-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwifipw_linux.go
48 lines (44 loc) · 1.14 KB
/
wifipw_linux.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
package wifipw
import (
"bytes"
"errors"
"fmt"
"os/exec"
"regexp"
"strings"
)
func WIFIPassword(ssid string) (password string, err error) {
paths := []string{
fmt.Sprintf("/etc/NetworkManager/system-connections/%s", ssid),
fmt.Sprintf("/etc/NetworkManager/system-connections/%s.nmconnection", ssid),
}
outputStr := ""
for _, p := range paths {
output, err := exec.Command("sudo", "cat", p).CombinedOutput()
if err == nil {
outputStr = strings.TrimSpace(string(output))
break
} else {
outputStr = ""
}
}
if outputStr == "" {
return "", errors.New("could not get password. please make sure you have the root permission")
}
ret := regexp.MustCompile(`(?:psk|password)=(.+)`).FindStringSubmatch(outputStr)
if len(ret) < 1 {
return "", errors.New("could not get SSID")
}
return strings.TrimSpace(ret[1]), nil
}
func WIFISSID() (name string, err error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command("sh", "-c", "iwgetid -r")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", errors.New(stderr.String())
}
return strings.TrimSpace(stdout.String()), nil
}