Parcourir la source

项目初始化

huangyan il y a 5 mois
commit
d8dfba36fe
9 fichiers modifiés avec 318 ajouts et 0 suppressions
  1. 7 0
      .gitattributes
  2. 8 0
      .idea/.gitignore
  3. 8 0
      .idea/modules.xml
  4. 77 0
      .idea/remote-targets.xml
  5. 9 0
      .idea/restNetwork.iml
  6. 6 0
      .idea/vcs.xml
  7. 3 0
      go.mod
  8. 155 0
      main.go
  9. 45 0
      管理主机网卡切换工具操作文档.md

+ 7 - 0
.gitattributes

@@ -0,0 +1,7 @@
+# auto generated by UGit 
+*.mod filter=lfs diff=lfs merge=binary -text
+go.mod !filter=lfs !diff=lfs !merge=binary -text
+
+# auto generated by UGit 
+go.mod !filter=lfs !diff=lfs !merge=binary -text
+

+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# 默认忽略的文件
+/shelf/
+/workspace.xml
+# 基于编辑器的 HTTP 客户端请求
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/restNetwork.iml" filepath="$PROJECT_DIR$/.idea/restNetwork.iml" />
+    </modules>
+  </component>
+</project>

+ 77 - 0
.idea/remote-targets.xml

@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="RemoteTargetsManager">
+    <targets>
+      <target name="root@116.204.6.184:22" type="ssh/sftp" uuid="4ca7f587-d2a7-4f4d-a9d8-bc1c4640505f">
+        <config>
+          <option name="projectRootOnTarget" value="/root/restNetwork" />
+          <option name="serverName" value="root@116.204.6.184:22 password" />
+        </config>
+        <ContributedStateBase type="GoLanguageRuntime">
+          <config>
+            <option name="goPath" value="/root/go" />
+            <option name="goRoot" value="/usr/local/go/bin/go" />
+            <option name="goVersion" value="go1.16.12 linux/amd64" />
+          </config>
+        </ContributedStateBase>
+        <ContributedStateBase type="GoLanguageRuntime">
+          <config>
+            <option name="goRoot" value="/usr/local/go/bin/go" />
+          </config>
+        </ContributedStateBase>
+      </target>
+      <target name="root@116.204.6.184:23" type="ssh/sftp" uuid="16d4ddd9-83be-4615-b117-746198d1de5a">
+        <config>
+          <option name="projectRootOnTarget" value="/root/restNetwork" />
+          <option name="serverName" value="root@116.204.6.184:22 password" />
+        </config>
+        <ContributedStateBase type="GoLanguageRuntime">
+          <config>
+            <option name="goPath" value="/home/go/" />
+            <option name="goRoot" value="/usr/local/go/bin/go" />
+            <option name="goVersion" value="go1.23.2 linux/amd64" />
+          </config>
+        </ContributedStateBase>
+      </target>
+      <target name="root@116.204.6.184:24" type="ssh/sftp" uuid="561d65c7-5e4c-447f-9d6f-0ec67203344a">
+        <config>
+          <option name="projectRootOnTarget" value="/root/restNetwork" />
+          <option name="serverName" value="root@116.204.6.184:22 password" />
+        </config>
+        <ContributedStateBase type="GoLanguageRuntime">
+          <config>
+            <option name="goPath" value="/home/go/" />
+            <option name="goRoot" value="/usr/local/go/bin/go" />
+            <option name="goVersion" value="go1.23.2 linux/amd64" />
+          </config>
+        </ContributedStateBase>
+      </target>
+      <target name="root@116.204.6.184:25" type="ssh/sftp" uuid="a86a770c-0a2d-4333-8925-edab23a37140">
+        <config>
+          <option name="projectRootOnTarget" value="/root/restNetwork" />
+          <option name="serverName" value="root@116.204.6.184:22 password" />
+        </config>
+        <ContributedStateBase type="GoLanguageRuntime">
+          <config>
+            <option name="goPath" value="/home/go/" />
+            <option name="goRoot" value="/usr/local/go/bin/go" />
+            <option name="goVersion" value="go1.23.2 linux/amd64" />
+          </config>
+        </ContributedStateBase>
+      </target>
+      <target name="root@116.204.6.184:26" type="ssh/sftp" uuid="4d8bf4e2-e87e-4c8d-b1d8-96d8e4f46773">
+        <config>
+          <option name="projectRootOnTarget" value="/root/restNetwork" />
+          <option name="serverName" value="root@116.204.6.184:22 password" />
+        </config>
+        <ContributedStateBase type="GoLanguageRuntime">
+          <config>
+            <option name="goPath" value="/home/go/" />
+            <option name="goRoot" value="/usr/local/go/bin/go" />
+            <option name="goVersion" value="go1.23.2 linux/amd64" />
+          </config>
+        </ContributedStateBase>
+      </target>
+    </targets>
+  </component>
+</project>

+ 9 - 0
.idea/restNetwork.iml

@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="WEB_MODULE" version="4">
+  <component name="Go" enabled="true" />
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

+ 3 - 0
go.mod

@@ -0,0 +1,3 @@
+module restNetwork
+
+go 1.22

+ 155 - 0
main.go

@@ -0,0 +1,155 @@
+package main
+
+import (
+	"bytes"
+	"os/exec"
+	"strings"
+	"time"
+)
+
+const (
+	pingInterval = 60 * time.Second // 每10秒执行一次
+	ipToPing     = "203.34.49.130"  // 这里填写要ping的IP地址
+)
+
+// checkErr 输出错误信息并退出程序
+func checkErr(err error) {
+	if err != nil {
+		//log.Fatalf("Error: %s", err)
+	}
+}
+
+// ping 检查是否可以到达指定的IP地址
+func ping(ip string) bool {
+	cmd := exec.Command("ping", "-c", "1", ip)
+	var out bytes.Buffer
+	cmd.Stdout = &out
+	err := cmd.Run()
+	output := out.String()
+
+	if strings.Contains(output, "1 packets transmitted, 1 received") ||
+		strings.Contains(output, "1 packets transmitted, 1 received, 0% packet loss") {
+		return true
+	}
+	return err == nil
+}
+
+// checkNet 解析ip route命令的输出,返回接口与默认网关的映射以及当前默认网卡名
+func checkNet(net string) (map[string]string, string) {
+	var defaultNet string
+	m := make(map[string]string)
+	split := strings.Split(net, "\n")
+
+	for i := 0; i < len(split)-1; i++ {
+		line := strings.TrimSpace(split[i])
+		if line == "" {
+			continue
+		}
+
+		defaultNets := strings.Fields(line)
+		if len(defaultNets) > 1 {
+			for k := 0; k < len(defaultNets)-1; k++ {
+				if defaultNets[k] == "dev" && defaultNets[0] == "default" {
+					defaultNet = defaultNets[k+1]
+				}
+			}
+		}
+
+		i2 := strings.Fields(line)
+		if len(i2) > 1 {
+			for j := 0; j < len(i2)-1; j++ {
+				if i2[j] == "dev" {
+					netName := i2[j+1]
+					i3 := strings.Split(i2[j-1], ".")
+					if len(i3) > 1 {
+						ip := i3[0] + "." + i3[1] + "." + i3[2] + ".1"
+						m[netName] = ip
+					}
+				}
+			}
+		}
+	}
+
+	//fmt.Println("Routes:", m)
+	//fmt.Println("Default Net:", defaultNet)
+	return m, defaultNet
+}
+
+// updateRoute 更新默认路由
+func updateRoute(routes map[string]string, currentDefault, newDefault string) {
+	if currentDefault != newDefault {
+		cmdDel := exec.Command("ip", "route", "del", "default", "via", routes[currentDefault], "dev", currentDefault)
+		cmdAdd := exec.Command("ip", "route", "add", "default", "via", routes[newDefault], "dev", newDefault)
+
+		checkErr(cmdDel.Run())
+		checkErr(cmdAdd.Run())
+
+		//fmt.Printf("切换默认网卡  从 %s 到 %s\n", currentDefault, newDefault)
+	} else {
+		//fmt.Println("不需要切换默认网卡")
+	}
+}
+
+func main() {
+	for {
+		b := ping(ipToPing)
+		if b {
+			//fmt.Println("网络连接正常")
+
+			// 获取所有可用的网络接口及其默认网关
+			cmd := exec.Command("ip", "route")
+			var out bytes.Buffer
+			cmd.Stdout = &out
+			checkErr(cmd.Run())
+			output := out.String()
+			routes, currentDefault := checkNet(output)
+
+			// 判断当前默认网卡是否为 eth 网卡
+			if !strings.Contains(currentDefault, "eth") {
+				//fmt.Println("当前为无线网卡,正在切换到有线网卡")
+				for k := range routes {
+					if strings.Contains(k, "eth") {
+						updateRoute(routes, currentDefault, k)
+						break
+					}
+				}
+			} else {
+				//fmt.Println("当前为有线网卡,无需切换")
+			}
+		} else {
+			//fmt.Println("网络未接通正在重启....")
+
+			// 获取所有可用的网络接口及其默认网关
+			cmd := exec.Command("ip", "route")
+			var out bytes.Buffer
+			cmd.Stdout = &out
+			checkErr(cmd.Run())
+			output := out.String()
+			routes, currentDefault := checkNet(output)
+
+			// 找到一个新的默认网卡
+			newDefault := ""
+			for k := range routes {
+				if k != currentDefault {
+					newDefault = k
+					break
+				}
+			}
+
+			if newDefault != "" {
+				updateRoute(routes, currentDefault, newDefault)
+
+				// 再次检查是否可以 ping 通
+				b := ping(ipToPing)
+				if b {
+					//fmt.Println("切换网卡后网络连接正常")
+				} else {
+					//fmt.Println("切换网卡后仍然无法 ping 通")
+				}
+			} else {
+				//fmt.Println("没有找到其他可用的网卡")
+			}
+		}
+		time.Sleep(pingInterval)
+	}
+}

+ 45 - 0
管理主机网卡切换工具操作文档.md

@@ -0,0 +1,45 @@
+一:进入管理界面后通过  `lsblk ` 命令查询u盘名字
+
+![](https://cdn.nlark.com/yuque/0/2024/png/35884699/1729154050248-76276b57-7c4a-4ee1-8d83-505f129ec70c.png)
+
+二:通过命令  mkdir 创建目录  ` mkdir /usbsd`
+
+三:`mount /dev/sda1  /usbsd` 挂载u盘   
+
+四:切换到u盘目录下   `cd /usbsd`
+
+五:将工具移动到/opt 目录下   ` mv   restWork  /opt`  并切换到opt目录下 `cd /opt`
+
+六:创建文件`vim  <font style="color:rgb(44, 44, 54);">/etc/systemd/system/restwork.service</font>` 按下键盘`** i**`**键 将下方代码复制  然后按下键盘 **`**ESC**`** 键输入**`**: wq**`** 退出**
+
+```bash
+[Unit]
+Description=RestWork Service
+After=network.target
+
+[Service]
+ExecStart=/opt/restWork
+WorkingDirectory=/opt/
+StandardOutput=/var/log/restwork.log
+StandardError=/var/log/restwork-error.log
+Restart=always
+User=root
+
+[Install]
+WantedBy=multi-user.target
+```
+
+七:重启 依次输入以下命令重启
+
+```bash
+systemctl daemon-reload
+systemctl enable restwork.service
+systemctl start restwork.service
+```
+
+<font style="color:rgb(44, 44, 54);"></font>
+
+
+
+
+