常寧網(wǎng)站建設(shè)去了外包簡歷就毀了嗎
window下的wsl2 開發(fā)中使用到?域名映射,但是WSL2?每次啟動都會被分配一個虛擬的?ip?地址,每次啟動虛擬ip?都不一樣,導(dǎo)致要頻繁?更改 window?的?hosts?文件,太麻煩了,所以寫一個自動執(zhí)行的 .sh?腳本,每次啟動之后?自動獲取虛擬ip,并寫入到?window?的?hosts?文件中。
1、在?當(dāng)前用戶目錄下?新建?script/get_wsl_ip.sh?文件腳本,我的路徑?\\wsl$\Ubuntu\home\user1\scripts
#!/usr/bin/bash# 為 win 設(shè)置 wsl host# win hosts 文件路徑
win_hosts_path="/mnt/c/Windows/System32/drivers/etc/hosts"# 為 wsl2 設(shè)置的域名
wsl_domain="dev.domain.com"# 獲取 wsl2 的 ip
wsl_ip=$(ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}')if [ -z "$wsl_ip" ]; thenecho "無法獲取 WSL2 的 IP 地址,請檢查網(wǎng)絡(luò)配置。"exit 1
fi# 判斷是否已存在 wsl2 的域名,如果存在則修改,否則追加
if grep -wq "$wsl_domain" "$win_hosts_path"; then# 備份原始 hosts 文件cp "$win_hosts_path" "$win_hosts_path.bak"# 使用臨時文件避免權(quán)限問題temp_file=$(mktemp)sed "s/.* $wsl_domain/$wsl_ip $wsl_domain/" "$win_hosts_path" > "$temp_file"sudo mv "$temp_file" "$win_hosts_path"
else# 追加記錄到 hosts 文件echo "$wsl_ip $wsl_domain" | sudo tee -a "$win_hosts_path" > /dev/null
fi# 為 wsl 設(shè)置 win host
wsl_hosts_path="/etc/hosts"
win_domain="win"
win_ip=$(grep "nameserver" /etc/resolv.conf | awk '{print $2}')if [ -z "$win_ip" ]; thenecho "無法獲取 Windows 主機的 IP 地址,請檢查網(wǎng)絡(luò)配置。"exit 1
fiif grep -wq "$win_domain" "$wsl_hosts_path"; then# 使用臨時文件避免權(quán)限問題temp_file=$(mktemp)sed "s/.* $win_domain/$win_ip $win_domain/" "$wsl_hosts_path" > "$temp_file"sudo mv "$temp_file" "$wsl_hosts_path"
else# 追加記錄到 hosts 文件echo "$win_ip $win_domain" | sudo tee -a "$wsl_hosts_path" > /dev/null
fiecho "設(shè)置完成。"
2、修改當(dāng)前用戶目錄下? \\wsl$\Ubuntu\home\user1\.bashrc,在末尾加
# Call custom script to get WSL IP and save it for host update
/home/user1/scripts/get_wsl_ip.sh
3、重啟?wsl?即可
wsl --shutdown
4、window?的?hosts?會自動添加下面的?ip?地址映射
# wsl 2 虛擬的IP
172.23.38.130 dev.domain.com
?