Commits

jasama  committed 94e690c

Added possibility to use a config file for storing options, as they tend to
be exposed to others (i.e. 'ps aux' on *nix).

Imported with, so it will run on 2.5.

  • Participants
  • Parent commits 9759367

Comments (0)

Files changed (1)

 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
+from __future__ import with_statement
+
 import smtplib
 from email.mime.text import MIMEText
 import sys
 
     # Logg inn i studweb
     tc.go("https://studweb.uio.no/as/WebObjects/studentweb2.woa/3/wa/default?inst=UiO")
-    tc.fv("2", "fodselsnr", opts.fnr)
-    tc.fv("2", "pinkode", opts.pin)
+    tc.fv("2", "fodselsnr", opts["fnr"])
+    tc.fv("2", "pinkode", opts["pin"])
     tc.submit()
 
     # Naviger til karakterer
 def sendNetcom(opts, msg):
     tc.go("https://www.netcom.no")
     tc.follow("» Logg inn på Min side")
-    tc.fv('2', 'username', opts.netcom_user)
-    tc.fv('2', 'password', opts.netcom_pass)
+    tc.fv('2', 'username', opts["netcom_user"])
+    tc.fv('2', 'password', opts["netcom_pass"])
     tc.submit()
     tc.follow("Send 25 gratis SMS")
-    tc.fv('2', 'gsmnumber', opts.netcom_user)
+    tc.fv('2', 'gsmnumber', opts["netcom_user"])
     tc.submit('submitChooseContact')
     tc.fv('2', 'message', msg)
     tc.submit('submitSendsms')
 def sendTelenor(opts, msg):
     # Login
     tc.go("https://telenormobil.no/norm/telenor/sms/send.do")
-    tc.fv("loginForm", "phonenumber", opts.telenor_user)
-    tc.fv("loginForm", "password", opts.telenor_pass)
+    tc.fv("loginForm", "phonenumber", opts["telenor_user"])
+    tc.fv("loginForm", "password", opts["telenor_pass"])
     tc.submit()
 
     # Send
-    tc.fv("smsSendSmsForm", "toAddress", opts.telenor_user)
+    tc.fv("smsSendSmsForm", "toAddress", opts["telenor_user"])
     tc.fv("smsSendSmsForm", "message", msg)
     tc.submit()
 
 def sendEmail(opts, msg):
     m = MIMEText(msg)
     m['Subject'] = "StudentWeb oppdatert"
-    m['From'] = opts.email
-    m['To'] = opts.email
-    s = smtplib.SMTP(opts.smtp)
+    m['From'] = opts["email"]
+    m['To'] = opts["email"]
+    s = smtplib.SMTP(opts["smtp"])
     s.sendmail(m['From'], m['To'], m.as_string())
     s.quit()
 
     # Hvis første gang programmet kjører,
     # har vi ingen gammel fil å sammenligne med,
     # lagrer karakterstate og returnerer.
-    if not os.path.exists(opts.statefile):
-        dump(ans, opts.statefile)
+    if not os.path.exists(opts["statefile"]):
+        dump(ans, opts["statefile"])
         return []
     elif olddata == []:
         # Laster state fra forrige kjøring
         try:
-            f = open(opts.statefile)
+            f = open(opts["statefile"])
             olddata = pickle.load(f)
             f.close()
         except IOError:
     
     # Vi har ny(e) karakter, send epost/sms med karakter.
     if len(new):
-        dump(ans, opts.statefile)
+        dump(ans, opts["statefile"])
         print "Nytt resultat fra StudentWeb."
 
         # Lager pen tekst med fagkode og karakterer:
         msg = "Nytt resultat fra StudentWeb: "
         msg += reduce(lambda x,y: x + y[0] + ": " + y[1] + ", ", new, '')[:-2]
-        print msg
-        if opts.email:
+        
+        if opts["email"]:
             print "Sender e-post"
             sendEmail(opts, msg)
 
-        if opts.netcom_user:
+        if opts["netcom_user"]:
             print "Sender SMS via NetCom"
             sendNetcom(opts, msg)
 
-        if opts.telenor_user:
+        if opts["telenor_user"]:
             print "Sender SMS via telenor"
             sendTelenor(opts, msg)
     return ans
     parser.add_option("-w", "--working-directory", type="string",
             dest="working_directory", default="/tmp",
             help="working directory in daemon mode [default: %default]")
+    parser.add_option("-c", "--config-file", type="string", dest="config_file",
+            default=None, help="read config from file [default: %default]")
 
     # Studweb relaterte opsjoner
-    group = OptionGroup(parser, "Studweb related options")
+    group = OptionGroup(parser, "Studweb related options", "WARNING: PIN" +\
+            " code and FNR should be set in the config file (see -c), since" +\
+            " these can appear in the process list of some systems.")
     group.add_option("-f", "--fnr", type="string", dest="fnr", default="",
             help="Birth number used to log into Studentweb")
     group.add_option("-p", "--pin", type="string", dest="pin", default="",
     
     # SMS, netcom
     group = OptionGroup(parser, "SMS notification using Netcom",
-            "The username must be your cell phone number")
+            "The username must be your cell phone number.\n" + "WARNING: " +\
+            "password and username should be set in the config file " +\
+            "(see -c) since these can appear in the process list of some " +\
+            "systems.")
     group.add_option("-n", "--netcom-user", type="string", dest="netcom_user",
             default="")
     group.add_option("-m", "--netcom-password", type="string",
 
     # SMS, Telenor
     group = OptionGroup(parser, "SMS notification using Telenor",
-            "The username must be your cell phone number")
+            "The username must be your cell phone number.\n" + "WARNING: " +\
+            "password and username should be set in the config file " +\
+            "(see -c) since these can appear in the process list of some " +\
+            "systems.")
     group.add_option("-t", "--telenor-user", type="string", dest="telenor_user",
             default="")
     group.add_option("-y", "--telenor-password", type="string",
             dest="telenor_pass", default="")
     parser.add_option_group(group)
-    (options, args) = parser.parse_args()
+    (pa_options, args) = parser.parse_args()
 
-    if options.daemon:
+    options = vars(pa_options)
+
+    if pa_options.config_file:
+        try:
+            opt_keys = vars(pa_options).keys()
+            f = open(pa_options.config_file)
+            for l in f:
+                if l[0] != '#' and len(l[:-1]):
+                    tmp = l[:-1].split(':')
+                    if tmp[0] in opt_keys:
+                        obj = eval("pa_options." + tmp[0])
+                        if type(obj) is str:
+                            options[tmp[0]] = tmp[1]
+                        else:
+                            options[tmp[0]] = eval(tmp[1])
+                    else:
+                        print "Error: key error in config file, '" + tmp[0] + \
+                            "' is not a key"
+            f.close()
+        except IOError:
+            print "Error: cannot open " + options.config_file
+            exit(1)
+
+        ## Penere en å dumpe alt i en dict? virker dog ikke...       
+        #try:
+        #    opt_keys = vars(options).keys()
+        #    f = open(options.config_file)
+        #    for l in f:
+        #        if l[0] != '#' and len(l[:-1]):
+        #            tmp = l[:-1].split(':')
+        #            if tmp[0] in opt_keys:
+        #                obj = eval("options." + tmp[0])
+        #                if type(obj) is str:
+        #                    obj = eval("'" + tmp[1] + "'")
+        #                else:
+        #                    obj = eval(tmp[1])
+        #            else:
+        #                print "Error: key error in config file, '" + tmp[0] + \
+        #                    "' is not a key"
+        #    f.close()
+        #except IOError:
+        #    print "Error: cannot open " + options.config_file
+        #    exit(1)
+
+    if options["daemon"]:
         try:
             import daemon
-            if options.daemon:
-                dae = daemon.DaemonContext()
-                dae.working_directory = options.working_directory
-                dae.umask = 0166
-                with dae:
-                    if options.interval:
-                        ans = []
-                        while True:
-                            ans = checkAndSend(options, ans)
-                            time.sleep(options.interval * 60)
-                    else:
-                        checkAndSend(options)
+            dae = daemon.DaemonContext()
+            dae.working_directory = options.working_directory
+            dae.umask = 0166
+            with dae:
+                if options["interval"]:
+                    ans = []
+                    while True:
+                        ans = checkAndSend(options, ans)
+                        time.sleep(options["interval"] * 60)
+                else:
+                    checkAndSend(options)
         except ImportError:
             print "Error: python-daemon is required"
     else:
-        if options.interval:
+        if options["interval"]:
             ans = []
             while True:
                 ans = checkAndSend(options, ans)
-                time.sleep(options.interval * 60)
+                time.sleep(options["interval"] * 60)
         else:
             checkAndSend(options)