-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
107 lines (91 loc) · 2.03 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"bytes"
"fmt"
"net"
"os"
"os/exec"
"strings"
"text/template"
)
const (
IFUP = "ifup"
INTERFACES_FILE = "/etc/network/interfaces"
DOWN_INTERFACES_FILE = "/etc/network/downinterfaces"
TEMPLATE_PATH = "/home/vagrant/netman/interfaces.tmpl"
)
type Interfaces struct {
NetInt []NetInterface
}
type NetInterface struct {
InetName string
}
func main() {
var netInterfaces []NetInterface
ineti, err := net.Interfaces()
if err != nil {
panic(err)
}
for _, inter := range ineti {
if !strings.Contains(inter.Flags.String(), "up") {
netInterfaces = append(netInterfaces, NetInterface{InetName: inter.Name})
}
}
downInterfaces := Interfaces{NetInt: netInterfaces}
info := createInterfacesSetting(downInterfaces)
fmt.Printf("%s\n", info)
if err := createFile(INTERFACES_FILE, info); err != nil {
panic(err)
}
var tempInterfaces []string
for _, i := range downInterfaces.NetInt {
tempInterfaces = append(tempInterfaces, i.InetName)
if err := execUp(i.InetName); err != nil {
panic(err)
}
}
c := strings.Join(tempInterfaces, ",")
if err := createFile(DOWN_INTERFACES_FILE, c); err != nil {
panic(err)
}
if err := deleteDefaultRule(); err != nil {
panic(err)
}
}
func execUp(iname string) error {
cmd := exec.Command(IFUP, iname)
err := cmd.Start()
if err != nil {
return err
}
err = cmd.Wait()
return err
}
func createInterfacesSetting(interfaces Interfaces) string {
var tpl bytes.Buffer
tmpl := template.Must(template.ParseFiles(TEMPLATE_PATH))
tmpl.Execute(&tpl, interfaces)
return tpl.String()
}
func createFile(path string, content string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(content)
if err != nil {
return err
}
return nil
}
func deleteDefaultRule() error {
//deleting the default rule set automatically in order to have Internet.
cmd := exec.Command("sudo", "ip", "route", "del", "default")
err := cmd.Start()
if err != nil {
return err
}
err = cmd.Wait()
return err
}