From 5c4eb808302fac1d59d8ec02cad5f8be19189783 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AD=8F=E7=81=BF?= Date: Mon, 3 Jul 2023 11:34:45 +0800 Subject: [PATCH] =?UTF-8?q?hosts=E8=BD=ACjson?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/common/tools/hosts | 6 ++++++ src/common/tools/hosts.go | 40 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/common/tools/hosts create mode 100644 src/common/tools/hosts.go diff --git a/src/common/tools/hosts b/src/common/tools/hosts new file mode 100644 index 0000000..81b1295 --- /dev/null +++ b/src/common/tools/hosts @@ -0,0 +1,6 @@ +[webGroup1] +192.168.0.11 ansible_ssh_host=192.168.0.11 ansible_ssh_user=root ansible_ssh_pass=123.com ansible_ssh_port=3333 +192.168.0.12 ansible_ssh_host=192.168.0.12 ansible_ssh_user=root ansible_ssh_pass=1234.com ansible_ssh_port=2222 +[webGroup2] +192.168.1.11 ansible_ssh_host=192.168.1.11 ansible_ssh_user=admin ansible_ssh_pass=ccc.com ansible_ssh_port=11 +192.168.1.12 ansible_ssh_host=192.168.1.12 ansible_ssh_user=admin ansible_ssh_pass=111.com ansible_ssh_port=22 \ No newline at end of file diff --git a/src/common/tools/hosts.go b/src/common/tools/hosts.go new file mode 100644 index 0000000..0c61c24 --- /dev/null +++ b/src/common/tools/hosts.go @@ -0,0 +1,40 @@ +package tools + +import ( + "bufio" + "log" + "os" + "strings" +) + +func HostsToJson() (data map[string][]string, err error) { + f, err := os.Open(`/etc/ansible/hosts`) + if err != nil { + return nil, err + } + defer func() { + if err = f.Close(); err != nil { + log.Fatal(err) + } + }() + data = make(map[string][]string) + // 以这个文件为参数,创建一个 scanner + s := bufio.NewScanner(f) + var key string + var per []string + // 扫描每行文件,按行读取 + for s.Scan() { + if strings.HasPrefix(s.Text(), "[") && strings.HasSuffix(s.Text(), "]") { + key = s.Text() + per = []string{} + data[key] = per + } else { + data[key] = append(data[key], s.Text()) + } + } + err = s.Err() + if err != nil { + return nil, err + } + return data, nil +} -- 2.26.0