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

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

New release 1.2.0:

  • tested and added fixes to command line script 'myproxyclient'
  • 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='Set username')
114
115    op.set_defaults(
116        outfile=None,
117        cadir=MyProxyClient.PROPERTY_DEFAULTS['caCertDir'],
118        hostname=MyProxyClient.PROPERTY_DEFAULTS['hostname'],
119        port=MyProxyClient.PROPERTY_DEFAULTS['port'],
120        lifetime=MyProxyClient.PROPERTY_DEFAULTS['proxyCertLifetime'],
121        bootstrap=False,
122        trustroots=False,
123        openid=None,
124        username=None,
125        stdin_pass=False,
126        )
127
128    return op
129
130
131def main(argv=sys.argv):
132    op = make_optparser()
133
134    logname = os.environ.get('LOGNAME')
135
136    nArgs = len(argv)
137    if nArgs < 2:
138        op.error('No command set')
139    else:
140        command = argv[1]
141   
142    # Catch example of just specifying --help or '-h'
143    if command in ['--help', '-h']:
144        argl = argv[1:2]
145        command = None
146       
147    elif command != 'logon':
148        op.error('Command %s not supported' % command)
149       
150    elif nArgs < 3:
151        op.error('No command options set')
152       
153    else:
154        argl = argv[2:]
155       
156    options = op.parse_args(argl)[0]
157
158    if options.outfile is None:
159        if MyProxyClient.X509_USER_PROXY_ENVVARNAME in os.environ:
160            options.outfile = os.environ[
161                                    MyProxyClient.X509_USER_PROXY_ENVVARNAME]
162        else:
163            op.error("Credential output file must be specified or %r set" %
164                     MyProxyClient.X509_USER_PROXY_ENVVARNAME)
165           
166    if options.username is None:
167        options.username = logname
168
169    if options.cadir:
170        cadir = options.cadir
171       
172    elif MyProxyClient.X509_CERT_DIR_ENVVARNAME in os.environ:
173        cadir = os.environ[MyProxyClient.X509_CERT_DIR_ENVVARNAME]
174       
175    elif logname == 'root':
176        cadir = MyProxyClient.ROOT_TRUSTROOT_DIR
177    else:
178        cadir = os.path.join(
179                        os.path.expanduser(MyProxyClient.USER_TRUSTROOT_DIR))
180
181    client_props = dict(caCertDir=cadir,
182                        hostname=options.hostname,
183                        port=options.port,
184                        proxyCertLifetime=options.lifetime,
185                        )
186
187    myproxy = MyProxyClient(**client_props)
188
189    do_logon(myproxy, options)     
190
191
192def do_logon(myproxy, options):
193    """Execute MyProxy logon command
194   
195    @type myproxy: myproxy.client.MyProxyClient
196    @param myproxy: MyProxy client object
197    @type options:
198    @param options: command line options
199    """
200    if options.stdin_pass:
201        #!TODO: Is this right to read just the first line of stdin?
202        password = sys.stdin.readline().rstrip()
203    else:
204        password = getpass.getpass('Enter password for user %r on MyProxy '
205                                   'server %r:'
206                                   % (options.username, options.hostname))
207
208    creds = myproxy.logon(options.username, password, 
209                          bootstrap=options.bootstrap,
210                          updateTrustRoots=options.trustroots)
211   
212    if options.outfile == '-':
213        fout = sys.stdout
214    else:
215        fout = open(options.outfile, 'w')
216   
217    for cred in creds:
218        fout.write(cred)
219   
220    if fout != sys.stdout:
221        fout.close()
222
223
224if __name__ == '__main__':
225    main()
Note: See TracBrowser for help on using the repository browser.