开机启动时修改Hostname
开机自动运行脚本
原理:Linux开机启动时会执行/etc/profile.d/目录下的脚本
开机启动时修改Hostname
解决:在/etc/profile.d/目录下新建一个hostname.sh 文件,内容如下
## 把IP获取到写入/etc/hostname
ip -4 addr show ens33|grep inet |awk '{print $2}' |sed 's/\//-/g' | xargs nmcli g hostname
开机启动时,自动添加宿主机hosts映射
WSL中,开机时自动检测宿主机的IP,并添加hosts映射,以下为脚本内容
#!/bin/bash
# 自动检测宿主机 IP 并更新 /etc/hosts 中的 win.host 映射
# set -e # 不能设置为严格模式,不然输入任何错误都会退出整个shell
# 获取默认路由对应的接口
DEFAULT_IF=$(ip route | awk '/default/ {print $5; exit}')
if [ -z "$DEFAULT_IF" ]; then
echo "⚠️ 未检测到默认出口接口,可能未联网。使用本机 127.0.0.1 作为宿主机 IP"
HOST_IP="127.0.0.1"
else
# 从该接口获取 IPv4 地址
HOST_IP=$(ip -4 addr show "$DEFAULT_IF" 2>/dev/null \
| grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -1)
# 如果接口没有 IP,也回退到 127.0.0.1
if [ -z "$HOST_IP" ]; then
echo "⚠️ 接口 $DEFAULT_IF 未分配 IPv4 地址,使用 127.0.0.1"
HOST_IP="127.0.0.1"
fi
fi
echo "Detected Host IP: $HOST_IP"
# 更新 /etc/hosts
if grep -q "win.host" /etc/hosts; then
sudo sed -i "s/^.*win\.host.*\$/$HOST_IP win.host/" /etc/hosts || true
else
echo "$HOST_IP win.host" | sudo tee -a /etc/hosts >/dev/null || true
fi
echo "✅ /etc/hosts 已更新: $HOST_IP win.host"

浙公网安备 33010602011771号