Debian Codegraph @

examples/linksys.py

raw
1 #! /usr/bin/env python
2 # vi:ts=4:et
3 #
4 # linksys.py -- program settings on a Linkys router
5 #
6 # This tool is designed to help you recover from the occasional episodes
7 # of catatonia that afflict Linksys boxes. It allows you to batch-program
8 # them rather than manually entering values to the Web interface. Commands
9 # are taken from the command line first, then standard input.
10 #
11 # The somewhat spotty coverage of status queries is because I only did the
12 # ones that were either (a) easy, or (b) necessary. If you want to know the
13 # status of the box, look at the web interface.
14 #
15 # This code has been tested against the following hardware:
16 #
17 # Hardware Firmware
18 # ---------- ---------------------
19 # BEFW11S4v2 1.44.2.1, Dec 20 2002
20 #
21 # The code is, of course, sensitive to changes in the names of CGI pages
22 # and field names.
23 #
24 # Note: to make the no-arguments form work, you'll need to have the following
25 # entry in your ~/.netrc file. If you have changed the router IP address or
26 # name/password, modify accordingly.
27 #
28 # machine 192.168.1.1
29 # login ""
30 # password admin
31 #
32 # By Eric S. Raymond, August April 2003. All rites reversed.
33
34 import sys, re, curl, exceptions
35
36 def print_stderr(arg):
37 sys.stderr.write(arg)
38 sys.stderr.write("\n")
39
40 class LinksysError(exceptions.Exception):
41 def __init__(self, *args):
42 self.args = args
43
44 class LinksysSession:
45 months = 'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec'
46
47 WAN_CONNECT_AUTO = '1'
48 WAN_CONNECT_STATIC = '2'
49 WAN_CONNECT_PPOE = '3'
50 WAN_CONNECT_RAS = '4'
51 WAN_CONNECT_PPTP = '5'
52 WAN_CONNECT_HEARTBEAT = '6'
53
54 # Substrings to check for on each page load.
55 # This may enable us to detect when a firmware change has hosed us.
56 check_strings = {
57 "": "basic setup functions",
58 "Passwd.htm": "For security reasons,",
59 "DHCP.html": "You can configure the router to act as a DHCP",
60 "Log.html": "There are some log settings and lists in this page.",
61 "Forward.htm":"Port forwarding can be used to set up public services",
62 }
63
64 def __init__(self):
65 self.actions = []
66 self.host = "http://192.168.1.1"
67 self.verbosity = False
68 self.pagecache = {}
69
70 def set_verbosity(self, flag):
71 self.verbosity = flag
72
73 # This is not a performance hack -- we need the page cache to do
74 # sanity checks at configure time.
75 def cache_load(self, page):
76 if page not in self.pagecache:
77 fetch = curl.Curl(self.host)
78 fetch.set_verbosity(self.verbosity)
79 fetch.get(page)
80 self.pagecache[page] = fetch.body()
81 if fetch.answered("401"):
82 raise LinksysError("authorization failure.", True)
83 elif not fetch.answered(LinksysSession.check_strings[page]):
84 del self.pagecache[page]
85 raise LinksysError("check string for page %s missing!" % os.path.join(self.host, page), False)
86 fetch.close()
87 def cache_flush(self):
88 self.pagecache = {}
89
90 # Primitives
91 def screen_scrape(self, page, template):
92 self.cache_load(page)
93 match = re.compile(template).search(self.pagecache[page])
94 if match:
95 result = match.group(1)
96 else:
97 result = None
98 return result
99 def get_MAC_address(self, page, prefix):
100 return self.screen_scrape("", prefix+r":[^M]*\(MAC Address: *([^)]*)")
101 def set_flag(self, page, flag, value):
102 if value:
103 self.actions.append(page, flag, "1")
104 else:
105 self.actions.append(page, flag, "0")
106 def set_IP_address(self, page, cgi, role, ip):
107 ind = 0
108 for octet in ip.split("."):
109 self.actions.append(("", "F1", role + repr(ind+1), octet))
110 ind += 1
111
112 # Scrape configuration data off the main page
113 def get_firmware_version(self):
114 # This is fragile. There is no distinguishing tag before the firmware
115 # version, so we have to key off the pattern of the version number.
116 # Our model is ">1.44.2.1, Dec 20 2002<"
117 return self.screen_scrape("", ">([0-9.v]*, (" + \
118 LinksysSession.months + ")[^<]*)<", )
119 def get_LAN_MAC(self):
120 return self.get_MAC_address("", r"LAN IP Address")
121 def get_Wireless_MAC(self):
122 return self.get_MAC_address("", r"Wireless")
123 def get_WAN_MAC(self):
124 return self.get_MAC_address("", r"WAN Connection Type")
125
126 # Set configuration data on the main page
127 def set_host_name(self, name):
128 self.actions.append(("", "hostName", name))
129 def set_domain_name(self, name):
130 self.actions.append(("", "DomainName", name))
131 def set_LAN_IP(self, ip):
132 self.set_IP_address("", "ipAddr", ip)
133 def set_LAN_netmask(self, ip):
134 if not ip.startswith("255.255.255."):
135 raise ValueError
136 lastquad = ip.split(".")[-1]
137 if lastquad not in ("0", "128", "192", "240", "252"):
138 raise ValueError
139 self.actions.append("", "netMask", lastquad)
140 def set_wireless(self, flag):
141 self.set_flag("", "wirelessStatus")
142 def set_SSID(self, ssid):
143 self.actions.append(("", "wirelessESSID", ssid))
144 def set_SSID_broadcast(self, flag):
145 self.set_flag("", "broadcastSSID")
146 def set_channel(self, channel):
147 self.actions.append(("", "wirelessChannel", channel))
148 def set_WEP(self, flag):
149 self.set_flag("", "WepType")
150 # FIXME: Add support for setting WEP keys
151 def set_connection_type(self, type):
152 self.actions.append(("", "WANConnectionType", type))
153 def set_WAN_IP(self, ip):
154 self.set_IP_address("", "aliasIP", ip)
155 def set_WAN_netmask(self, ip):
156 self.set_IP_address("", "aliasMaskIP", ip)
157 def set_WAN_gateway_address(self, ip):
158 self.set_IP_address("", "routerIP", ip)
159 def set_DNS_server(self, index, ip):
160 self.set_IP_address("", "dns" + "ABC"[index], ip)
161
162 # Set configuration data on the password page
163 def set_password(self, str):
164 self.actions.append("Passwd.htm","sysPasswd", str)
165 self.actions.append("Passwd.htm","sysPasswdConfirm", str)
166 def set_UPnP(self, flag):
167 self.set_flag("Passwd.htm", "UPnP_Work")
168 def reset(self):
169 self.actions.append("Passwd.htm", "FactoryDefaults")
170
171 # DHCP features
172 def set_DHCP(self, flag):
173 if flag:
174 self.actions.append("DHCP.htm","dhcpStatus","Enable")
175 else:
176 self.actions.append("DHCP.htm","dhcpStatus","Disable")
177 def set_DHCP_starting_IP(self, val):
178 self.actions.append("DHCP.htm","dhcpS4", str(val))
179 def set_DHCP_users(self, val):
180 self.actions.append("DHCP.htm","dhcpLen", str(val))
181 def set_DHCP_lease_time(self, val):
182 self.actions.append("DHCP.htm","leaseTime", str(val))
183 def set_DHCP_DNS_server(self, index, ip):
184 self.set_IP_address("DHCP.htm", "dns" + "ABC"[index], ip)
185 # FIXME: add support for setting WINS key
186
187 # Logging features
188 def set_logging(self, flag):
189 if flag:
190 self.actions.append("Log.htm", "rLog", "Enable")
191 else:
192 self.actions.append("Log.htm", "rLog", "Disable")
193 def set_log_address(self, val):
194 self.actions.append("DHCP.htm","trapAddr3", str(val))
195
196 # The AOL parental control flag is not supported by design.
197
198 # FIXME: add Filters and other advanced features
199
200 def configure(self):
201 "Write configuration changes to the Linksys."
202 if self.actions:
203 fields = []
204 self.cache_flush()
205 for (page, field, value) in self.actions:
206 self.cache_load(page)
207 if self.pagecache[page].find(field) == -1:
208 print_stderr("linksys: field %s not found where expected in page %s!" % (field, os.path.join(self.host, page)))
209 continue
210 else:
211 fields.append((field, value))
212 # Clearing the action list before fieldsping is deliberate.
213 # Otherwise we could get permanently wedged by a 401.
214 self.actions = []
215 transaction = curl.Curl(self.host)
216 transaction.set_verbosity(self.verbosity)
217 transaction.get("Gozila.cgi", tuple(fields))
218 transaction.close()
219
220 if __name__ == "__main__":
221 import os, cmd
222
223 class LinksysInterpreter(cmd.Cmd):
224 """Interpret commands to perform LinkSys programming actions."""
225 def __init__(self):
226 cmd.Cmd.__init__(self)
227 self.session = LinksysSession()
228 if os.isatty(0):
229 print("Type ? or `help' for help.")
230 self.prompt = self.session.host + ": "
231 else:
232 self.prompt = ""
233 print("Bar1")
234
235 def flag_command(self, func, line):
236 if line.strip() in ("on", "enable", "yes"):
237 func(True)
238 elif line.strip() in ("off", "disable", "no"):
239 func(False)
240 else:
241 print_stderr("linksys: unknown switch value")
242 return 0
243
244 def do_connect(self, line):
245 newhost = line.strip()
246 if newhost:
247 self.session.host = newhost
248 self.session.cache_flush()
249 self.prompt = self.session.host + ": "
250 else:
251 print(self.session.host)
252 return 0
253 def help_connect(self):
254 print("Usage: connect [<hostname-or-IP>]")
255 print("Connect to a Linksys by name or IP address.")
256 print("If no argument is given, print the current host.")
257
258 def do_status(self, line):
259 self.session.cache_load("")
260 if "" in self.session.pagecache:
261 print("Firmware:", self.session.get_firmware_version())
262 print("LAN MAC:", self.session.get_LAN_MAC())
263 print("Wireless MAC:", self.session.get_Wireless_MAC())
264 print("WAN MAC:", self.session.get_WAN_MAC())
265 print(".")
266 return 0
267 def help_status(self):
268 print("Usage: status")
269 print("The status command shows the status of the Linksys.")
270 print("It is mainly useful as a sanity check to make sure")
271 print("the box is responding correctly.")
272
273 def do_verbose(self, line):
274 self.flag_command(self.session.set_verbosity, line)
275 def help_verbose(self):
276 print("Usage: verbose {on|off|enable|disable|yes|no}")
277 print("Enables display of HTTP requests.")
278
279 def do_host(self, line):
280 self.session.set_host_name(line)
281 return 0
282 def help_host(self):
283 print("Usage: host <hostname>")
284 print("Sets the Host field to be queried by the ISP.")
285
286 def do_domain(self, line):
287 print("Usage: host <domainname>")
288 self.session.set_domain_name(line)
289 return 0
290 def help_domain(self):
291 print("Sets the Domain field to be queried by the ISP.")
292
293 def do_lan_address(self, line):
294 self.session.set_LAN_IP(line)
295 return 0
296 def help_lan_address(self):
297 print("Usage: lan_address <ip-address>")
298 print("Sets the LAN IP address.")
299
300 def do_lan_netmask(self, line):
301 self.session.set_LAN_netmask(line)
302 return 0
303 def help_lan_netmask(self):
304 print("Usage: lan_netmask <ip-mask>")
305 print("Sets the LAN subnetwork mask.")
306
307 def do_wireless(self, line):
308 self.flag_command(self.session.set_wireless, line)
309 return 0
310 def help_wireless(self):
311 print("Usage: wireless {on|off|enable|disable|yes|no}")
312 print("Switch to enable or disable wireless features.")
313
314 def do_ssid(self, line):
315 self.session.set_SSID(line)
316 return 0
317 def help_ssid(self):
318 print("Usage: ssid <string>")
319 print("Sets the SSID used to control wireless access.")
320
321 def do_ssid_broadcast(self, line):
322 self.flag_command(self.session.set_SSID_broadcast, line)
323 return 0
324 def help_ssid_broadcast(self):
325 print("Usage: ssid_broadcast {on|off|enable|disable|yes|no}")
326 print("Switch to enable or disable SSID broadcast.")
327
328 def do_channel(self, line):
329 self.session.set_channel(line)
330 return 0
331 def help_channel(self):
332 print("Usage: channel <number>")
333 print("Sets the wireless channel.")
334
335 def do_wep(self, line):
336 self.flag_command(self.session.set_WEP, line)
337 return 0
338 def help_wep(self):
339 print("Usage: wep {on|off|enable|disable|yes|no}")
340 print("Switch to enable or disable WEP security.")
341
342 def do_wan_type(self, line):
343 try:
344 type=eval("LinksysSession.WAN_CONNECT_"+line.strip().upper())
345 self.session.set_connection_type(type)
346 except ValueError:
347 print_stderr("linksys: unknown connection type.")
348 return 0
349 def help_wan_type(self):
350 print("Usage: wan_type {auto|static|ppoe|ras|pptp|heartbeat}")
351 print("Set the WAN connection type.")
352
353 def do_wan_address(self, line):
354 self.session.set_WAN_IP(line)
355 return 0
356 def help_wan_address(self):
357 print("Usage: wan_address <ip-address>")
358 print("Sets the WAN IP address.")
359
360 def do_wan_netmask(self, line):
361 self.session.set_WAN_netmask(line)
362 return 0
363 def help_wan_netmask(self):
364 print("Usage: wan_netmask <ip-mask>")
365 print("Sets the WAN subnetwork mask.")
366
367 def do_wan_gateway(self, line):
368 self.session.set_WAN_gateway(line)
369 return 0
370 def help_wan_gateway(self):
371 print("Usage: wan_gateway <ip-address>")
372 print("Sets the LAN subnetwork mask.")
373
374 def do_dns(self, line):
375 (index, address) = line.split()
376 if index in ("1", "2", "3"):
377 self.session.set_DNS_server(eval(index), address)
378 else:
379 print_stderr("linksys: server index out of bounds.")
380 return 0
381 def help_dns(self):
382 print("Usage: dns {1|2|3} <ip-mask>")
383 print("Sets a primary, secondary, or tertiary DNS server address.")
384
385 def do_password(self, line):
386 self.session.set_password(line)
387 return 0
388 def help_password(self):
389 print("Usage: password <string>")
390 print("Sets the router password.")
391
392 def do_upnp(self, line):
393 self.flag_command(self.session.set_UPnP, line)
394 return 0
395 def help_upnp(self):
396 print("Usage: upnp {on|off|enable|disable|yes|no}")
397 print("Switch to enable or disable Universal Plug and Play.")
398
399 def do_reset(self, line):
400 self.session.reset()
401 def help_reset(self):
402 print("Usage: reset")
403 print("Reset Linksys settings to factory defaults.")
404
405 def do_dhcp(self, line):
406 self.flag_command(self.session.set_DHCP, line)
407 def help_dhcp(self):
408 print("Usage: dhcp {on|off|enable|disable|yes|no}")
409 print("Switch to enable or disable DHCP features.")
410
411 def do_dhcp_start(self, line):
412 self.session.set_DHCP_starting_IP(line)
413 def help_dhcp_start(self):
414 print("Usage: dhcp_start <number>")
415 print("Set the start address of the DHCP pool.")
416
417 def do_dhcp_users(self, line):
418 self.session.set_DHCP_users(line)
419 def help_dhcp_users(self):
420 print("Usage: dhcp_users <number>")
421 print("Set number of address slots to allocate in the DHCP pool.")
422
423 def do_dhcp_lease(self, line):
424 self.session.set_DHCP_lease(line)
425 def help_dhcp_lease(self):
426 print("Usage: dhcp_lease <number>")
427 print("Set number of address slots to allocate in the DHCP pool.")
428
429 def do_dhcp_dns(self, line):
430 (index, address) = line.split()
431 if index in ("1", "2", "3"):
432 self.session.set_DHCP_DNS_server(eval(index), address)
433 else:
434 print_stderr("linksys: server index out of bounds.")
435 return 0
436 def help_dhcp_dns(self):
437 print("Usage: dhcp_dns {1|2|3} <ip-mask>")
438 print("Sets primary, secondary, or tertiary DNS server address.")
439
440 def do_logging(self, line):
441 self.flag_command(self.session.set_logging, line)
442 def help_logging(self):
443 print("Usage: logging {on|off|enable|disable|yes|no}")
444 print("Switch to enable or disable session logging.")
445
446 def do_log_address(self, line):
447 self.session.set_Log_address(line)
448 def help_log_address(self):
449 print("Usage: log_address <number>")
450 print("Set the last quad of the address to which to log.")
451
452 def do_configure(self, line):
453 self.session.configure()
454 return 0
455 def help_configure(self):
456 print("Usage: configure")
457 print("Writes the configuration to the Linksys.")
458
459 def do_cache(self, line):
460 print(self.session.pagecache)
461 def help_cache(self):
462 print("Usage: cache")
463 print("Display the page cache.")
464
465 def do_quit(self, line):
466 return 1
467 def help_quit(self, line):
468 print("The quit command ends your linksys session without")
469 print("writing configuration changes to the Linksys.")
470 def do_EOF(self, line):
471 print("")
472 self.session.configure()
473 return 1
474 def help_EOF(self):
475 print("The EOF command writes the configuration to the linksys")
476 print("and ends your session.")
477
478 def default(self, line):
479 """Pass the command through to be executed by the shell."""
480 os.system(line)
481 return 0
482
483 def help_help(self):
484 print("On-line help is available through this command.")
485 print("? is a convenience alias for help.")
486
487 def help_introduction(self):
488 print("""\
489
490 This program supports changing the settings on Linksys blue-box routers. This
491 capability may come in handy when they freeze up and have to be reset. Though
492 it can be used interactively (and will command-prompt when standard input is a
493 terminal) it is really designed to be used in batch mode. Commands are taken
494 from the command line first, then standard input.
495
496 By default, it is assumed that the Linksys is at http://192.168.1.1, the
497 default LAN address. You can connect to a different address or IP with the
498 'connect' command. Note that your .netrc must contain correct user/password
499 credentials for the router. The entry corresponding to the defaults is:
500
501 machine 192.168.1.1
502 login ""
503 password admin
504
505 Most commands queue up changes but don't actually send them to the Linksys.
506 You can force pending changes to be written with 'configure'. Otherwise, they
507 will be shipped to the Linksys at the end of session (e.g. when the program
508 running in batch mode encounters end-of-file or you type a control-D). If you
509 end the session with `quit', pending changes will be discarded.
510
511 For more help, read the topics 'wan', 'lan', and 'wireless'.""")
512
513 def help_lan(self):
514 print("""\
515 The `lan_address' and `lan_netmask' commands let you set the IP location of
516 the Linksys on your LAN, or inside. Normally you'll want to leave these
517 untouched.""")
518
519 def help_wan(self):
520 print("""\
521 The WAN commands become significant if you are using the BEFSR41 or any of
522 the other Linksys boxes designed as DSL or cable-modem gateways. You will
523 need to use `wan_type' to declare how you expect to get your address.
524
525 If your ISP has issued you a static address, you'll need to use the
526 `wan_address', `wan_netmask', and `wan_gateway' commands to set the address
527 of the router as seen from the WAN, the outside. In this case you will also
528 need to use the `dns' command to declare which remote servers your DNS
529 requests should be forwarded to.
530
531 Some ISPs may require you to set host and domain for use with dynamic-address
532 allocation.""")
533
534 def help_wireless_desc(self):
535 print("""\
536 The channel, ssid, ssid_broadcast, wep, and wireless commands control
537 wireless routing.""")
538
539 def help_switches(self):
540 print("Switches may be turned on with 'on', 'enable', or 'yes'.")
541 print("Switches may be turned off with 'off', 'disable', or 'no'.")
542 print("Switch commands include: wireless, ssid_broadcast.")
543
544 def help_addresses(self):
545 print("An address argument must be a valid IP address;")
546 print("four decimal numbers separated by dots, each ")
547 print("between 0 and 255.")
548
549 def emptyline(self):
550 pass
551
552 interpreter = LinksysInterpreter()
553 for arg in sys.argv[1:]:
554 interpreter.onecmd(arg)
555 fatal = False
556 while not fatal:
557 try:
558 interpreter.cmdloop()
559 fatal = True
560 except LinksysError:
561 message, fatal = sys.exc_info()[1].args
562 print("linksys: " + message)
563
564 # The following sets edit modes for GNU EMACS
565 # Local Variables:
566 # mode:python
567 # End: