使用脚本的方式进行创建
在网上找到很多命令创建,可是重启服务器后,新增的ip地址都会丢失,于是我利用systemctl 服务来每次启动后自动附加ip地址,具体操作如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #!/bin/bash
if [ "$#" -ne 1 ]; then echo "Usage: $0 <ip_address>" exit 1 fi
ip_address=$1
interface=$(ip link show up | grep -v lo | awk '{print $2}' | sed 's/://g' | head -n 1)
if [ -z "$interface" ]; then echo "No active network interface found." exit 1 fi
nmcli con mod "$interface" ipv4.addresses "$ip_address/24"
nmcli connection up "$interface"
echo "Static IP address $ip_address has been set for $interface"
|
把文件保存到/opt/目录下,并赋予执行权限
1
| sudo vim /etc/systemd/system/set_ip.service
|
在文件中添加如下内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| [Unit]
Description = set_ip, nearby ip address After = network.target syslog.target Wants = network.target
[Service] Type = simple
ExecStart = bash /opt/set_ip.sh 10.0.0.118
[Install] WantedBy = multi-user.target
|
1 2
| sudo systemctl start set_ip.service sudo systemctl enable set_ip.service
|
这样,每次重启服务器后,就会自动附加IP地址,可以使用命令 ip addr
查看当前IP地址。
作者:
JenkinWoo
日期:
12/28, 2023 10:24:04
分类:
Linux
归档:
https://www.65.gs/2023/12/5df3591587e1.html