source: TI12-security/trunk/MyProxyClient/myproxy/script.py @ 7554

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/MyProxyClient/myproxy/script.py@7554
Revision 7554, 6.7 KB checked in by pjkersha, 11 years ago (diff)

Preparing new release:

  • Important fix for PyOpenSSL based client authentication.
  • including new command line script 'myproxyclient' added by Stephen Pascoe
  • Property svn:keywords set to Id
Line 
1"""
2Lightweight command-line interface to MyProxyClient.
3
4Sub commands
5------------
6
7``myproxyclient logon`` a replacement for myproxy-logon.  It understands most of
8the same options and tries to behave the same with a few exceptions:
9
10  1. -C/--cadir allows you to override the CA directory
11  2. It will not write the credentials to /tmp.  You must either set
12     X509_USER_PROXY or specify the ``-o`` option.
13
14"""
15
16__author__ = "Stephen Pascoe"
17__date__ = "17/06/2010"
18__copyright__ = "(C) 2010 Science and Technology Facilities Council"
19__license__ = __license__ = """BSD - See LICENSE file in top-level directory
20
21For myproxy_logon see Access Grid Toolkit Public License (AGTPL)
22
23This product includes software developed by and/or derived from the Access
24Grid Project (http://www.accessgrid.org) to which the U.S. Government retains
25certain rights."""
26
27__revision__ = '$Id$'
28
29import sys
30import optparse
31import getpass
32import os
33
34from myproxy.client import MyProxyClient
35
36def make_optparser():
37    """Make command line option parser
38   
39    @rtype: optparse.OptionParser
40    @return: option parser instance
41    """
42    usage = """\
43usage: %prog [command] [options]
44
45commands:
46  logon        Retrieve credentials from a MyProxy service
47"""
48
49    op = optparse.OptionParser(usage=usage)
50
51    op.add_option('-o', '--out', dest='outfile',
52                  action='store', type='string',
53                  help='''\
54Set the file to store the retrieved creentials.
55If not specified credentials will be stored in X509_USER_PROXY environment
56variable.  To write the credential tostdout use -o -.
57''')
58   
59    op.add_option('-C', '--cadir', dest='cadir', 
60                  action='store', type='string',
61                  help='''\
62Set location of trusted certificates.  By default this is the X509_CERT_DIR
63environment variable or ~/.globus/certificates or /etc/grid-security.
64''')
65   
66    op.add_option('-s', '--pshost', dest='hostname',
67                  action='store', type='string',
68                  help='Set hostname of myproxy server')
69   
70    op.add_option('-p', '--psport', dest='port', 
71                  action='store', type='int',
72                  help='Set port of myproxy server')
73   
74    def set_lifetime(opt, opt_str, val, op):
75        """Callback to convert input requested proxy lifetime from hours to
76        seconds
77       
78        @type opt: optparse.Option
79        @param opt: Option instance that’s calling the callback
80        @type opt_str: string
81        @param opt_str: option string seen on the command-line that’s triggering
82        this callback
83        @type val: float
84        @param val: argument to this option seen on the command-line
85        @type op: optparse.OptionParser
86        @param op: OptionParser instance
87        """
88        op.values.lifetime = val * 60 * 60
89       
90    op.add_option('-t', '--proxy_lifetime', type='float', 
91                  action='callback', callback=set_lifetime,
92                  help='Set proxy certificate Lifetime (hours)')
93   
94    op.add_option('-S', '--stdin_pass', dest='stdin_pass',
95                  action='store_true',
96                  help='Read the password directly from stdin')
97   
98    #!TODO: What is the myproxy-logon equivilent of this option?
99    #op.add_option('-m', '--maxlifetime', dest='maxlifetime',
100    #              action='store', type='int',
101    #              help='Set proxy certificate Lifetime')
102    op.add_option('-b', '--bootstrap', dest='bootstrap',
103                  action='store_true',
104                  help='Download trusted CA certificates')
105   
106    op.add_option('-T', '--trustroots', dest='trustroots',
107                  action='store_true',
108                  help='Update trustroots')
109   
110    op.add_option('-l', '--username', dest='username',
111                  action='store', type='string',
112                  help='Set username')
113
114    op.set_defaults(
115        outfile=None,
116        cadir=MyProxyClient.PROPERTY_DEFAULTS['caCertDir'],
117        hostname=MyProxyClient.PROPERTY_DEFAULTS['hostname'],
118        port=MyProxyClient.PROPERTY_DEFAULTS['port'],
119        lifetime=MyProxyClient.PROPERTY_DEFAULTS['proxyCertLifetime'],
120        bootstrap=False,
121        trustroots=False,
122        openid=None,
123        username=None,
124        stdin_pass=False,
125        )
126
127    return op
128
129
130def main(argv=sys.argv):
131    op = make_optparser()
132
133    logname = os.environ.get('LOGNAME')
134
135    command = argv[1]
136   
137    # Catch example of just specifying --help or '-h'
138    if command in ['--help', '-h']:
139        argl = argv[1:2]
140        command = None
141    else:
142        argl = argv[2:]
143    options, args = op.parse_args(argl)
144
145    if options.outfile is None:
146        if MyProxyClient.X509_USER_PROXY_ENVVARNAME in os.environ:
147            options.outfile = os.environ[
148                                    MyProxyClient.X509_USER_PROXY_ENVVARNAME]
149        else:
150            op.error("Credential output file must be specified or %r set" %
151                     MyProxyClient.X509_USER_PROXY_ENVVARNAME)
152           
153    if options.username is None:
154        options.username = logname
155
156    if options.cadir:
157        cadir = options.cadir
158       
159    elif MyProxyClient.X509_CERT_DIR_ENVVARNAME in os.environ:
160        cadir = os.environ[MyProxyClient.X509_CERT_DIR_ENVVARNAME]
161       
162    elif logname == 'root':
163        cadir = MyProxyClient.ROOT_TRUSTROOT_DIR
164    else:
165        cadir = os.path.join(
166                        os.path.expanduser(MyProxyClient.USER_TRUSTROOT_DIR))
167
168    client_props = dict(caCertDir=cadir,
169                        hostname=options.hostname,
170                        port=options.port,
171                        proxyCertLifetime=options.lifetime,
172                        )
173
174    myproxy = MyProxyClient(**client_props)
175
176    if command == 'logon':
177        do_logon(myproxy, options)
178    else:
179        op.error('Command %s not supported' % command)
180
181
182def do_logon(myproxy, options):
183    """Execute MyProxy logon command
184   
185    @type myproxy: myproxy.client.MyProxyClient
186    @param myproxy: MyProxy client object
187    @type options:
188    @param options: command line options
189    """
190    if options.stdin_pass:
191        #!TODO: Is this right to read just the first line of stdin?
192        password = sys.stdin.readline().rstrip()
193    else:
194        password = getpass.getpass('Enter password for user %r on MyProxy '
195                                   'server %r:'
196                                   % (options.username, options.hostname))
197
198    creds = myproxy.logon(options.username, password, 
199                          bootstrap=options.bootstrap,
200                          updateTrustRoots=options.trustroots)
201   
202    if options.outfile == '-':
203        fout = sys.stdout
204    else:
205        fout = open(options.outfile, 'w')
206   
207    for cred in creds:
208        fout.write(cred)
209   
210    if fout != sys.stdout:
211        fout.close()
212
213
214if __name__ == '__main__':
215    main()
Note: See TracBrowser for help on using the repository browser.