在计算机网络管理中,配置IP地址是基础且关键的操作,通过命令行配置IP地址不仅高效灵活,还能应对无图形界面的服务器环境或自动化脚本需求,以下是不同操作系统的详细操作指南:
Windows 系统(以管理员身份运行命令提示符或PowerShell)
查看当前网络配置
ipconfig /all
记录需修改的网卡名称(如 “Ethernet0″)。
配置静态IP地址
netsh interface ip set address name="Ethernet0" static 192.168.1.100 255.255.255.0 192.168.1.1
168.1.100
:IP地址255.255.0
:子网掩码168.1.1
:默认网关
配置DNS服务器
netsh interface ip set dns name="Ethernet0" static 8.8.8.8 netsh interface ip add dns name="Ethernet0" 8.8.4.4 index=2 # 备用DNS
恢复动态获取IP(DHCP)
netsh interface ip set address name="Ethernet0" source=dhcp netsh interface ip set dns name="Ethernet0" source=dhcp
Linux 系统(需root权限)
临时配置(重启失效)
ifconfig eth0 192.168.1.100 netmask 255.255.255.0 up route add default gw 192.168.1.1 # 设置网关 echo "nameserver 8.8.8.8" > /etc/resolv.conf # 设置DNS
永久配置(不同发行版方法)
-
Ubuntu/Debian(修改
/etc/network/interfaces
)auto eth0 iface eth0 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
重启服务:
systemctl restart networking
-
CentOS/RHEL(修改网卡配置文件)
编辑文件/etc/sysconfig/network-scripts/ifcfg-eth0
:BOOTPROTO=static IPADDR=192.168.1.100 NETMASK=255.255.255.0 GATEWAY=192.168.1.1 DNS1=8.8.8.8 DNS2=8.8.4.4
重启服务:
systemctl restart network
使用ip
命令(推荐)
ip addr add 192.168.1.100/24 dev eth0 # 配置IP和掩码 ip route add default via 192.168.1.1 # 设置网关
macOS 系统
使用networksetup
命令
# 配置静态IP networksetup -setmanual "Wi-Fi" 192.168.1.100 255.255.255.0 192.168.1.1 networksetup -setdnsservers "Wi-Fi" 8.8.8.8 8.8.4.4
恢复DHCP
networksetup -setdhcp "Wi-Fi"
关键注意事项
- 权限要求:
- Windows需管理员身份运行终端。
- Linux/macOS需
sudo
或root权限。
- 风险预防:
- 操作前备份配置文件(如Linux的
/etc/network/interfaces
)。 - 远程服务器操作时,建议通过带外管理(如IPMI)避免断网失控。
- 操作前备份配置文件(如Linux的
- 验证配置:
- 立即测试网络连通性:
ping 8.8.8.8
- 检查路由表:
route -n
(Linux/macOS)或route print
(Windows)
- 立即测试网络连通性:
- 防火墙影响:
若配置后无法访问,检查防火墙是否开放端口(如Linux的iptables
/firewalld
)。
为什么推荐命令行配置?
- 效率:批量操作或脚本部署时远快于图形界面。
- 通用性:适用于所有服务器及精简版系统(如Windows Server Core、Linux无桌面环境)。
- 排错优势:命令输出可直接反馈错误信息(如网卡名错误提示
The interface name is invalid
)。
引用说明:
- Microsoft官方文档:Netsh命令参考
- Linux
iproute2
手册页:ip(8) – Linux man page- Apple支持:networksetup命令手册
操作前请务必查阅硬件厂商或云服务商(如AWS/Azure)的特定网络配置建议。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/4526.html