CentOS7配置静态IP
2025-10-02 16:02:57

1. 环境准备

  1. Oracle VM VirtualBox
    下载地址:https://www.virtualbox.org/wiki/Downloads
  2. CentOS 7.9
    下载地址:https://mirrors.aliyun.com/centos/7.9.2009/isos/x86_64/?spm=a2c6h.25603864.0.0.3dccf5adbnhdJY

2. 调整网络模式

设置 → 网络 → 网卡1

  • 连接方式:桥接网卡
  • 名称:本机上网使用的网卡名称

image-20241205104936386


3. 网卡自启配置(可选)

如果在安装系统界面已经连接了网络,这一步可以跳过!

3.1. 检查网卡名称

1
nmcli device status

3.2. 配置网卡为开机自启

假设网卡名称为 enp0s3(请根据实际情况替换)

1
nmcli connection modify enp0s3 connection.autoconnect yes

3.3. 验证网卡配置

1
nmcli connection show enp0s3 | grep autoconnect

输出示例

1
2
3
4
connection.autoconnect:                 yes
connection.autoconnect-priority: 0
connection.autoconnect-retries: -1 (default)
connection.autoconnect-slaves: -1 (default)

4. 配置静态 IP

4.1. 方法一:修改网卡配置文件

4.1.1. 查看宿主机 IP

1
ipconfig

image-20241205113859194

可以看到宿主机的网关为192.168.148.20,请记住它,待会儿要用!!!!!!!

4.1.2. 编辑配置文件

1
vi /etc/sysconfig/network-scripts/ifcfg-enp0s3
  • 修改BOOTPROTO=static,既然要配置静态IP,那肯定要关闭DHCP嘛对吧!

    添加IPADDR=192.168.148.100,IP不用多说吧,IP地址必须与网关在同一个网段,否则通信无法正常进行。

    添加GATEWAY=192.168.148.20,来源于宿主机的网关。

    添加NETMASK=255.255.255.0

    添加DNS1=8.8.8.8

    添加DNS2=8.8.4.4

image-20241205114551520

4.1.3. 重启服务

1
systemctl restart network

4.1.4. 验证网络连通性

1
ping www.baidu.com

4.2. 方法二:使用 nmcli 工具

4.2.1. 查看网卡名称

1
nmcli device status

输出示例

1
2
3
DEVICE  TYPE      STATE      CONNECTION
enp0s3 ethernet connected enp0s3
lo loopback unmanaged --

4.2.2. 配置静态 IP

1
2
3
4
5
nmcli connection modify enp0s3 ipv4.addresses 192.168.148.100/24
nmcli connection modify enp0s3 ipv4.gateway 192.168.148.20
nmcli connection modify enp0s3 ipv4.dns "8.8.8.8,8.8.4.4"
nmcli connection modify enp0s3 ipv4.method manual
nmcli connection up enp0s3

4.2.3. 验证配置

1
nmcli -f ipv4.addresses,ipv4.gateway,ipv4.dns connection show enp0s3

输出示例

1
2
3
ipv4.addresses:                         192.168.148.100/24
ipv4.gateway: 192.168.148.20
ipv4.dns: 8.8.8.8,8.8.4.4

4.2.4. 验证网络连通性

1
ping www.baidu.com

4.2.5. 恢复 DHCP 模式(可选)

1
2
nmcli connection modify enp0s3 ipv4.method auto
nmcli connection up enp0s3

4.2.6. 删除 nmcli 静态配置(可选)

1
2
nmcli connection delete enp0s3
nmcli device connect enp0s3

4.3. 方法三:使用 nmtui 工具

4.3.1. 进入交互界面

1
nmtui

按照提示进入网卡配置界面

image-20241207104541968

4.3.2. 配置步骤

  1. IPv4 CONFIGURATION <Automatic> ——->>> IPv4 CONFIGURATION <Manual>
  2. show
  3. [X] Automatically connect
  4. <OK>
  5. <back>
  6. <quit>

image-20241207105524062

4.3.3. 重启系统

1
reboot

4.3.4. 验证 IP

1
ip a

4.3.5. 验证网络连通性

1
ping www.baidu.com