gpt4 book ai didi

go - 如何在特定部分创建一个具有接口(interface)名称的文件,然后从另一个文件中解析以修改 GO 中数据的接口(interface)?

转载 作者:IT王子 更新时间:2023-10-29 02:01:20 27 4
gpt4 key购买 nike

我正在构建一个程序来更改 Ubuntu 18.04.1 LTS 中机器的 IP 地址。所以基本上我是用

创建一个 YAML 文件模板
network:
ethernets:
{INTERFACE}:
dhcp4: no
addresses: [{IP}/24]
gateway4: {GATEWAY}
optional: true
nameservers:
addresses: [{DNS}]
{INTERFACE2}:
dhcp4: no
addresses: [{IP2}/24]
gateway4: {GATEWAY2}
optional: true
nameservers:
addresses: [{DNS2}]

现在我需要扫描此模板文件并通过 JSON 调用或作为 CLI 中的参数添加来自另一个文件的值。

因此应用程序将采用预先准备好的模板文件。例如yaml文件的示例模板。

需要3个参数这个模板文件,一个翻译文件(JSON),以及输出

翻译文件也可以在命令行上解析

它基于2列,IP等搜索变量及其新值该实用程序将搜索 {IP} 变量并将其替换为第二列值。

在 CLI 上它可能看起来像这样:

./searchreplace -intemplate='templateip.yaml' -translation='{IP},xxx.x.x.x; {SUBNET},yyy.yyy.yyy.y} -outfile=/tmp/newipfile.yaml

我当前的代码对数据进行硬编码并更改 IP,但我希望它位于单独的模板文件中。这是我当前的代码

    package main

import (
"bufio"
"fmt"
"log"
"net"
"os"
"os/exec"
"regexp"
"strings"
)

var pathdelete = "/etc/netplan/01-network-manager-all.yaml"
var ipv4Regex = regexp.MustCompile(`^(?:[0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$`)
var gatewayRegex = regexp.MustCompile(`^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`)
var nsRegex = regexp.MustCompile(`^(?:[0-9]\.){3}[0-9]{1,3}\,(?:[0-9]\.){3}[0-9]{1,3}$`)
var nicRegex = regexp.MustCompile(`e([a-z]+)`)

func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter the IP address: ")
IPaddress, _ := reader.ReadString('\n')
IPaddress = strings.TrimSuffix(IPaddress, "\n")

//sanity check
testInput := net.ParseIP(IPaddress)
if testInput.To4() == nil {
fmt.Printf("%v is not a valid IPv4 address\n", testInput)
} else {
fmt.Printf("It is a valid IP address\n")
writeFile()
readFile()
}
}
func writeFile() {
err01 := os.Truncate(pathdelete, 0)
if err01 != nil {
log.Fatal(err01)
}

//reading Network Cards
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter the Ethernet Card (for example : 'ens0N' or 'eth0') ")
nic, _ := reader.ReadString('\n')
nic = strings.TrimSuffix(nic, "\n")
if nicRegex.MatchString(nic) {
} else {
log.Fatal("Please check the name of the NIC Card you have entered")
os.Exit(1)
}

//reading IP Address and DNS
fmt.Print("Enter the IP address along with the DNS in the format xxx.xxx.x.xxx/yy ")
IP, _ := reader.ReadString('\n')
IP = strings.TrimSuffix(IP, "\n")

if ipv4Regex.MatchString(IP) {
} else {
log.Fatal("Please check the IP address you have entered")
os.Exit(1)
}

//reading Gateway
fmt.Print("Enter the gateway in the format xxx.xxx.x.x ")
gateway, _ := reader.ReadString('\n')
gateway = strings.TrimSuffix(gateway, "\n")
if gatewayRegex.MatchString(gateway) {
} else {
log.Fatal("Please check the Gateway you have entered")
os.Exit(1)
}

//reading Name servers
fmt.Print("Enter the nameservers seperated by comma(,) in the format x.x.x.x,y.y.y.y ")
ns, _ := reader.ReadString('\n')
ns = strings.TrimSuffix(ns, "\n")
if nsRegex.MatchString(ns) {
} else {
log.Fatal("Please check the Name Servers you have entered")
os.Exit(1)
}

// open file using READ & WRITE permission
var file, err = os.OpenFile(pathdelete, os.O_RDWR, 0644)
checkError(err)
defer file.Close()

// write some text to file
_, err = file.WriteString("# Let NetworkManager manage all devices on this system\nnetwork:\n version: 2\n renderer: NetworkManager\n")
if err != nil {
fmt.Println(err.Error())
return //must return here for defer statements to be called
}
_, err = file.WriteString(" ethernets:\n " + nic + ":\n dhcp4: no\n dhcp6: no\n")
if err != nil {
fmt.Println(err.Error())
return //same as above
}
_, err = file.WriteString(" addresses: [" + IP + "]\n gateway4: " + gateway + "\n nameservers:\n addresses: [" + ns + "]")
if err != nil {
fmt.Println(err.Error())
return //same as above
}

// save changes
err = file.Sync()
if err != nil {
fmt.Println(err.Error())
return //same as above
}
applyCmd := exec.Command("bash", "-c", "sudo netplan apply")
_, err2 := applyCmd.Output()
if err2 != nil {
panic(err2)
}
}

func readFile() {
// re-open file
var file, err = os.OpenFile(pathdelete, os.O_RDWR, 0644)
checkError(err)
defer file.Close()

// read file
var text = make([]byte, 1024)
n, err := file.Read(text)
if n > 0 {
fmt.Println("\nThe data you have entered is \n ")
fmt.Println(string(text))
}
//if there is an error while reading
//just print however much was read if any
//at return file will be closed
}

func checkError(err error) {
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
}

最佳答案

我能够通过转换命令行输入来实现这一点

./program --xyz.yaml --{interface} eth0 --IPaddress 192.168.1.233/24 --{gateway} 192.168.0.1 --DNS 8.8.3.8,8.8.8.3

我使用映射函数将 CLI 映射到字符串

func manyRandomArg() map[string]string {
rv := make(map[string]string)
for ix, x := range os.Args {
if x[:2] == "--" {
rv[x] = os.Args[ix+1]
}
}
return rv
}

然后我只对键进行了排序,并进行了搜索替换功能

keys := make([]string, 0, len(rv))
for key := range rv {
keys = append(keys, key)
}
sort.Strings(keys) //sort keys alphabetically

必须修剪 key 中的“--”部分

key0 = trimLeftChars(keys[0], 2)

使用的字符串替换函数是

r := strings.NewReplacer(key0, rv[keys[0]], key1, rv[keys[1]], key2, rv[keys[2]], key3, rv[keys[3]], key4, rv[keys[4]])

关于go - 如何在特定部分创建一个具有接口(interface)名称的文件,然后从另一个文件中解析以修改 GO 中数据的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52816069/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com