3

Linux 静态 ip 配置方法

 1 year ago
source link: https://xujinzh.github.io/2022/09/07/linux-network-ip/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Linux 静态 ip 配置方法

2022-09-07technologylinux

1.8k 2 分钟

Linux 系统默认都是动态(DHCP) IP,但因为某些原因公司要求个人使用静态 IP,因此,本篇介绍如何为 Ubuntu/CentOS 等设置静态 IP.

Ubuntu

生成配置文件

自从 Ubuntu 17.10 后,网络设置中引入了 netplan,使用它可不重启机器就可以变更 IP,方法如下:

网卡信息配置在 /etc/netplan/01-network-manager-all.yaml 文件中,如果这个 yaml 文件不存在(发型版本中没有默认创建),那么可以使用下面的命令创建出来。创建出来的名字可能略有不同,但 /etc/netplan/ 目录下面所有的 yaml 文件都可以生效。
sudo netplan generate

配置静态 IP

设置静态 IP,以 /etc/netplan/01-network-manager-all.yaml 为例:

vim /etc/netplan/01-network-manager-all.yaml

更为为如下:

# This file is generated from information provided by
# the datasource. Changes to it will not persist across an instance.
# 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:
enp0s25:
dhcp4: no
dhcp6: no
addresses: [192.168.2.12/24, ]
optional: true
gateway4: 192.168.2.1
nameservers:
addresses: [8.8.8.8, 8.8.4.4]
version: 2
# renderer: NetworkManager

参数说明与注意事项:

  1. enp0s25 为你要设置的网卡,可通过 ip addrifconfig 获取;
  2. dhcp4: no 指定不采用动态 IP V4;
  3. dhcp6: no 指定不采用动态 IP V6;
  4. addresses 设置固定 IP 地址为 192.168.2.12;
  5. gateway4 指定 IP V4 网关为 192.168.2.1;
  6. nameservers 里的 addresses 表示 DNS;
  7. renderer: NetworkManager 注释;

使配置生效

sudo netplan apply

CentOS

修改网卡配置

sudo vim /etc/sysconfig/network-scripts/ifcfg-eth0

修改为如下内容:

# Created by cloud-init on instance boot automatically, do not edit.
#
#BOOTPROTO=dhcp
BOOTPROTO=static
DEVICE=eth0
IPADDR=192.168.2.12
GATEWAY=192.168.2.1
NETMASK=255.255.255.0
BROADCAST=192.168.2.255
HWADDR=53:55:01:e3:75:12
ONBOOT=yes
PERSISTENT_DHCLIENT=yes
TYPE=Ethernet
USERCTL=no

网关配置也可以写在 /etc/sysconfig/network 中。

DNS 配置写在 /etc/resolv.conf 中,

; generated by /usr/sbin/dhclient-script
nameserver 8.8.8.8
nameserver 8.8.4.4
sudo service network restart

# or
sudo /etc/init.d/network restart

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK