Wireless access with a Ruby script
I wrote a Ruby script to automate the process of connecting to a wireless access point. Granted, it would be better if the wireless adapter connected on startup, but I haven’t gotten that far yet. The script is a command line executable. It scans for all available networks, or lets you specify a network not listed in the scan. Then it gives the option of connecting with or without a WEP key, and finally it connects using DHCP.
This is one of my first Ruby scripts and as such is a bit rough. It could probably be condensed and would really need some comments, error checking, etc. But here it goes, in less than 50 lines:
#!/usr/bin/ruby
class Wifi
def initialize(devfile)
@devfile = devfile
@ssids = []
end
def scan
@ssids = []
for line in `wlanconfig #{@devfile} list scan`
ssid = line.chomp.split(/s+/)[0]
unless ssid == "SSID": @ssids.push(ssid) end
end
@ssids.push("other network")
end
def chooseNetwork
if @ssids.empty?: scan end
puts "Available networks:"
option = 1
for ssid in @ssids
puts option.to_s + ") " + ssid
option += 1
end
print "Select network #: "
@network = @ssids[gets.to_i-1]
if @network == "other network"
print "Specify other network name: "
@network = gets
end
end
def connect
print "Connect using WEP?: "
if gets =~ /^y/i
print "Input WEP key: "
wep = gets
`iwpriv #{@devfile} authmode 1`
`iwconfig #{@devfile} key #{wep}`
end
`dhclient #{@devfile}`
end
end
if __FILE__ == $0
wifi = Wifi.new("ath0")
wifi.chooseNetwork
wifi.connect
end
Drop a comment with any suggested improvements. It sure could use some.