转【Ubuntu】添加虚拟网卡的三种方式

原文:https://blog.csdn.net/White_Idiot/article/details/82934338

------------------------------

1. ifconfig添加
使用ifconfig -a命令查看已有物理网卡,一般得到如下输出:

eno1 ...(省略)

lo ...

ppp0 ...
1
2
3
4
5
然后向物理网卡eno1中添加一块虚拟网卡:

sudo ifconfig eno1:1 192.168.0.10 up
1
以上命令创建了一个叫eno1:1的虚拟网卡,地址是192.168.0.10。

可以使用如下命令删除:

sudo ifconfig eno1:1 down
1
用这种方式添加的虚拟网卡,重启服务器或网络后就没了。

2. 修改网卡配置文件
在Ubuntu下,网卡的配置文件是/etc/network/interfaces:

sudo vim /etc/network/interfaces
1
增加如下内容:

auto eno1:1
iface eno1:1 inet static
address 192.168.0.10
netmask 255.255.255.0
# network 192.168.10.1
# broadcast 192.168.1.255
1
2
3
4
5
6
然后重启网卡(重新加载配置文件):

sudo /etc/init.d/networking restart
1
这种方式在重启服务器或者网卡后配置不会丢失。

3. 创建TAP
前面两种方式创建的虚拟网卡和物理网卡相比,IP地址不同,但是Mac地址相同:

eno1 Link encap:以太网 硬件地址 da:3d:b0:a0:13:p9
...(省略)

eno1:1 Link encap:以太网 硬件地址 da:3d:b0:a0:13:p9 (相同Mac地址)
inet 地址:192.168.0.10 广播:192.168.0.255 掩码:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 跃点数:1
1
2
3
4
5
6
如果需要不同的Mac地址,可以添加虚拟网卡TAP。先安装uml-utilities:

sudo apt-get install uml-utilities
1
然后使用tunctl添加虚拟网卡,该命令会生成一个TAP,后缀从0递增:

$ sudo tunctl -b
tap0
$ sudo tunctl -b
tap1
1
2
3
4
最后激活创建的TAP:

$ sudo ip link set tap0 up
$ sudo ip link set tap1 up
1
2
查看网卡信息可以看到TAP有不同的Mac地址:

tap0 Link encap:以太网 硬件地址 be:74:81:f7:27:97
...(省略)

tap1 Link encap:以太网 硬件地址 b2:da:ce:f0:45:5d
...
1
2
3
4
5
这种方式创建的虚拟网卡在重启后也会消失,需要编写脚本作为系统服务随系统自动启动创建虚拟网卡,可以根据具体需求修改此脚本(符合chkconfig规范)。脚本如下:

$ cat /etc/init.d/config_tap

#!/bin/bash
#
# config_tap Start up the tun/tap virtual nic
#
# chkconfig: 2345 55 25

USER="root"
TAP_NETWORK="192.168.0.1"
TAP_DEV_NUM=0
DESC="TAP config"

do_start() {
if [ ! -x /usr/sbin/tunctl ]; then
echo "/usr/sbin/tunctl was NOT found!"
exit 1
fi
tunctl -t tap$TAP_DEV_NUM -u root
ifconfig tap$TAP_DEV_NUM ${TAP_NETWORK} netmask 255.255.255.0 promisc
ifconfig tap$TAP_DEV_NUM
}

do_stop() {
ifconfig tap$TAP_DEV_NUM down
}
do_restart() {
do_stop
do_start
}
check_status() {
ifconfig tap$TAP_DEV_NUM
}

case $1 in
start) do_start;;
stop) do_stop;;
restart) do_restart;;
status)
echo "Status of $DESC: "
check_status
exit "$?"
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
esac
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
然后将脚本加入到系统服务中:

chkconfig --add config_tap
chkconfig --level 345 config_tap on
1
2
操作完成后,就可以像其他标准服务一样,通过service config_tap start来进行创建和启动操作。

参考文章
Linux添加虚拟网卡的多种方法
linux下TUN/TAP虚拟网卡的使用
————————————————
版权声明:本文为CSDN博主「widiot0x」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/White_Idiot/article/details/82934338

原文地址:https://www.cnblogs.com/oxspirt/p/11471322.html