在 Linux 系统中,修改静态 IP 通常需要编辑网络配置文件,具体方法取决于你使用的发行版和网络管理工具(例如 `Netplan`、`NetworkManager` 或传统的 `ifcfg` 文件)。以下是几种常见的修改方法:
---
1. 基于 Netplan(Ubuntu 18.04 及更新版本)
Ubuntu 18.04+ 默认使用 Netplan 管理网络配置。
步骤:
1. 打开网络配置文件(通常在 `/etc/netplan/` 目录下,文件名可能是 `01-netcfg.yaml` 或类似的 `.yaml` 文件):
```bash
sudo nano /etc/netplan/01-netcfg.yaml
```
2. 修改内容,设置静态 IP,例如:
```yaml
network:
version: 2
renderer: networkd
ethernets:
enp0s3:
dhcp4: no
addresses:
- 192.168.1.100/24
gateway4: 192.168.1.1
nameservers:
addresses:
- 8.8.8.8
- 8.8.4.4
```
- `enp0s3` 是网卡名称,可以通过 `ip a` 或 `ifconfig` 查看。
- `addresses` 是你的静态 IP 和子网掩码。
- `gateway4` 是默认网关。
- `nameservers` 是 DNS 服务器地址。
3. 应用配置:
```bash
sudo netplan apply
```
4. 验证:
```bash
ip a
ping -c 4 8.8.8.8
```
---
2. 基于 NetworkManager(适用于大部分桌面环境,如 Ubuntu 桌面版、CentOS 等)
NetworkManager 提供图形界面和命令行工具 `nmcli`。
使用 `nmcli` 设置静态 IP:
1. 查看当前的网络连接:
```bash
nmcli connection show
```
2. 修改连接为静态 IP(假设连接名称为 `Wired connection 1`):
```bash
nmcli connection modify "Wired connection 1" ipv4.addresses 192.168.1.100/24
nmcli connection modify "Wired connection 1" ipv4.gateway 192.168.1.1
nmcli connection modify "Wired connection 1" ipv4.dns "8.8.8.8,8.8.4.4"
nmcli connection modify "Wired connection 1" ipv4.method manual
```
3. 重新激活连接:
```bash
nmcli connection up "Wired connection 1"
```
4. 验证:
```bash
ip a
ping -c 4 8.8.8.8
```
---
3. 基于 ifcfg 文件(CentOS 7/8 和部分 RHEL 系统)
CentOS 和 RHEL 系统常使用 `/etc/sysconfig/network-scripts/` 目录下的 `ifcfg-*` 文件管理网络。
步骤:
1. 编辑对应网卡的配置文件(假设网卡为 `ens33`):
```bash
sudo nano /etc/sysconfig/network-scripts/ifcfg-ens33
```
2. 修改或添加以下内容:
```
TYPE=Ethernet
BOOTPROTO=none
NAME=ens33
DEVICE=ens33
ONBOOT=yes
IPADDR=192.168.1.100
PREFIX=24
GATEWAY=192.168.1.1
DNS1=8.8.8.8
DNS2=8.8.4.4
```
3. 重启网络服务:
```bash
sudo systemctl restart network
```
4. 验证:
```bash
ip a
ping -c 4 8.8.8.8
```
---
4. 基于 `/etc/network/interfaces`(旧版 Debian/Ubuntu 系统)
Debian 和 Ubuntu 的旧版系统使用 `/etc/network/interfaces` 文件管理网络。
步骤:
1. 编辑配置文件:
```bash
sudo nano /etc/network/interfaces
```
2. 修改或添加如下内容:
```
auto enp0s3
iface enp0s3 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
```
- `enp0s3` 是你的网卡名称。
3. 重启网络服务:
```bash
sudo systemctl restart networking
```
4. 验证:
```bash
ip a
ping -c 4 8.8.8.8
```
---
注意事项
1. 确认网卡名称:通过 `ip a` 或 `ifconfig` 确认网卡名称是否正确。
2. 权限问题:修改配置文件需要 `root` 权限,可以通过 `sudo` 提升权限。
3. 备份原配置:在修改配置前备份原文件以便恢复。
如果你不确定使用哪种方式,可以告诉我你的 Linux 发行版及版本,我会为你提供更具体的步骤!