Saturday, October 19, 2013

How to connect to a WPA/WPA2 WiFi network using Linux command line

This is a step-to-step guide for connecting to a WPA/WPA2 WiFi network via the Linux command line interface. The tools are:

  • wpa_supplicant
  • iw
  • ip
  • ping

iw is the basic tool for WiFi network-related tasks, such as finding the WiFi device name, and scanning access points. wpa_supplicant is the wireless tool for connecting to a WPA/WPA2 network. ip is used for enabling/disabling devices, and finding out general network interface information.

The steps for connecting to a WPA/WPA2 network are:

  1. Find out the wireless device name.
    $ /sbin/iw dev
    	Interface wlan0
    		ifindex 3
    		type managed

    The above output showed that the system has 1 physical WiFi card, designated as phy#0. The device name is wlan0. The type specifies the operation mode of the wireless device. managed means the device is a WiFi station or client that connects to an access point.

  2. Check that the wireless device is up.
    $ ip link show wlan0
    3: wlan0: (BROADCAST,MULTICAST) mtu 1500 qdisc noop state DOWN mode DEFAULT qlen 1000
        link/ether 74:e5:43:a1:ce:65 brd ff:ff:ff:ff:ff:ff

    Look for the word "UP" inside the brackets in the first line of the output.

    In the above example, wlan0 is not UP. Execute the following command to bring it up:

    $ sudo ip link set wlan0 up  
    [sudo] password for peter: 

    Note: you need root privilege for the above operation.

    If you run the show link command again, you can tell that wlan0 is now UP.

    $ ip link show wlan0
    3: wlan0: (NO-CARRIER,BROADCAST,MULTICAST,UP) mtu 1500 qdisc mq state DOWN mode DEFAULT qlen 1000
        link/ether 74:e5:43:a1:ce:65 brd ff:ff:ff:ff:ff:ff
  3. Check the connection status.
    $ /sbin/iw wlan0 link
    Not connected.

    The above output shows that you are not connected to any network.

  4. Scan to find out what WiFi network(s) are detected
    $ sudo /sbin/iw wlan0 scan
    BSS 00:14:d1:9c:1f:c8 (on wlan0)
            ... sniped ...
    	freq: 2412
    	SSID: gorilla
    	RSN:	 * Version: 1
    		 * Group cipher: CCMP
    		 * Pairwise ciphers: CCMP
    		 * Authentication suites: PSK
    		 * Capabilities: (0x0000)
            ... sniped ...

    The 2 important pieces of information from the above are the SSID and the security protocol (WPA/WPA2 vs WEP). The SSID from the above example is gorilla. The security protocol is RSN, also commonly referred to as WPA2. The security protocol is important because it determines what tool you use to connect to the network.

  5. Connect to WPA/WPA2 WiFi network.

    This is a 2 step process. First, you generate a configuration file for wpa_supplicant that contains the pre-shared key ("passphrase") for the WiFi network.

    $ sudo -s
    [sudo] password for peter: 
    $ wpa_passphrase gorilla >> /etc/wpa_supplicant.conf 
    ...type in the passphrase and hit enter...

    wpa_passphrase takes the SSID as the single argument. You must type in the passphrase for the WiFi network gorilla after you run the command. Using that information, wpa_passphrase will output the necessary configuration statements to the standard output. Those statements are appended to the wpa_supplicant configuration file located at /etc/wpa_supplicant.conf.

    Note: you need root privilege to write to /etc/wpa_supplicant.conf.

    $ cat /etc/wpa_supplicant.conf 
    # reading passphrase from stdin

    The second step is to run wpa_supplicant with the new configuration file.

    $ sudo wpa_supplicant -B -D wext -i wlan0 -c /etc/wpa_supplicant.conf

    -B means run wpa_supplicant in the background.

    -D specifies the wireless driver. wext is the generic driver.

    -c specifies the path for the configuration file.

    Use the iw command to verify that you are indeed connected to the SSID.

    $ /sbin/iw wlan0 link
    Connected to 00:14:d1:9c:1f:c8 (on wlan0)
    	SSID: gorilla
    	freq: 2412
    	RX: 63825 bytes (471 packets)
    	TX: 1344 bytes (12 packets)
    	signal: -27 dBm
    	tx bitrate: 6.5 MBit/s MCS 0
    	bss flags:	short-slot-time
    	dtim period:	0
    	beacon int:	100
  6. Obtain IP address by DHCP
    $ sudo dhclient wlan0

    Use the ip command to verify the IP address assigned by DHCP. The IP address is from below.

    $ ip addr show wlan0
    3: wlan0:  mtu 1500 qdisc mq state UP qlen 1000
        link/ether 74:e5:43:a1:ce:65 brd ff:ff:ff:ff:ff:ff
        inet brd scope global wlan0
        inet6 fe80::76e5:43ff:fea1:ce65/64 scope link 
           valid_lft forever preferred_lft forever
  7. Add default routing rule.

    The last configuration step is to make sure that you have the proper routing rules.

    $ ip route show dev wlan0  proto kernel  scope link  src 

    The above routing table contains only 1 rule which redirects all traffic destined for the local subnet (192.168.1.x) to the wlan0 interface. You may want to add a default routing rule to pass all other traffic through wlan0 as well.

    $ sudo ip route add default via dev wlan0
    $ ip route show
    default via dev wlan0 dev wlan0  proto kernel  scope link  src 
  8. ping external ip address to test connectivity
    $ ping
    PING ( 56(84) bytes of data.
    64 bytes from icmp_req=1 ttl=48 time=135 ms
    64 bytes from icmp_req=2 ttl=48 time=135 ms
    64 bytes from icmp_req=3 ttl=48 time=134 ms
    --- ping statistics ---
    3 packets transmitted, 3 received, 0% packet loss, time 2000ms
    rtt min/avg/max/mdev = 134.575/134.972/135.241/0.414 ms

The above series of steps is a very verbose explanation of how to connect a WPA/WPA2 WiFi network. Some steps can be skipped as you connect to the same access point for a second time. For instance, you already know the WiFi device name, and the configuration file is already set up for the network. The process needs to be tailored according to your situation.


jaspreet singh said...
This comment has been removed by the author.
Conor said...

Oh thank goodness you've written this up, step by step instead of just "use wpa_supplicant". WPA was a maze of twisty passages and I didn't know about wpa_passphrase. Thanks a lot for this.

Anonymous said...

excelente ... muchas gracias

Anonymous said...

What to do if I have hidden SSID for WPA2 wifi?

#iw wlan0 scan
SSID: \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00

Anonymous said...

PS. I know name of hidden SSID

Peter Leung said...

For hidden SSIDs, edit wpa_supplicant.conf.

Add 'scan_ssid=1' to the network definition.



Anonymous said...

Messed up my graphics driver install so the network manager gui wouldn't start. Saved my day! Thanks. Put that in a script now :)

jaspreet singh said...

nothing better than the Linux the only draw back with Linux is it is not user friendly and post like this help many to do the task on linux

Anonymous said...

you saved be, thank you

Anonymous said...

# wpa_supplicant -B -D wext -i wlan0 -c /etc/wpa_supplicant.conf
Successfully initialized wpa_supplicant
ioctl[SIOCSIWENCODEEXT]: Invalid argument
ioctl[SIOCSIWENCODEEXT]: Invalid argument
# iw wlan0 link
Not connected.

xubuntu 14.04, Qualcomm Atheros AR9285 Wireless Network Adapter (PCI-Express) (rev 01)

jaspreet singh said...

Perfect post for slove my problem atleast

red wimax

Nick said...

I have almost the same problem as anonymous at April 25 above. But mine doesn't even say successfully initialised before returning the invalid argument message. Any help greatly appreciated. Thanks.

Satheesh P'h'p said...

Thank you so much for this great post. You saved me from a big disaster. Thanks a lot. But I'm suffering from last one problem. I've connected to the network in my office. I can view IP from 'ifconfig' command.
But I couldn't connect to this system from a external system at given ip. I've looked upon router configuration page where my device has been connected but ip isn't shown. when I use 'ip route show' this is coming, dev wlan0 proto kernel scope link src

Please help on this... :-(

Anonymous said...

Thank you SO much for this!

Anonymous said...

I used none instead of wext after the -D option and it solved the problem.

Anonymous said...

I used none instead of wext and it solved the problem

jaspreet singh said...

Nice thanks for share

wifi en eventos

gordon said...

>>Anonymous said...
>>I used none instead of wext after the
>>-D option and it solved the problem.

I get: Unsupported driver 'none'

If remove the -D option, I get Invalid argument errors.

I'm so close on this. Please help.

Bo Grimes said...

Thanks. I had a power outage during a distro upgrade. I couldn't get back into the GUI, so I used this to connect at console and finish the upgrade. Plus I know more about networking now.

Emerson Prado said...

Many thanks! My Linux Mint Debian Edition powered notebook is Wi-Fi connected now. Great article!
I just had to change the route command in step 7 to:
sudo route add default gw <gateway> <interface>

Also, the route and the wpa_supplicant command aren't persistent. For a permanent change, we have to add them in /etc/network/interfaces (for Debian), in the Wi-Fi interface section. Mine ended up like:

auto <interface>
iface <interface> inet dhcp
wireless-essid <essid>
pre-up wpa_supplicant -B -D wext -i <interface> -c /etc/wpa_supplicant.conf
post-up route add default gw <gateway> <interface>
post-down killall -q wpa_supplicant

Keep up,

Anonymous said...

Grandiose and verbose gratitude. Excellent step by step!

arvindh said...

nice post. But i have a WIFI network without any security protocol.

BSS xx:xx:xx:xx:xx:xx (on wlan0)
TSF: 478427021 usec (0d, 00:07:58)
freq: 2437
beacon interval: 100
capability: ESS ShortPreamble ShortSlotTime (0x0421)
signal: -45.00 dBm
SSID: tpay
Supported rates: 1.0* 2.0* 5.5* 11.0*
DS Parameter set: channel 6
Extended supported rates: 6.0 9.0 12.0 18.0 24.0 36.0 48.0 54.0
HT capabilities:
Capabilities: 0x12c
SM Power Save disabled
RX STBC 1-stream
Max AMSDU length: 7935 bytes
Maximum RX AMPDU length 65535 bytes (exponent: 0x003)
Minimum RX AMPDU time spacing: No restriction (0x00)
HT RX MCS rate indexes supported: 0-7
HT TX MCS rate indexes are undefined
WMM: * Parameter version 1
* u-APSD
* BE: CW 15-1023, AIFSN 3
* BK: CW 15-1023, AIFSN 7
* VI: CW 7-15, AIFSN 2, TXOP 3008 usec
* VO: CW 3-7, AIFSN 2, TXOP 1504 usec

How can i connect to this network through command line,..???
can any one plz help,..!!

Bostek said...

Dude you're awsome!! Thx for that. I had a big problem to configure wireless until i found your step by step solution!

Everything works great now!!
Thx again!

Anonymous said...

Thank you so much for that. It solved my problem as well :)

Softql said...

very nice blog i am very interseting your blog
RF Post processing

Anonymous said...

Thank you so much!

trayalis29 said...

Thank you verymuch for your step by step procedures and the explanations.

Anonymous said...

you are awesome. Thanks for a great tut.

Krish said...

The very very best description...

Atlatl said...

# wpa_supplicant -B -D wext -i wlan0 -c /etc/wpa_supplicant.conf
Successfully initialized wpa_supplicant
ioctl[SIOCSIWENCODEEXT]: Invalid argument
ioctl[SIOCSIWENCODEEXT]: Invalid argument
# iw wlan0 link
Not connected.

this is a driver problem (-D wext).
you need to find the driver used by your wifi controller. take a look at lsmod output.
if you use intel wifi : replace wext by nl80211.

Anonymous said...

I was stuck in minimal install on laptop and only tablet has internet. Thanks a lot.

Anonymous said...

I'm using Gentoo
I had to remove the space after the -c /etc/wpa_supplicant.conf

+ wpa_supplicant -B -D wext -i wlan0 -c/etc/wpa_supplicant.conf
- wpa_supplicant -B -D wext -i wlan0 -c /etc/wpa_supplicant.conf

Awesome right up!


goshthatwashandy said...

Outstanding! Helped me so much.

Anonymous said...

Nice tutorial but I still cannot connect. I have tried both drivers, as well as omitting -D, and none connect. Is the correct connect syntax "sudo iw connect -w "? I did not see this in your article, does the wpa_supplicant run this automatically on initialisation? I'll look elsewhere for now but keep up the good work, this is arcane stuff. If only iw's help and man pages were as well organised as wpa_supplicant's...

Anonymous said...

You absolute star!

I gave my technically-inespeiernced brother Opensuse since i can teamviewer in to fix any issues he has, but when Display-manager failed i thought I was screwed, This guide helped him connect to wireless so i could ssh in

atlatl's comment also helped a lot. the original article failed in assuming drivers.

Wisknort said...

Used lspci -nnk | grep -iA2 net, got:
07:07.0 Network controller [0280]: Qualcomm Atheros AR9227 Wireless Network Adapter [168c:002d] (rev 01)
Subsystem: Qualcomm Atheros Device [168c:0301]
Kernel driver in use: ath9k

(As well as my ethernet.)
So I did this:

desktop@steamos:~$ lsmod | grep ath9k
ath9k 94208 0
ath9k_common 28672 1 ath9k
ath9k_hw 425984 2 ath9k_common,ath9k
ath 28672 3 ath9k_common,ath9k,ath9k_hw
mac80211 569344 1 ath9k
cfg80211 458752 5 wl,ath,ath9k_common,ath9k,mac80211
desktop@steamos:~$ sudo wpa_supplicant -B -D ath9k -i wlan0 -c /etc/wpa_supplicant.conf
Successfully initialized wpa_supplicant
wlan0: Unsupported driver 'ath9k'

Then tried everything else in that list, and got the same result from all of them. What do?

Christian said...

My security protocol is not PSK, and I believe it requires a login as well as the password.

RSN: * Version: 1
* Group cipher: TKIP
* Pairwise ciphers: CCMP
* Authentication suites: IEEE 802.1X
* Capabilities: 4-PTKSA-RC 4-GTKSA-RC (0x0028)

How do I change the wpa_supplicant file to that?

Andrew Franklin said...

Good Article.

But, It will be more better if you add some screenshot to the post.

Anyway, Good

Wisknort said...

Update on my case, I cabled in so I could update everything and see if that fixed it. After they were done, I rebooted, and no change.

Then I booted again a few days later and it worked flawlessly. Go figure.

Anonymous said...

Thank you very much, very useful.

Larm Stockholm said...

Thank you for share Peter, that was what i was looking for

sandeep said...

1st of all. . Thanks for the detailed steps. After this I got the internet. But I have 2 questions.
1. After rebooting my laptop I have to do redo this procedure again. Can't we make this permanent?

2. I have a lan on the same network and the default route is already with the lan. And now when i try to add the default route again it says rtnetlink file exists. Is there a way I have same default route from both lan and wifi

Anonymous said...

so helpful & useful. also, thanks Peter Leung for the scan hidden networks tip.

you'd be hard pressed to find anything more basic and informative as this. truly the best help page on command line wifi configuration i've been able to find on the internet anywhere... and i've been to a lot of pages covering this topic. thanks again.

P.S.S. ABISHEK said...

When I typed the second step of connecting to the WPA2 wifi network it shows Operation Not permitted. What's the fix for this ?

ExpHP said...

# wpa_supplicant -B -D wext -i wlan0 -c /etc/wpa_supplicant.conf
Successfully initialized wpa_supplicant
ioctl[SIOCSIWENCODEEXT]: Invalid argument
ioctl[SIOCSIWENCODEEXT]: Invalid argument
# iw wlan0 link
Not connected.

I got this too (using Netgear N150 Wireless Adapter WNA1100), and just now finally resolved it after a good hour of muddling about.

As another person has mentioned, part of the trick is to make sure you're using the right driver. To find what options are available:

# wpa_supplicant -h
nl80211 = Linux nl80211/cfg80211
wext = Linux wireless extensions (generic)
wired = Wired Ethernet driver

The right choice for me is nl80211.

# wpa_supplicant -B -D nl80211 -i wlan0 -c /etc/wpa_supplicant.conf
Successfully initialized wpa_supplicant
# iw wlan0 link
Not connected.

...and then this is the next problem I ran into. The errors disappeared, but it still did not connect! So on I went, continuing to try other things, with all of it failing...until it occurred to me.

# pgrep wpa_supplicant

Each time you do "wpa_supplicant -B" it leaves a new instance running! And they all compete with each other!

# pkill wpa_supplicant
# wpa_supplicant -B -D nl80211 -i wlan0 -c /etc/wpa_supplicant.conf
Successfully initialized wpa_supplicant
# iw wlan0 link
Connected to my:ma:ca:dd:re:ss (on wlan0)