zhangzengfei
2019-10-29 b50ab8c04f6ae6097701a2a2b0f3cd9226ad77e3
fix: change network settings
1个文件已添加
4个文件已修改
345 ■■■■ 已修改文件
controllers/syssetcont.go 14 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
extend/config/config.go 51 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
extend/sys/system.go 116 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
extend/util/util.go 42 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
scripts/netconfig 122 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/syssetcont.go
@@ -159,11 +159,13 @@
    } else {
        resData["server_id"] = sysconf.GetServerId()
        resData["server_name"] = sysconf.GetServerName()
        ipv4, mask, _ := util.GetLocalIP(config.Server.NetworkAdapter)
        gateway, _ := util.GetDefaultRoute(config.Server.NetworkAdapter)
        ipv4, mask, _ := sys.GetLocalIP(config.Server.NetworkAdapter)
        gateway, _ := sys.GetDefaultRoute(config.Server.NetworkAdapter)
        dns, _ := sys.GetDnsServer()
        resData["ip"] = ipv4
        resData["subMask"] = mask
        resData["gateway"] = gateway
        resData["dns"] = dns
        resData["deviceNum"] = config.Server.DeviceNum
        resData["deviceType"] = config.Server.DeviceType
@@ -193,6 +195,14 @@
    var api dbapi.SysSetApi
    paramBody := make(map[string]interface{}, 0)
    paramBody["serverName"] = dev_name
    // 设置ip
    isOk, msg := sys.SetNetworkConfig(c.PostForm("ip"), c.PostForm("subMask"), c.PostForm("gateway"), c.PostForm("dns"))
    if !isOk {
        util.ResponseFormat(c, code.ComError, msg)
        return
    }
    b, data := api.SaveServerInfo(paramBody)
    if b { // 查询是否存在
        util.ResponseFormat(c, code.Success, data)
extend/config/config.go
@@ -1,33 +1,36 @@
package config
import (
    "github.com/spf13/viper"
    "log"
    "github.com/spf13/viper"
)
type server struct {
    Runmode   string `mapstructure: "runmode"`
    JwtSecret string `mapstructure: "jwtSecret"`
    JwtExpire string `mapstructure: "jwtExpire"`
    Url       string `mapstructure: "url"`
    AnalyServerId string `mapstructure: "analyServerId"`
    Runmode        string `mapstructure: "runmode"`
    JwtSecret      string `mapstructure: "jwtSecret"`
    JwtExpire      string `mapstructure: "jwtExpire"`
    Url            string `mapstructure: "url"`
    AnalyServerId  string `mapstructure: "analyServerId"`
    NetworkAdapter string `mapstructure: "networkAdapter"`
    DeviceNum string `mapstructure: "deviceNum"` //设备编号
    DeviceType string `mapstructure: "deviceType"`  //设备型号
    DeviceSerialNum string `mapstructure: "deviceSerialNum"`  //设备序列号
    MasterVersion string `mapstructure: "masterVersion"` //主控版本
    WebVersion string `mapstructure: "webVersion"`  //web版本
    ChannelCount string `mapstructure: "channelCount"`  //通道个数
    DiskCount string `mapstructure: "diskCount"`  //硬盘个数
    DeviceNum       string `mapstructure: "deviceNum"`       //设备编号
    DeviceType      string `mapstructure: "deviceType"`      //设备型号
    DeviceSerialNum string `mapstructure: "deviceSerialNum"` //设备序列号
    MasterVersion   string `mapstructure: "masterVersion"`   //主控版本
    WebVersion      string `mapstructure: "webVersion"`      //web版本
    ChannelCount    string `mapstructure: "channelCount"`    //通道个数
    DiskCount       string `mapstructure: "diskCount"`       //硬盘个数
    SysServerPort string `mapstructure: "SysServerPort"`
}
var Server = &server{}
// wp add es 索引 以及 IP port
type esinfo struct {
    Shards string         `mapstructure:"shards"`
    EsIndex  esindexlist `mapstructure:"index"`
    Shards  string      `mapstructure:"shards"`
    EsIndex esindexlist `mapstructure:"index"`
}
type esindexlist struct {
@@ -42,7 +45,7 @@
}
type sopath struct {
    Ip string `mapstructure:"ip"`
    Ip   string `mapstructure:"ip"`
    Port string `mapstructure:"port"`
}
@@ -51,18 +54,18 @@
var EsInfo = &esinfo{}
type facedetect struct {
    Ip string `mapstructure:"Ip"`
    Port int `mapstructure:"port"`
    Ip   string `mapstructure:"Ip"`
    Port int    `mapstructure:"port"`
}
type dbpersoncompare struct {
    Ip string `mapstructure:"ip"`
    Port int `mapstructure:"port"`
    Ip   string `mapstructure:"ip"`
    Port int    `mapstructure:"port"`
}
type espersoncompare struct {
    Port int `mapstructure:"port"`
    Ips []string `mapstructure:"ips"`
    Port int      `mapstructure:"port"`
    Ips  []string `mapstructure:"ips"`
}
var DbPersonCompInfo = &dbpersoncompare{}
@@ -84,8 +87,8 @@
    }
    viper.UnmarshalKey("es", EsInfo)
    viper.UnmarshalKey("server", Server)
    viper.UnmarshalKey("sopath",SoPath)
    viper.UnmarshalKey("sopath", SoPath)
    viper.UnmarshalKey("facedetect", FaceDetectSet)
    viper.UnmarshalKey("dbpersoncompare",DbPersonCompInfo)
    viper.UnmarshalKey("dbpersoncompare", DbPersonCompInfo)
    viper.UnmarshalKey("espersoncompare", EsCompServerInfo)
}
extend/sys/system.go
@@ -1,14 +1,58 @@
package sys
import (
    "encoding/json"
    "errors"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
    "os/exec"
    "strconv"
    "webserver/extend/config"
    "webserver/extend/util"
    "fmt"
    "net"
    "strings"
    "time"
)
func execRootCommand(cmd string) (bool, string) {
    serverPort := config.Server.SysServerPort
    if serverPort == "" {
        serverPort = "18081"
    }
    sysConfigServer := fmt.Sprintf("http://127.0.0.1:%s/api/v1/command/exec", serverPort)
    resp, err := http.PostForm(sysConfigServer, url.Values{"command": {cmd}})
    if err != nil {
        return false, err.Error()
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return false, err.Error()
    }
    type response struct {
        Code    int    `json:"code"`
        Success bool   `json:"success"`
        Msg     string `json:"msg"`
        CMD     string `json:"cmd"`
        Data    string `json:"data"`
    }
    var rsp response
    if err := json.Unmarshal(body, &rsp); err != nil {
        return false, err.Error()
    }
    fmt.Println(body)
    fmt.Println(rsp)
    return rsp.Success, rsp.Data
}
// 检查 root权限
func CheckRootPermissions() bool {
@@ -20,6 +64,78 @@
    return true
}
// 获取本机网卡IP
func GetLocalIP(networkName string) (ipv4 string, mask string, err error) {
    interfaces, err := net.Interfaces()
    if err != nil {
        return "", "", err
    }
    for _, i := range interfaces {
        byName, err := net.InterfaceByName(i.Name)
        if err != nil {
            return "", "", err
        }
        addresses, err := byName.Addrs()
        for _, v := range addresses {
            if ipnet, ok := v.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
                if ipnet.IP.To4() != nil {
                    if byName.Name == networkName {
                        maskStr := ipnet.Mask.String()
                        mask64, _ := strconv.ParseUint(maskStr, 16, 32)
                        return ipnet.IP.String(), util.IpIntToString(int(mask64)), nil
                    }
                }
            }
        }
    }
    return "", "", errors.New("ipv4 not found")
}
// 获取本机网关ip
func GetDefaultRoute(networkName string) (route string, err error) {
    cmdStr := fmt.Sprintf("ip route show | grep -P \"^default.*%s\" | awk '{printf $3}'", networkName)
    cmd := exec.Command("/bin/sh", "-c", cmdStr)
    b, err := cmd.Output()
    if err != nil {
        return "", err
    }
    return string(b), nil
}
func GetDnsServer() (dns string, err error) {
    cmd := exec.Command("/bin/sh", "-c", "cat /etc/resolv.conf | grep nameserver | head -1 |awk '{printf $2}'")
    b, err := cmd.Output()
    if err != nil {
        return "", err
    }
    return string(b), nil
}
// 配置服务器网络
func SetNetworkConfig(ipv4, netmask, gateway, dns string) (bool, string) {
    networkConfigScript := "/opt/vasystem/bin/netconfig"
    ifname := config.Server.NetworkAdapter
    localIPv4, localNetMask, _ := GetLocalIP(ifname)
    localGW, _ := GetDefaultRoute(ifname)
    localDNS, _ := GetDnsServer()
    if localIPv4 == ipv4 && localNetMask == netmask && localGW == gateway && localDNS == dns {
        return true, ""
    }
    // 检查文件是否存在
    if _, err := os.Stat(networkConfigScript); err != nil {
        return false, "network Config Script not exist"
    }
    // # netconfig enp59s0f0 192.168.1.2 255.255.255.0 192.168.1.1 192.168.100.1
    cmdStr := fmt.Sprintf("%s %s %s %s %s %s", networkConfigScript, ifname, ipv4, netmask, gateway, dns)
    // return exec.Command("/bin/sh", "-c", cmdStr).Run() == nil
    return execRootCommand(cmdStr)
}
// 配置时区
func TimeZone() (string, int64) {
    cmd := exec.Command("/bin/sh", "-c", "echo -n $TZ")
extend/util/util.go
@@ -3,12 +3,9 @@
import (
    "bytes"
    "encoding/json"
    "errors"
    "image"
    "io/ioutil"
    "net"
    "net/http"
    "os/exec"
    "strconv"
    "webserver/extend/code"
@@ -134,45 +131,6 @@
        y1_new = int(i.Height)
    }
    return
}
// 获取本机网卡IP
func GetLocalIP(networkName string) (ipv4 string, mask string, err error) {
    interfaces, err := net.Interfaces()
    if err != nil {
        return "", "", err
    }
    for _, i := range interfaces {
        byName, err := net.InterfaceByName(i.Name)
        if err != nil {
            return "", "", err
        }
        addresses, err := byName.Addrs()
        for _, v := range addresses {
            if ipnet, ok := v.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
                if ipnet.IP.To4() != nil {
                    if byName.Name == networkName {
                        maskStr := ipnet.Mask.String()
                        mask64, _ := strconv.ParseUint(maskStr, 16, 32)
                        return ipnet.IP.String(), IpIntToString(int(mask64)), nil
                    }
                }
            }
        }
    }
    return "", "", errors.New("ipv4 not found")
}
func GetDefaultRoute(networkName string) (route string, err error) {
    cmdStr := fmt.Sprintf("ip route show | grep -P \"^default.*%s\" | awk '{print $3}'", networkName)
    cmd := exec.Command("/bin/sh", "-c", cmdStr)
    b, err := cmd.Output()
    if err != nil {
        return "", err
    }
    return string(b), nil
}
func StringIpToInt(ipstring string) int {
scripts/netconfig
New file
@@ -0,0 +1,122 @@
#!/bin/bash
# 系统网络配置文件
NETWORK_CONFIG_FILE="/etc/network/interfaces"
LOG_FILE="/opt/vasystem/logs/netconfig.log"
# basic系统服务关闭脚本
SERVICE_STOP_CMD=""
# basic系统服务启动脚本
SERVICE_START_CMD=""
INTERFACE="$1"
IPADDR="$2"
NETMASK="$3"
GATEWAY="$4"
DNSSERVER="$5"
Usage(){
    cat <<EOF
$0 : missing operand
Usage:
    $0 <ifname> <ipaddr> <netmask> <gateway> [dns-server]
EOF
    exit 1
}
n_log() {
    v_time=$(date "+%Y-%m-%d %H:%M:%S")
    echo "$v_time $*" >>$LOG_FILE
}
write_interfaces()
{
echo "auto lo
iface lo inet loopback
auto $INTERFACE
iface $INTERFACE inet static
address $IPADDR
netmask $NETMASK
gateway $GATEWAY
dns-nameserver $DNSSERVER
" > $NETWORK_CONFIG_FILE
ret=$?
n_log "write_interfaces. ret: $ret"
return $ret
}
validate_ip()
{
    if [[ $1 =~ ^([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$ ]]; then
        return 0
    fi
    return 1
}
network_restart()
{
    # 重启网络
    /etc/init.d/networking restart
    ip addr flush dev $INTERFACE
    ifdown $INTERFACE
    ifup $INTERFACE
    n_log "network restart."
    sleep 3
}
service_restart()
{
    n_log "service restart." >>$LOG_FILE
    # 重启basic服务
    su basic -c "sh /opt/startAllServices.sh &"
}
# Start Execution
n_log "Start NetConfig Execution, CMD: $*"
# 校验参数个数
if [ $# -lt 4 ]; then
    Usage
fi
# 验证接口是否存在
ifconfig | grep -q $INTERFACE || exit 1
# 校验IP合法性
i=0
while [ $# -ne 0 ]
do
    if [ $i -gt 0 -a $i -lt 4 ]; then
        validate_ip $1 || exit 1
    fi
    shift
    let i+=1
done
if [ "$DNSSERVER" == "" ]; then
    DNSSERVER=$GATEWAY
fi
# 配置接口
write_interfaces || {
    echo -n "write interfaces failure"
    exit 1
}
# 重启网络
network_restart
# 重启相关服务, 不更改ip的情况下, 重启网络即可
localip=$(/sbin/ifconfig $INTERFACE | grep inet | grep -v inet6 | awk '{printf $2}' | tr -d "addr:")
if [ "$localip" != "$IPADDR" ]; then
    service_restart
fi
exit 0