Ubuntu20.04 命令行使用 wpasupplicant 连接 wifi

安装 wpasupplicant

1
apt install wpasupplicant -y

创建需要连接的 wifi 配置文件

假设连接的 wifi 名称是:ttt,密码是:yyy

1
2
cd /etc/wpa_supplicant
wpa_passphrase ttt yyy > wpa_supplicant.conf

连接

Tips: 查看网卡名称

1
2
3
4
5
6
7
8
9
ip addr

# 或者使用 net-tools 的 ifconfig 查询
sudo apt install net-tools -y
ifconfig -a

# 如果要使用 iw 工具集的话 ,需要先安装 wireless-tools
sudo apt install wireless-tools -y
iwconfig

假设查到的网卡名称是 wlp3s0,连接的命令如下:

1
2
cd /etc/wpa_supplicant
sudo wpa_supplicant -B -c wpa_supplicant.conf -i wlp3s0

DHCP

1
sudo dhclient wlp3s0 -v

设置开机启动

1
2
3
4
5
mkdir /etc/wpa_supplicant/systemd
cd /etc/wpa_supplicant/systemd
sudo touch dhclient.service wpa_supplicant.service
sudo ln -s /etc/wpa_supplicant/systemd/wpa_supplicant.service /etc/systemd/system/
sudo ln -s /etc/wpa_supplicant/systemd/dhclient.service /etc/systemd/system/

wpa_supplicant.service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=WPA supplicant
Before=network.target
After=dbus.service
Wants=network.target
IgnoreOnIsolate=true

[Service]
Type=dbus
BusName=fi.w1.wpa_supplicant1
ExecStart=/sbin/wpa_supplicant -u -s -c /etc/wpa_supplicant/wpa_supplicant.conf -i wlp3s0
Restart=always

[Install]
WantedBy=multi-user.target

dhclient.service

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description = DHCP Client
Before = network.targer
After = wpa_supplicant.service

[Service]
Type = forking
ExecStart = /sbin/dhclient wlp3s0 -v
ExecStop = /sbin/dhclient wlp3s0 -r
Restart = always

[Install]
WantedBy = multi-user.target

如果以后需要连接的 wifi 变了,或者更改密码了,通过第二步创建 wifi 配置文件的操作将配置文件覆盖掉即可。