* Copyright (c) 2025 Bocloud Technologies Co., Ltd.
* installer is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain n copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
******************************************************************/
package syscompat
import (
"bufio"
"os"
"strings"
"gopkg.openfuyao.cn/bkeadm/utils"
)
func SetHosts(ip, host string) error {
file, err := os.Open("/etc/hosts")
if err != nil {
return err
}
defer file.Close()
lines := make([]string, 0)
scanner := bufio.NewScanner(file)
found := false
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, host) {
line = ip + "\t" + host
found = true
}
lines = append(lines, line)
}
if !found {
lines = append(lines, ip+"\t"+host)
}
file, err = os.OpenFile("/etc/hosts", os.O_WRONLY|os.O_TRUNC, utils.DefaultFilePermission)
if err != nil {
return err
}
defer file.Close()
for _, line := range lines {
_, err = file.WriteString(line + "\n")
if err != nil {
return err
}
}
return nil
}