linux下设置ip的多种方法
一.网络配置的基本知识
1.IP ADDRESS
ip是网络地址
ip是由32个01组成,分为4组,每组8位
例如:11111110.11111110.1111110.1111110=254.254.254.254
以太网: 当一个数据在传输的时候另一个数据检测线缆的使用情况,如果线缆被占用,则他会等待至线缆闲置
2.子网掩码
它是用来划分网络区域,子网掩码非0的位对应的ip上的数字表示这个ip的网络位,子网掩码0位对应的数字是ip的主机位,网络位表示网络区域,主机位表示网络区域里某台主机
3.ip通信判定
网络位一致,主机位不一致的2个IP可以直接通讯
比如:172.25.254.115与172.25.254.215
设置网关时24=255.255.255.0
ping来检测是否可以直接通讯
ping ip
ping -c n ## n表示次数,例如3 ,只ping3次
ping -w n ## n表示秒数,例如3,等待3秒
二:设置临时ip
<2>== ifconfig格式==
ifconfig | 检测网络是否通畅/查看或设定网络接口 |
---|---|
ifconfig device ip/24 | 设定网络ip |
ifconfig device down | 关闭网络ip |
ifconfig device up | 开机 |
注意:device的名字是一个物理事实,看到什么名字就用什么名字
如图所示:
ifconfig device ip/24 设定网络ip
为了保证实验环境纯净,删掉以前设定的ip
ifconfig device ip 设置网络ip
ifconfig device down 关闭网络ip
ifconfig device up 打开网络ip
<2>== ip addr格式==
ip addr | 检测这项网络接口 |
---|---|
ip addr show | 检测 |
ip addr add ip/24 dev device | 设定网络ip |
ip addr del dev device ip/24 | 删除网络ip |
ip addr flush eth0 | 刷新网络ip |
注意:device的名字是一个物理事实,看到什么名字就用什么名字
实验如下:
为了保持一个干净的实验环境,我将原来设定的ip都删除。
ip addr show eth0 查看网卡的信息
ip addr add ip/24 dev device 设定ip
刷新之后设定ip
ip addr flush eth0 刷新ip(刷新过后ip不在,说明是临时ip)
ip addr del dev eth0 ip/24 删除ip
flush跟delete的区别:
flush刷新能将一块网卡上的所有ip都删除掉,而delete只能删除指定的ip
三:图形永久设置ip的方法
<1>.nm-connection-editor(这个方法我们在前面将真机与虚拟机的连接时讲过,这篇博客就不详细叙述)
<2>.nutui
此方法可用于图形界面,也可用于无图形界面
如图所示:
测试临时ip与永久ip的方法:
四:nmcli命令设定网络ip
nmcli device connect eth0 | 启用eth0网卡 |
---|---|
nmcli device disconnect eth0 | 关闭eth0网卡 |
nmcli device show eth0 | 查看网卡信息 |
nmcli device status eth0 | 查看网卡服务接口信息 |
nmcli connection show | 查看网卡信息 |
nmcli connection down eth0 | 关闭eth0网卡 |
nmcli connection up eth0 | 开启eth0网卡 |
nmcli connection delete eth0 | 删除eth0网卡 |
nmcli connection add type ethernet con-name westos ifname eth0 ip4 172.25.254.100/24 | 添加一个网络 |
前提:
如图所示:
nmcli device disconnect eth0 关闭eth0网卡
nmcli device connect eth0 启用eth0网卡
nmcli device show eth0 查看网卡信息
nmcli connection show 查看网卡信息
nmcli device status eth0 查看网卡服务接口信息
nmcli connection down meng 关闭接口名为meng的ip
nmcli connection up meng 开启接口名为meng这个ip
nmcli connection delete eth0 删除eth0网卡
nmcli connection add type ethernet con-name westos ifname eth1 ip4 172.25.254.115/24
添加一个类型是以太网,名字为westos,网卡为eth1,ip为172.25.254.115,子网掩码为24的网络ip
nmcli connection add type ethernet con-name meng ifname eth0 autoconnect yes 创建动态ip
五.网络配置目录里永久设定网络ip
在/etc/sysconfig/network-scripts/目录下进行配置
在以ifcfg为首的文本里编写,网络配置文件的命令规则如下:
DEVICE=xxx | 设备名称 |
---|---|
BOOTPROTO=dhcp/static/none | 设备工作方式动态/静态/无 |
ONBOOT=yes | 网络服务开启时自动**网卡 |
IPADDR=xxx.xxx.xxx.xxx | IP地址 |
PREFIX=24 | 子网掩码 |
NETMASK=255.255.255.0 | 子网掩码 |
NAME= | 接口名称 |
实验一:用网络配置文件设定一个动态ip
cd etc/sysconfig/network-scripts/ 进到这个网络配置文件的目录里
ls 查看
vim ifcfg-eth0 配置ip
在网络配置文件里写入的内容
完整截图:
注意:一个网卡上只能有一个动态ip
实验二:在配置文件里配置一个静态ip
配置文件里写入的内容
因为一个网卡上可以配置多个静态ip
六.用脚本去设定网络ip
保证实验环境纯净,将原本的网卡删除
编辑一个脚本文件:
vim /bin/set_ip.sh
在里面写入:
注意:这个里面的$1,$2代表可以自定义。
比如我想要文件名为eth0,ip为1.1.1.115我便可以这样写:
set_ip.sh eth0 1.1.1.115