树莓派使用无线连接网络

不使用netplan

1. 安装工具

1
$ sudo apt install ifupdown

2. 修改/etc/network/interfaces文件

1
$ sudo vim /etc/network/interfaces
# ifupdown has been replaced by netplan(5) on this system.  See
# /etc/netplan for current configuration.
# To re-enable ifupdown on this system, you can run:
#    sudo apt install ifupdown

auto wlan0
allow-hotplug wlan0
#iface wlan0 inet static
iface wlan0 inet dhcp
#       address 192.168.1.52
#       netmask 255.255.255.0
        wpa_conf /etc/wpa_supplicant/wpa_supplicant.conf

3. 修改/etc/wpa_supplicant/wpa_supplicant.conf文件

1
$ sudo vim /etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=/var/run/wpa_supplicant
#ap_scan=1

network={
       ssid="SSID"
       scan_ssid=1
       psk="password"
       priority=5
}

4. 重启网卡

1
$ sudo ifdown wlan0

回显:

Killed old client process
Internet Systems Consortium DHCP Client 4.3.5
Copyright 2004-2016 Internet Systems Consortium.
All rights reserved.
For info, please visit https://www.isc.org/software/dhcp/

Listening on LPF/wlan0/b8:27:eb:xx:xx:xx
Sending on   LPF/wlan0/b8:27:eb:xx:xx:xx
Sending on   Socket/fallback
DHCPRELEASE on wlan0 to 192.168.1.1 port 67 (xid=0x13ea153a)
1
$ sudo ifup wlan0

回显:

Internet Systems Consortium DHCP Client 4.3.5
Copyright 2004-2016 Internet Systems Consortium.
All rights reserved.
For info, please visit https://www.isc.org/software/dhcp/

Listening on LPF/wlan0/b8:27:eb:xx:xx:xx
Sending on   LPF/wlan0/b8:27:eb:xx:xx:xx
Sending on   Socket/fallback
DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 3 (xid=0xd0fcdd63)
DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 4 (xid=0xd0fcdd63)
DHCPREQUEST of 192.168.1.52 on wlan0 to 255.255.255.255 port 67 (xid=0x63ddfcd0)
DHCPOFFER of 192.168.1.52 from 192.168.1.1
DHCPACK of 192.168.1.52 from 192.168.1.1
bound to 192.168.1.52 -- renewal in 2147483648 seconds.

5. 备注

  • ap_scan
    • 默认值为1
    • 1:总是先连接可见的WiFi,如果扫描完所有可见的网络之后都没有连接上,则开始连接隐藏WiFi。
    • 2:会按照network定义的顺序连接WiFi网络,遇到隐藏的将立刻开始连接,因此在这个模式下连接顺序不受priority影响
  • ctrl_interface
    • 文件夹里面存的是一个当前使用的interface的socket文件,可以供其他程序使用读取WiFi状态信息
  • network
    • 是一个连接一个WiFi网络的配置,可以有多个,wpa_supplicant会按照priority指定的优先级(数字越大越先连接)来连接,当然,在这个列表里面隐藏WiFi不受priority的影响,隐藏WiFi总是在可见WiFi不能连接时才开始连接。
    • ssid:网络的ssid
    • psk:密码
    • priority:连接优先级,越大越优先
    • scan_ssid:连接隐藏WiFi时需要指定该值为1

使用netplan

Ubuntu 18及以后的新系统使用netplan管理网络连接,不再使用interfaces。

修改配置文件

1
$ vim /etc/netplan/50-cloud-init.yaml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
network:
    ethernets:
        eth0:
            dhcp4: true
            optional: true
    wifis:
            wlan0:
                    dhcp4: true
                    dhcp6: true
                    access-points:
                            "WiFi名称":
                                    password: "密码"
    version: 2

应用更改

1
$ sudo netplan apply
updatedupdated2020-05-252020-05-25