#!/bin/bash
# sts内容(IP与域名映射)
HOSTS_ENTRIES=(
"172.16.171.100 xx1.com"
"172.16.171.101 xx2.com"
"172.16.171.102 xx3.com"
"172.16.171.103 xx4.com"
)
# 检查是否为root用户
if [[ $EUID -ne 0 ]]; then
echo "错误:此脚本需要root权限运行,请使用 sudo 执行!" >&2
exit 1
fi
if [ -f "/etc/hosts.bak" ]; then
cp -f /etc/hosts.bak /etc/hosts
echo "重置hosts:hosts.bak"
fi
# 备份原hosts文件(可选)
if [ ! -f "/etc/hosts.bak" ]; then
cp /etc/hosts /etc/hosts.bak
echo "备份文件:hosts.bak"
fi
# 写入新的hosts条目
for entry in "${HOSTS_ENTRIES[@]}"; do
# 检查是否已存在相同记录
if ! grep -q "$entry" /etc/hosts; then
echo "$entry" >>/etc/hosts
echo "已添加:$entry"
else
echo "已存在,跳过:$entry"
fi
done
echo "操作完成!当前hosts文件内容:"
echo "----------------------------------"
tail -n 3 /etc/hosts
域名映射小工具,测试环境还挺好用
win10版本移步:win10修改hosts小工具_host修改工具-优快云博客