summaryrefslogtreecommitdiff
path: root/scripts/print-mailcreds
blob: 0151c2c3cad9c65af7199153b3ce7804bab94d06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/python

import sys
import gtk
import gnomekeyring as gkey

class Keyring(object):
    def __init__(self, name, server, protocol):
        self._name = name
        self._server = server
        self._protocol = protocol
        self._keyring = gkey.get_default_keyring_sync()

    def has_credentials(self):
        try:
            attrs = {"server": self._server, "protocol": self._protocol}
            items = gkey.find_items_sync(gkey.ITEM_NETWORK_PASSWORD, attrs)
            return len(items) > 0
        except gkey.DeniedError:
            return False

    def get_credentials(self):
        attrs = {"server": self._server, "protocol": self._protocol}
        items = gkey.find_items_sync(gkey.ITEM_NETWORK_PASSWORD, attrs)
        return (items[0].attributes["user"], items[0].secret)

    def set_credentials(self, (user, pw)):
        attrs = {
                "user": user,
                "server": self._server,
                "protocol": self._protocol,
            }
        gkey.item_create_sync(gkey.get_default_keyring_sync(),
                gkey.ITEM_NETWORK_PASSWORD, self._name, attrs, pw, True)

want_url = False

if len(sys.argv) > 1:
    if sys.argv[1] == "--url":
        want_url = True
        sys.argv.remove("--url")

if len(sys.argv) < 4:
    print "Usage: print-mailcreds [--url] <service> <server> <protocol>"
    print "e.g. print-mailcreds offlineimap mail.banana.com imap"
    print "e.g. print-mailcreds --url mutt mail.banana.com smtp"
    sys.exit(1)

service = sys.argv[1]
server = sys.argv[2]
protocol = sys.argv[3]
#print "Connect"
keyring = Keyring(service, server, protocol)
#print "Check"
if not keyring.has_credentials():
    print "Failure!"
    sys.exit(2)
#print "Retrieve"
(username, password) = keyring.get_credentials()
#print "Done"
if want_url:
    if 'smtps' in protocol:
        print "%s://%s:%s@%s/" % (protocol, username, password, server)
    else:
        print "%s://%s:%s@%s:587/" % (protocol, username, password, server)
else:
    print "%s : %s" % (username, password)