How to connect to wifi from command line?

I'm assuming wpa_supplicant and iw is installed.

  1. To connect to wifi through wpa_supplicant you need to create a wpa_supplicant.conf file

    nano /etc/wpa_supplicant.conf
    

    with the following lines:

    network={
             ssid="wifi_name"
             psk="wifi_key"
    }
    

Or you can use wpa_passphrase to create the configuration file (copy and past):

wpa_passphrase "Your_SSID" Your_passwd 

Also you can write the wpa_supplicant.conf directly through:

wpa_passphrase "Your_SSID" Your_passwd > /etc/wpa_supplicant.conf

to connect type the following command:

sudo ip link set wlan0 down
sudo ip link set wlan0 up
sudo wpa_supplicant -B -iwlan0 -c /etc/wpa_supplicant.conf -Dnl80211,wext
sudo dhclient wlan0

Note: Multiple comma separated driver wrappers in option -Dnl80211,wext makes wpa_supplicant use the first driver wrapper that is able to initialize the interface (see wpa_supplicant(8)). This is useful when using mutiple or removable (e.g. USB) wireless devices which use different drivers.

You can connect through wpa_supplicant without wpa_supplicant.conf file:

wpa_supplicant -B -i wlan0 -c <(wpa_passphrase "Your_SSID" Your_passphrase) && dhclient wlan0

You can visit the official documentation of Arch-linux to get more information about the configuration file and arguments.

  1. you can connect through nmcli

    nmcli d wifi connect Your_SSID password Your_Psswd_here iface Your_interface
    

Example:

nmcli d wifi connect MYSSID password 12345678 iface wlan0
  1. Also you can connect through wpa_cli:

Open the terminal and type wpa_cli

To scan, type:

scan
scan_results

Create a network:

add_network

This will output a number, which is the network ID, for example 0 Next, we need to set the SSID and PSK for the network.

set_network 0 ssid "SSID_here"
set_network 0 psk "Passphrase_here"

Once the wireless has connected, it should automatically get an IP address. if it doesn’t you can run the dhclient to get an IP address via DHCP.

The dhclient command ca be replaced with 2 ip commands:

ip addr add IP-ADDRESSE/24 dev wlan0
ip route add default via ROUTE
  1. iwctl command line tools.

The iwd package provide the iwctl command line tools . The package isn't installed by default. To avoid any conflict the wpasupplicant.service should be stopped/disabled.

for more details see this answer on U&L: Connect to wifi from command line on linux systems through the iwd (wireless daemon for linux)

Further reading :

Connecting with wpa_cli

Connecting with wpa_passphrase

nmcli examples

Archlinux: iwd/iwctl


To install wpa_supplicant on Debian, type

sudo apt install wpasupplicant

in the terminal. To create the wpa_supplicant.conf file, type in

echo 'network={ssid="nameOfYourWiFiNetwork" psk="thePassword"}' >> /etc/wpa_supplicant.conf