使用 SSH 方式远程修改服务器的默认 IP 地址和网关是一个常见的网络管理任务。
前提条件 1. **SSH 访问**:确保你有远程服务器的 SSH 访问权限。 2. **超级用户权限**:大多数网络配置更改需要超级用户权限(即 `root` 权限)。
步骤
1. 远程连接到服务器 使用 SSH 连接到你的服务器:
ssh username@current_ip_address
2. 备份当前网络配置 在进行任何更改之前,备份当前的网络配置文件。具体文件位置取决于你的操作系统。
Debian/Ubuntu 备份 `/etc/network/interfaces` 文件:
sudo cp /etc/network/interfaces /etc/network/interfaces.bak
CentOS/RHEL 备份 `/etc/sysconfig/network-scripts/ifcfg-eth0` 文件:
sudo cp /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth0.bak
Netplan (Ubuntu 18.04+) 备份 `/etc/netplan/` 目录下的配置文件:
sudo cp /etc/netplan/01-netcfg.yaml /etc/netplan/01-netcfg.yaml.bak
3. 修改 IP 地址和网关
使用 `ip` 命令临时修改 使用 `ip` 命令临时修改 IP 地址和网关:
- 修改 IP 地址:
sudo ip addr add new_ip_address/subnet_mask dev eth0
sudo ip addr del current_ip_address/subnet_mask dev eth0
例如:
sudo ip addr add 192.168.1.100/24 dev eth0
sudo ip addr del 192.168.1.50/24 dev eth0
- 修改网关:
sudo ip route add default via new_gateway_ip dev eth0
sudo ip route del default via current_gateway_ip dev eth0
例如:
sudo ip route add default via 192.168.1.1 dev eth0
sudo ip route del default via 192.168.1.254 dev eth0
- 验证配置:
ip addr show eth0
ip route
4. 永久保存配置
Debian/Ubuntu 编辑 `/etc/network/interfaces` 文件:
sudo nano /etc/network/interfaces
添加或修改以下内容:
auto eth0
iface eth0 inet static
address new_ip_address
netmask subnet_mask
gateway new_gateway_ip
例如:
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
CentOS/RHEL 编辑 `/etc/sysconfig/network-scripts/ifcfg-eth0` 文件:
sudo nano /etc/sysconfig/network-scripts/ifcfg-eth0
添加或修改以下内容:
DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
IPADDR=new_ip_address
NETMASK=subnet_mask
GATEWAY=new_gateway_ip
例如:
DEVICE=eth0
BOOTPROTO=static
ONBOOT=yes
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
Netplan (Ubuntu 18.04+) 编辑 `/etc/netplan/01-netcfg.yaml` 文件:
sudo nano /etc/netplan/01-netcfg.yaml
添加或修改以下内容:
network:
version: 2
ethernets:
eth0:
dhcp4: no
addresses:
– 192.168.1.100/24
gateway4: 192.168.1.1
nameservers:
addresses:
– 8.8.8.8
– 8.8.4.4
5. 启网络服务 为了使更改生效,可以重启网络服务。
Debian/Ubuntu
sudo systemctl restart networking
或
sudo service networking restart
CentOS/RHEL
sudo systemctl restart network
或
sudo service network restart
Netplan (Ubuntu 18.04+)
sudo netplan apply
6. 验证配置 使用 `ifconfig` 或 `ip` 命令验证 IP 地址和网关是否已正确设置。
ip addr show eth0
ip route
测试连接:在更改 IP 地址和网关后,确保新的配置能够正常工作,可以尝试从另一台机器 SSH 连接到新的 IP 地址。
评论前必须登录!
注册