Ubuntu简单修改IP

ubuntu简单修改固定IP

在网上搜到的ubuntu改IP都是通过手写interfaces文件,这需要记住语法和格式,很不方便,在Redhat系上,可以使用很方便的NetworkManager的nmtui的Text UI来设置IP,我们只需要填写我们希望的网络信息即可,那么在ubuntu上其实也是有简便的方法;

ubuntu 20使用的netplan来管理,其配置文件使用的YAML,虽然语法格式也简单,但是还是可以有不用记的方式来完成IP的修改;

默认情况下的配置文件在/etc/netplan/00-installer-config.yaml,默认使用DHCP的方式,全部内容为

# This is the network config written by 'subiquity'
network:
  ethernets:
    eth0:
      dhcp4: true
  version: 2

Linux上,大部分软件都包含了自己的文档,常规的包含README,Example之类的,目录在/usr/share/doc/netplan下,有个examples目录,当中包含了很多网络的配置文件模板,如

ls /usr/share/doc/netplan/examples/

bonding_router.yaml               loopback_interface.yaml   static_singlenic_multiip_multigateway.yaml
bonding.yaml                      modem.yaml                static.yaml
bridge_vlan.yaml                  network_manager.yaml      vlan.yaml
bridge.yaml                       openvswitch.yaml          windows_dhcp_server.yaml
dhcp_wired8021x.yaml              route_metric.yaml         wireguard.yaml
dhcp.yaml                         source_routing.yaml       wireless.yaml
direct_connect_gateway_ipv6.yaml  sriov_vlan.yaml           wpa_enterprise.yaml
direct_connect_gateway.yaml       sriov.yaml
ipv6_tunnel.yaml                  static_multiaddress.yaml

找到static.yaml就是我们想要的静态IP配置文件模板,现成的格式和内容;拷贝到/etc/netplan下即可;

# 先备份源文件
sudo cp /etc/netplan/00-installer-config.yaml /etc/netplan/00-installer-config.yaml.bak
# 拷贝静态IP配置文件
sudo cp /usr/share/doc/netplan/examples/static.yaml /etc/netplan/

# 简单修改一下;它的默认是这样的
network:
  version: 2
  renderer: networkd
  ethernets:
    enp3s0:
      addresses:
        - 10.10.10.2/24
      nameservers:
        search: [mydomain, otherdomain]
        addresses: [10.10.10.1, 1.1.1.1]
      routes: 
        - to: default
          via: 10.10.10.1

enp3s0: 是网卡的名称,ubuntu一般使用的是eth0作为第一块网卡,这点可以通过 ip addr的方式查看,一定写填写ip addr显示的结果
addresses:是需要设置的静态IP和子网,如192.168.1.100/24
nameservers:是DNS服务器设置
search:搜索域,如果内网没有DNS服务器,保持默认或者清空即可;
addresses:DNS地址,一般填写当地的或者阿里的之类的,如223.5.5.5,223.6.6.6
routes:路由设置
via:网关地址,如192.168.1.1

修改完成后,应用即可

sudo netplan apply

netplan作为ubuntu的网络管理程序,还有很多命令,可以使用-h获取

netplan -h
usage: /usr/sbin/netplan  [-h] [--debug]  ...

Network configuration in YAML

optional arguments:
  -h, --help  show this help message and exit
  --debug     Enable debug messages

Available commands:
  
    help      Show this help message
    apply     Apply current netplan config to running system
    generate  Generate backend specific configuration files from /etc/netplan/*.yaml
    get       Get a setting by specifying a nested key like "ethernets.eth0.addresses", or "all"
    info      Show available features
    ip        Retrieve IP information from the system
    set       Add new setting by specifying a dotted key=value pair like ethernets.eth0.dhcp4=true
    try       Try to apply a new netplan config to running system, with automatic rollback