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

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

Improved help description for script.

  • 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
36
37def make_optparser():
38    """Make command line option parser
39   
40    @rtype: optparse.OptionParser
41    @return: option parser instance
42    """
43    usage = """\
44usage: %prog [command] [options]
45
46commands:
47  logon        Retrieve credentials from a MyProxy service
48"""
49
50    op = optparse.OptionParser(usage=usage)
51
52    op.add_option('-o', '--out', dest='outfile',
53                  action='store', type='string',
54                  help='''\
55Set the file to store the retrieved creentials.
56If not specified credentials will be stored in X509_USER_PROXY environment
57variable.  To write the credential tostdout use -o -.
58''')
59   
60    op.add_option('-C', '--cadir', dest='cadir', 
61                  action='store', type='string',
62                  help='''\
63Set location of trusted certificates.  By default this is the X509_CERT_DIR
64environment variable or ~/.globus/certificates or /etc/grid-security.
65''')
66   
67    op.add_option('-s', '--pshost', dest='hostname',
68                  action='store', type='string',
69                  help='Set hostname of myproxy server')
70   
71    op.add_option('-p', '--psport', dest='port', 
72                  action='store', type='int',
73                  help='Set port of myproxy server')
74   
75    def set_lifetime(opt, opt_str, val, op):
76        """Callback to convert input requested proxy lifetime from hours to
77        seconds
78       
79        @type opt: optparse.Option
80        @param opt: Option instance that’s calling the callback
81        @type opt_str: string
82        @param opt_str: option string seen on the command-line that’s triggering
83        this callback
84        @type val: float
85        @param val: argument to this option seen on the command-line
86        @type op: optparse.OptionParser
87        @param op: OptionParser instance
88        """
89        op.values.lifetime = val * 60 * 60
90       
91    op.add_option('-t', '--proxy_lifetime', type='float', 
92                  action='callback', callback=set_lifetime,
93                  help='Set proxy certificate Lifetime (hours)')
94   
95    op.add_option('-S', '--stdin_pass', dest='stdin_pass',
96                  action='store_true',
97                  help='Read the password directly from stdin')
98   
99    #!TODO: What is the myproxy-logon equivilent of this option?
100    #op.add_option('-m', '--maxlifetime', dest='maxlifetime',
101    #              action='store', type='int',
102    #              help='Set proxy certificate Lifetime')
103    op.add_option('-b', '--bootstrap', dest='bootstrap',
104                  action='store_true',
105                  help='Download trusted CA certificates')
106   
107    op.add_option('-T', '--trustroots', dest='trustroots',
108                  action='store_true',
109                  help='Update trustroots')
110   
111    op.add_option('-l', '--username', dest='username',
112                  action='store', type='string',
113                  help=\
114        'Set username.  Defaults to "LOGNAME" environment variable setting.')
115
116    op.set_defaults(
117        outfile=None,
118        cadir=MyProxyClient.PROPERTY_DEFAULTS['caCertDir'],
119        hostname=MyProxyClient.PROPERTY_DEFAULTS['hostname'],
120        port=MyProxyClient.PROPERTY_DEFAULTS['port'],
121        lifetime=MyProxyClient.PROPERTY_DEFAULTS['proxyCertLifetime'],
122        bootstrap=False,
123        trustroots=False,
124        openid=None,
125        username=None,
126        stdin_pass=False,
127        )
128
129    return op
130
131
132def main(argv=sys.argv):
133    op = make_optparser()
134
135    logname = os.environ.get('LOGNAME')
136
137    nArgs = len(argv)
138    if nArgs < 2:
139        op.error('No command set')
140    else:
141        command = argv[1]
142   
143    # Catch example of just specifying --help or '-h'
144    if command in ['--help', '-h']:
145        argl = argv[1:2]
146        command = None
147       
148    elif command != 'logon':
149        op.error('Command %s not supported' % command)
150       
151    elif nArgs < 3:
152        op.error('No command options set')
153       
154    else:
155        argl = argv[2:]
156       
157    options = op.parse_args(argl)[0]
158
159    if options.outfile is None:
160        if MyProxyClient.X509_USER_PROXY_ENVVARNAME in os.environ:
161            options.outfile = os.environ[
162                                    MyProxyClient.X509_USER_PROXY_ENVVARNAME]
163        else:
164            op.error("Credential output file must be specified or %r set" %
165                     MyProxyClient.X509_USER_PROXY_ENVVARNAME)
166           
167    if options.username is None:
168        options.username = logname
169
170    if options.cadir:
171        cadir = options.cadir
172       
173    elif MyProxyClient.X509_CERT_DIR_ENVVARNAME in os.environ:
174        cadir = os.environ[MyProxyClient.X509_CERT_DIR_ENVVARNAME]
175       
176    elif logname == 'root':
177        cadir = MyProxyClient.ROOT_TRUSTROOT_DIR
178    else:
179        cadir = os.path.join(
180                        os.path.expanduser(MyProxyClient.USER_TRUSTROOT_DIR))
181
182    client_props = dict(caCertDir=cadir,
183                        hostname=options.hostname,
184                        port=options.port,
185                        proxyCertLifetime=options.lifetime,
186                        )
187
188    myproxy = MyProxyClient(**client_props)
189
190    do_logon(myproxy, options)     
191
192
193def do_logon(myproxy, options):
194    """Execute MyProxy logon command
195   
196    @type myproxy: myproxy.client.MyProxyClient
197    @param myproxy: MyProxy client object
198    @type options:
199    @param options: command line options
200    """
201    if options.stdin_pass:
202        #!TODO: Is this right to read just the first line of stdin?
203        password = sys.stdin.readline().rstrip()
204    else:
205        password = getpass.getpass('Enter password for user %r on MyProxy '
206                                   'server %r:'
207                                   % (options.username, options.hostname))
208
209    creds = myproxy.logon(options.username, password, 
210                          bootstrap=options.bootstrap,
211                          updateTrustRoots=options.trustroots)
212   
213    if options.outfile == '-':
214        fout = sys.stdout
215    else:
216        fout = open(options.outfile, 'w')
217   
218    for cred in creds:
219        fout.write(cred)
220   
221    if fout != sys.stdout:
222        fout.close()
223
224
225if __name__ == '__main__':
226    main()
Note: See TracBrowser for help on using the repository browser.