1年前
⋅
5
package ipset
import (
"bytes"
"fmt"
"io/ioutil"
"os/exec"
"strconv"
)
type Ipset struct {
IP string
Netmask string
GateWay string
DNS1 string
DNS2 string
}
// Ping 执行ping命令
func (i *Ipset) Ping(timeout int) bool {
var to = strconv.Itoa(timeout)
cmd := exec.Command("ping", i.IP, "-c", "1", "-w", to, "-W", to)
if cmd == nil {
return false
}
err := cmd.Run()
return err == nil
}
// Start 设置并启动服务
func (i *Ipset) Start() bool {
err := i.command()
if err != nil {
return false
}
err = i.file()
if err != nil {
return false
}
return i.restart()
}
// 启动网络生效
func (i *Ipset) restart() bool {
cmd := exec.Command("service", "network", "restart")
if cmd == nil {
return false
}
_, err := cmd.Output()
if err != nil {
return false
}
return true
}
// 修改配置文件
func (i *Ipset) file() error {
buf := bytes.NewBuffer([]byte{})
buf.WriteString("DEVICE=eth0\n")
buf.WriteString("BOOTPROTO=static\n")
buf.WriteString("ONBOOT=yes\n")
buf.WriteString(fmt.Sprintf("IPADDR=%s\n", i.IP))
buf.WriteString(fmt.Sprintf("NETMASK=%s\n", i.Netmask))
buf.WriteString(fmt.Sprintf("GATEWAY=%s\n", i.GateWay))
if i.DNS1 != "" {
buf.WriteString(fmt.Sprintf("DNS1=%s\n", i.DNS1))
}
if i.DNS2 != "" {
buf.WriteString(fmt.Sprintf("DNS2=%s\n", i.DNS2))
}
file := &Eth0{filename: NET_FILE}
return file.Write(buf.Bytes())
}
// 执行命令修改ip地址
func (i *Ipset) command() error {
err := i.create("./file.sh")
if err != nil {
return err
}
cmd := exec.Command("/bin/bash", "./file.sh")
_, err = cmd.Output()
if err != nil {
return err
}
return nil
}
// 命令行写入
func (i *Ipset) create(filename string) error {
buf := bytes.NewBuffer([]byte{})
buf.WriteString("#!/bin/bash\n")
buf.WriteString("echo 设置ip子网掩码\n")
buf.WriteString(fmt.Sprintf("ifconfig eth0 %s netmask %s\n", i.IP, i.Netmask))
buf.WriteString(fmt.Sprintf("route add default gw %s\n", i.GateWay))
err := ioutil.WriteFile(filename, buf.Bytes(), 0755)
if err != nil {
return err
}
return nil
}