In case of no encryption
iw dev <device> connect <ssid> [<bssid>]
Why bssid? In case you have multiple access points, you can specify a specific accesspoint. If you have just one, there’s no need to specify.
i.e. iw dev wlan0 connect Freewifi 40:A5:EF:25:BF:12
In case of WPA/WPA2
apt-get install wpasupplicant
wpa_passphrase <ssid> [passphrase]
i.e. wpa_passphrase MyWifi Welcome123
Copy output to file
wpa_supplicant -D<driver> -i <device> -c <file>
i.e. wpa_supplicant -Dnl80211 -i wlan1 -c /etc/wpa_supplicant.conf
If you want to associate to a specific access point, add bssid=<MAC address AP> to the file.
i.e.
network={
ssid=”MyWifi”
bssid=40:A5:EF:25:BF:12
#psk=”Welcome123″
psk=517ea7c308da240bc84409b1e7ad1fa9aaf0682fea89859f3de8f072be67899a
}