Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
Keep profiles for wireless networks and connect to them
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks
View previous topic :: View next topic  
Author Message
Cyberloon
n00b
n00b


Joined: 22 Jun 2004
Posts: 1
Location: Iceland

PostPosted: Thu Jul 08, 2004 12:07 am    Post subject: Keep profiles for wireless networks and connect to them Reply with quote

I haven't seen anything like this on the forum, so I thought I'd like to share my solution with you.
I take my laptop with me pretty much everywhere and in many of the places that I go to I have access to a wireless network, most of these networks have different settings and different magic that needs to be done to log on. So being the lazy person that I am (read programmer), I created a simple script that lets me create a profile for each network and then connect to the networks using those profiles.

To use my script you will need to place it in a folder that is accessible, I used /usr/local/bin
It will read the network profiles from /etc/pikey-config but that can easily be changed.
I made the /etc/pikey-config file the property of root and changed it's' mode so only root can read it and write to it.
I added the pikey script to my sudo profile, so that others using my laptop could also use the wireless networks.

/usr/local/bin/pikey
Code:

#!/usr/bin/python
#
# pikey - A convenience script for people which use many wireless networks
#
# I wrote this because I travel a lot with my laptop, and don't know which
# network I will be using each time I start it up. I like to open a
# terminal after I log in and type `pikey home` or `pikey work` depending
# on where I am.
# I added a sudo policy for this so that I can have other users using my
# machine, without actually letting them read the network config file and
# the WEP keys stored in it.
# There is minimal commenting in the code since I feel that the function
# and variable names speak for themselves along with the output strings.
# This script does everything that I need it to do, but I would love to
# see any changes made to it.
#
# This code is protected by the GNU GPL http://www.gnu.org/
#

import os
import sys

# Since we will be running as root, we will use absolute paths
iwconfig = '/usr/sbin/iwconfig'
ifconfig = '/sbin/ifconfig'
dhcpcd = '/sbin/dhcpcd'
route = '/sbin/route'
pikeyConfig = '/etc/pikey-networks'
resolvFile = '/etc/resolv.conf'
domainFile = '/etc/dnsdomainname'

maxNameLength = 32  # I see no need for longer names.


def FetchNameProperty(nameDict, netName, propName):
    """Fetch a name stored in a dict
   
    The property decleration will probably look something like this:
        netName_propName = 'some stuff'
    """
    assert type(nameDict) is dict, 'nameDict must be a dict'
    assert type(netName) is str, 'netName must be a string'
    assert type(propName) is str, 'propName must be a string'
   
    return nameDict.get(netName + '_' + propName, None)


def StartWirelessNet(name=None, adapter='eth1'):
    """Connect to a wireless network
   
    name will be the name of a network stored in pikey-config.
    adapter is your wireless network device.
    """
    if not type(name) is str:
        print 'name must be a string'
        return False
    if not type(adapter) is str:
        print 'adapter must be a string'
        return False
   
    # Read in the config file, it is parsed as a Python file for conveniece
    networks = {}
    networkData = file(pikeyConfig, 'rb').read() + '\n'
    networkCode = compile(networkData, 'nw-data', 'exec')
    eval(networkCode, networks, networks)

    if name not in networks.keys():
        print 'Name "%s" was not found' % name
        return False
   
    print 'Configuring wireless network... ',
    res = os.system('%s %s %s > /dev/null' % (iwconfig, adapter, networks[name]))
    if res != 0:
        print 'iwconfig failed'
        return False
    print 'Done'
   
    specialIfconf = FetchNameProperty(networks, name, 'ifconf')
    print 'Bringing wireless card online... ',
    if not specialIfconf:
        res = os.system('%s %s up > /dev/null' % (ifconfig, adapter))
    else:
        res = os.system('%s %s %s > /dev/null' % (ifconfig, adapter, specialIfconf))
    if res != 0:
        print 'ifconfig failed'
        return False
    print 'Done'
   
    useDhcp = FetchNameProperty(networks, name, 'dhcp')
    if useDhcp:
        print 'Contacting DHCP host... ',
        res = os.system('%s %s > /dev/null' % (dhcpcd, adapter))
        if res != 0:
            print 'dhcpcd failed'
            return False
        print 'Done'
   
    setupGateway = FetchNameProperty(networks, name, 'gateway')
    if setupGateway:
        print 'Setting default gateway... ',
        res = os.system('%s %s > /dev/null' % (route, setupGateway))
        if res != 0:
            print 'route failed'
            return False
        print 'Done'
   
    nameservers = FetchNameProperty(networks, name, 'nameservers')
    if nameservers:
        print 'Setting up nameserver table... ',
        resolvFileObj = file(resolvFile, 'w')
        dnsDomainName = file(domainFile, 'r').read()
       
        resolvFileObj.write('domain %s\n' % dnsDomainName)
        for each in nameservers:
            resolvFileObj.write('nameserver %s\n' % each)
        resolvFileObj.close()
        print 'Done'
   
    return True


if __name__ == '__main__':
    if len(sys.argv) == 1:
        print 'pikey - Wireless network automation tool'
        print
        print 'Usage:'
        print '  pikey configname [adapter]'
        print
        print 'The configname argument tells Pikey what network to select.'
        print 'Names of configured networks are in %s' % pikeyConfig
        print 'The adapter argument tells Pikey which network adapter to configure (defaults to eth1)'
    elif len(sys.argv) == 2:
        if not sys.argv[1].isalpha():
            print 'Illegal network name:', sys.argv[1]
        else:
            StartWirelessNet(sys.argv[1][:maxNameLength])
    else:
        if not sys.argv[1].isalpha():
            print 'Illegal network name:', sys.argv[1]
        elif not sys.argv[2].isalpha():
            print 'Illegal adapter name:', sys.argv[2]
        else:
            StartWirelessNet(sys.argv[1][:maxNameLength], sys.argv[2][:maxNameLength])


/etc/pikey-networks
Code:

#
# Sample config file for pikey (owned by root)
#
# I store it in /etc/pikey-config but it could be anywhere really.
#
# Permissions for this file should be set something like this
#
# chmod 640 pikey-networks       or
# chmod 600 pikey-networks
#
# Then we use sudo to run pikey as root, so no one else needs to
# be able to read this file.
#

# The network config name holds the parameters passed to iwconfig
home = 'essid HomeWireless key xxxxxxxxxx'
home_dhcp = True

work = 'essid WorkWireless key open xxxxxxxxxx'
# We can specify what parameters we wish to send to ifconfig
work_ifconf = '192.168.0.5 netmask 255.255.255.0 up'
# What gateway we want to use
work_gateway = 'add default gw 192.168.0.254'
# And which nameservers
work_nameservers = ['192.168.0.254']
work_dhcp = False



I added this line to /etc/sudoers
Code:

%users  ALL=NOPASSWD:/usr/bin/pikey

And this line to my .bashrc
Code:

alias pikey="sudo /usr/local/bin/pikey"


Now when I want to connect to the wireless network at home, all I have to do is open a terminal window and issue the following command pikey home :)
Back to top
View user's profile Send private message
blais
n00b
n00b


Joined: 30 Jul 2003
Posts: 57

PostPosted: Mon Apr 04, 2005 10:10 pm    Post subject: aerial Reply with quote

hi pikey

i'm almost done writing a program that will do that but with a gui and a network signal feedback.
also written in Python, on top of Qt.

let me know if you'd like to get it. i'll publish it at some point very soon.

cheers,
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Documentation, Tips & Tricks All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum