Automatically connect to a wireless network using CLI

I need my machine to connect to a wireless network automatically every time it starts

I'm running a headless server (10.04) and I use following commands to manually connect to the network

sudo iwconfig wlan0 essid "SSID_Name"
sudo iwconfig wlan0 key XXXXX
sudo iwconfig wlan0 key open
sudo iwconfig wlan0 mode Managed
sudo dhclient wlan0

I will appreciate if we can do that by modifying etc/network/interfaces file

Please note that my router is running wep, thanks in advance


Solution 1:

Please amend your /etc/network/interfaces file to:

auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet dhcp
wireless-ssid SSID_Name
wireless-key XXXXX

If you expect to ssh and ftp into the server, you need to know where it is. Do so with a static IP address:

auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet static
address 192.168.1.150
netmask 255.255.255.0
gateway 192.168.1.1
wireless-ssid SSID_Name
wireless-key XXXXX
dns-nameservers 8.8.8.8 192.168.1.1

Moreover, your settings imply that your network is encrypted with WEP which is quite insecure. I recommend you change the router to WPA2-AES:

auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet static
address 192.168.1.150
netmask 255.255.255.0
gateway 192.168.1.1
wpa-essid SSID_Name
wpa-psk XXXXX
dns-nameservers 8.8.8.8 192.168.1.1

Be sure to select an address outside the range used by the DHCP server in the router and, of course, substitute your details here.

Solution 2:

Automatic Wireless Connection when Login

For cases where you would like to login automatically to a wireless router here are the steps:

  1. Open the interface file:

    sudo nano /etc/network/interfaces
    
  2. Add the following information (Assuming your interface is called wlan0):

    auto wlan0
    iface wlan0 inet static
    address ASSIGNED_IP
    netmask 255.255.255.0
    gateway THE_GATEWAY
    wireless-essid YOURSSID
    wireless-key WIRELESSKEY_HERE
    
  3. Save the file and reboot computer.