Ubuntu 24.04 LTS 命令行固定 IP

参考

环境

环境 版本 说明
Windows Windows 10 家庭中文版 22H2 19045.4529
VMware Workstation 16 Pro
Ubuntu Ubuntu 24.04 LTS

步骤

我们可以使用 Netplan 工具和配置文件,为 Ubuntu Server 设置静态 IP 地址。Netplan 的配置文件通常位于/etc/netplan目录,取决于你的系统版本和实际环境,文件名可能是01-netcfg.yaml或50-cloud-init.yaml。

  1. 使用以下命令列出所有网络接口,确定 Ubuntu 上可用的网络接口名称:
    ip link show
    
    image
  2. 找到 Netplan 的配置文件:
    cd /etc/netplan
    ls -l
    
    image
  3. 备份 Netplan 的配置文件:
    cp 50-cloud-init.yaml ./50-cloud-init-back.yaml
    
  4. 打开并编辑 Netplan 配置文件,例如 50-cloud-init.yaml,修改为如下:
    sudo nano 50-cloud-init.yaml
    
    # This file is generated from information provided by the datasource.  Changes
    # to it will not persist across an instance reboot.  To disable cloud-init's
    # network configuration capabilities, write a file
    # /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
    # network: {config: disabled}
    # 默认
    # network:
    #     ethernets:
    #         ens33:
    #             dhcp4: true
    #     version: 2
    # 当前
    # 根据网络环境替换示例中的 IP 地址、网关和 DNS 服务器地址。
    # renderer」配置为networkd,使用 systemd-networkd 作为网络配置的后端。桌面环境使用 NetworkManager,Ubuntu Server 和无头环境使用networkd。
    	network:
    		renderer: networkd
    		ethernets:
    			ens33: # 替换为你的网络接口名称
    				dhcp4: false # 关闭 DHCP
    				dhcp6: false # 关闭 DHCP
    				addresses: [192.168.72.144/24] # 静态 IP 地址和子网掩码
    				routes:
    				  - to: default
    					via: 192.168.72.1 # 网关地址
    				nameservers:
    					addresses: [192.168.72.1] # DNS 服务器地址
    					search: []
    		version: 2
    
  5. 保存文件后,执行以下命令应用更改:
    sudo netplan apply
    
  6. 检查 IP 地址和网络连接:
    ip addr show
    ip route show
    ping www.sysgeek.cn
    
posted @ 2024-06-30 15:06  夏秋初  阅读(530)  评论(0编辑  收藏  举报