Go语言关闭docker虚拟网卡

关闭虚拟网卡,对日志输出的字符串进行重新编码并写入到日志文件。
windows在安装docker desktop后,启动后会启动虚拟网卡(vEthernet (WSL)或vEthernet (Default Switch)),可能会造成一切软件需要网卡广播时的问题,为解决这个问题,需要关闭虚拟网卡。

package main

import (
	"bufio"
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"log"
	"net"
	"os"
	"os/exec"
	"time"
)

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func ConvertByte2String(byte []byte, charset Charset) string {

	var str string
	switch charset {
	case GB18030:
		decodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(byte)
		str = string(decodeBytes)
	case UTF8:
		fallthrough
	default:
		str = string(byte)
	}

	return str
}
func main() {
	fmt.Println("等待关闭虚拟网卡,请勿关闭窗口...")
	//结束通道
	finish := make(chan bool)
	//需要关闭的网络
	network := map[string]string{"0": "vEthernet (WSL)", "1": "vEthernet (Default Switch)"}
	//设置日志存储位置
	logfile := "c:/disableNet.log"

	file, err := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.ModePerm)
	defer file.Close()
	if err != nil {
		log.Fatal("create file err: ", err)
	}
	log.SetOutput(file)
	//每两秒轮询关闭虚拟网卡
	go func() {
		for {
			interfaces, err := net.Interfaces()
			if err != nil {
				log.Fatal(err)
			}
			log.Println("查看需要关闭的网卡有没有启动")
			for _, v := range interfaces {
				for i, name := range network {
					log.Println("network name:", name)
					if v.Name == name {
						log.Println("准备关闭,", name)
						closeNet(name)
						delete(network, i)
						if len(network) == 1 {
							time.AfterFunc(time.Second*5, func() {
								finish <- true
							})
						}
						if len(network) == 0 {
							finish <- true
						}
					}
				}
			}
			time.Sleep(time.Second * 2)
		}

	}()
	//超时后直接退出
	select {
	case <-finish:
		log.Println("虚拟网卡已关闭")
	case <-time.After(time.Second * 60):
		log.Println("关闭超时")
	}

}

func closeNet(netName string) {
	cmdLine := "disable-NetAdapter -Name '" + netName + "' -IncludeHidden -confirm:$false"

	command := exec.Command("powershell", cmdLine)

	stdoutPipe, err := command.StdoutPipe()
	if err != nil {
		log.Println("stdout err: ", err)
	}
	stderrPipe, err := command.StderrPipe()
	if err != nil {
		log.Println("stderr err: ", err)
	}
	err = command.Start()
	if err != nil {
		log.Fatal("command run err: ", err)
	}
	stdout := bufio.NewScanner(stdoutPipe)
	stderr := bufio.NewScanner(stderrPipe)
	go func() {
		for stderr.Scan() {
			log.Fatalln(ConvertByte2String(stderr.Bytes(), GB18030))
		}
	}()

	go func() {
		for stdout.Scan() {
			log.Println(ConvertByte2String(stdout.Bytes(), GB18030))
		}
	}()

	err = command.Wait()
	if err != nil {
		log.Println(err)
	}
	log.Println(netName, "已关闭")
}

你可能感兴趣的:(docker,golang,linux)