source: fedd/confirm_sshkey.py @ b501f63

version-3.02
Last change on this file since b501f63 was ff2d928, checked in by Ted Faber <faber@…>, 16 years ago

mysql error handling

  • Property mode set to 100755
File size: 1.9 KB
Line 
1#!/usr/local/bin/python
2
3import os, sys
4import MySQLdb
5from optparse import OptionParser
6
7
8class opt_parser(OptionParser):
9    def __init__(self):
10        OptionParser.__init__(self, usage="%prog [opts] (--help for details)",
11                version="0.1")
12        self.add_option('-u', '--user', dest='user', action='store',
13                default=None, help="User to confirm key of")
14        self.add_option('-f', '--keyfile', dest='keyfile', action='store',
15                default=None, help="file containing pubkey to confirm")
16        self.add_option('-k', '--key', dest='key',
17                default=None, action='store',
18                help='Key on the command line')
19        self.add_option('-q', '--quiet', dest='verbose', action='store_false', 
20                default=True, help="No output")
21        self.add_option('-C', dest='dummy', 
22                help="Compatibility option, no function")
23
24
25def read_keyfile(file):
26    """
27    Return the contents of file as a single line
28    """
29
30    f = open(file, "r")
31    key = ""
32    for line in f:
33        line = line.strip()
34        key += line
35    f.close()
36    return key
37
38
39query_template = """
40SELECT
41    uid
42FROM user_pubkeys
43WHERE uid = '%s' AND pubkey='%s'
44"""
45parser = opt_parser()
46opts, args = parser.parse_args()
47if len(args):
48    parser.error("Unlabeled option.  Did you forget to quote a key?")
49
50if opts.user: user = opts.user
51else: parser.error("--user is required")
52
53if opts.keyfile: 
54    try:
55        key = read_keyfile(opts.keyfile)
56    except IOError, e:
57        sys.exit('Cannot read keyfile %s: %s' % (opts.keyfile, e))
58elif opts.key: key = opts.key.strip()
59else: parser.error("--keyfile or --key is required")
60
61query = query_template % (user, key)
62
63try:
64    db = MySQLdb.connect(db='tbdb')
65except Exception, e:
66    if len(e.args) == 2:
67        num, str = e.args
68    else:
69        str = unicode(e)
70        num = -1
71    sys.exit("Cannot connect: %s (%d)" % (str, num))
72
73c = db.cursor()
74c.execute(query)
75
76if len(c.fetchall()) == 1:
77    if opts.verbose: print "Confirmed"
78    sys.exit(0)
79else:
80    if opts.verbose: print "No such key for %s" % user
81    sys.exit(1)
Note: See TracBrowser for help on using the repository browser.