# 获取yaml文件中按照优先级的第一个
config_file=$(ls -t /etc/netplan/*.yaml | head -n1)
#判断是否为空
if [ -z "$config_file" ]; then
config_file="/etc/netplan/00-installer-config.yaml"
echo "不存在该文件"
else
echo "存在该文件"
cp "$config_file" "$config_file.bak"
fi
# $1 命令行输入的第一个参数 $2,$3,$4 分别是2,3,4
interface=$1 # Change this to match your system
# Set the desired static IP address, netmask, gateway, and DNS
static_ip=$2
gateway=$3
dns=$4
echo "$interface $static_ip $gateway $dns "
echo "$config_file"
# Create a new netplan configuration file
cat <<EOL > "$config_file"
network:
version: 2
renderer: networkd
ethernets:
$interface:
dhcp4: no
addresses: [$static_ip/24]
gateway4: $gateway
nameservers:
addresses: [$dns]
EOL
# 尝试应用新的配置
sudo netplan try
# 检查 netplan try 的结果 $?获取上一条命令的执行结果
if [ $? -eq 0 ]; then
echo "修改成功开始应用"
# 应用更改
sudo netplan apply
else
echo "网络配置失败,恢复之前的内容"
# 恢复之前的配置文件
#删除刚刚生成的文件
sudo rm "$config_file"
#将备份的文件重新恢复
mv "$config_file".bak "$config_file"
#这行有没有影响不大
sudo netplan apply
fi
最后运行
sudo bash xxx.sh 第一个参数 第二 .... ....