一、需求背景
当每次新创建系统(虚拟机克隆除外),静态IP地址都需要重新设置,因此可以编写一个静态IP初始化脚本,方便静态IP设置。
二、详细操作
1.创建一个脚本文件,例如:staticIP.sh
vim staticIP.sh
2.添加内容并保存
#!/bin/bash
echo "====================="
echo "| Static IP Setting |"
echo "====================="
# 输入静态IP地址
read -p "Input your IPADDR:" ipaddr
# 输入子网掩码
read -p "Input your NETMASK:" netmask
# 输入网关
read -p "Input your GATEWAY:" gateway
# 输入DNS地址
read -p "Input your DNS1:" dns1
# 将内容写入到/etc/sysconfig/network-scripts/ifcfg-ens33
echo "TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
DEVICE=ens33
ONBOOT=yes
IPADDR=${ipaddr}
NETMASK=${netmask}
GATEWAY=${gateway}
DNS1=${dns1}
" > /etc/sysconfig/network-scripts/ifcfg-ens33
# 重启网络使其生效
systemctl restart network
echo "Static IP Setting Is Succeed"
3.赋权
# 赋予执行权限
chmod +x staticIP.sh
[root@localhost opt]# ll staticIP.sh
-rwxr-xr-x. 1 root root 691 1月 2 23:02 staticIP.sh
[root@localhost opt]#
4.实际操作
[root@localhost opt]# ./staticIP.sh
=====================
| Static IP Setting |
=====================
Input your IPADDR:192.168.61.200
Input your NETMASK:255.255.255.0
Input your GATEWAY:192.168.61.2
Input your DNS1:114.114.114.114
Static IP Setting Is Succeed
[root@localhost opt]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:4e:89:21 brd ff:ff:ff:ff:ff:ff
inet 192.168.61.200/24 brd 192.168.61.255 scope global noprefixroute ens33
valid_lft forever preferred_lft forever
inet6 fe80::f809:a348:802d:8e1/64 scope link noprefixroute
valid_lft foreve
以上,请参考!