From b50ab8c04f6ae6097701a2a2b0f3cd9226ad77e3 Mon Sep 17 00:00:00 2001
From: zhangzengfei <zhangzengfei@iotlink.com>
Date: 星期三, 30 十月 2019 15:19:23 +0800
Subject: [PATCH] fix: change network settings
---
controllers/syssetcont.go | 14 ++
scripts/netconfig | 122 ++++++++++++++++++++
extend/sys/system.go | 116 +++++++++++++++++++
extend/util/util.go | 42 -------
extend/config/config.go | 51 ++++----
5 files changed, 277 insertions(+), 68 deletions(-)
diff --git a/controllers/syssetcont.go b/controllers/syssetcont.go
index afab0db..3be8a7a 100644
--- a/controllers/syssetcont.go
+++ b/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)
diff --git a/extend/config/config.go b/extend/config/config.go
index 0a7b6b0..4dd7ec8 100644
--- a/extend/config/config.go
+++ b/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)
}
diff --git a/extend/sys/system.go b/extend/sys/system.go
index 563d85b..526093e 100644
--- a/extend/sys/system.go
+++ b/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")
diff --git a/extend/util/util.go b/extend/util/util.go
index e680ee6..542dd2c 100644
--- a/extend/util/util.go
+++ b/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 {
diff --git a/scripts/netconfig b/scripts/netconfig
new file mode 100644
index 0000000..6b9fae0
--- /dev/null
+++ b/scripts/netconfig
@@ -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
+
+# 閲嶅惎鐩稿叧鏈嶅姟, 涓嶆洿鏀筰p鐨勬儏鍐典笅, 閲嶅惎缃戠粶鍗冲彲
+localip=$(/sbin/ifconfig $INTERFACE | grep inet | grep -v inet6 | awk '{printf $2}' | tr -d "addr:")
+if [ "$localip" != "$IPADDR" ]; then
+ service_restart
+fi
+
+exit 0
\ No newline at end of file
--
Gitblit v1.8.0