Modernize 'except' clauses

The 'as' syntax works from Python 2 on, and Python 3 will
drop the "comma" syntax.

Reviewed-By: Tomas Babej <tbabej@redhat.com>
This commit is contained in:
Petr Viktorin 2015-07-30 16:49:29 +02:00 committed by Tomas Babej
parent a651be3eec
commit 27dabb4528
118 changed files with 661 additions and 661 deletions

View File

@ -112,7 +112,7 @@ class ipaserver:
self.domain = lrealms[0].lower() self.domain = lrealms[0].lower()
return True return True
except LDAPError, err: except LDAPError as err:
#no good #no good
root_logger.error("Ldap Error: "+str(err)) root_logger.error("Ldap Error: "+str(err))
return False return False
@ -289,7 +289,7 @@ def main():
{'name':'empty', 'type':'empty'}] {'name':'empty', 'type':'empty'}]
try: try:
ldapconf.newConf("/etc/ldap.conf", opts) ldapconf.newConf("/etc/ldap.conf", opts)
except Exception, e: except Exception as e:
print "Configuration failed: " + str(e) print "Configuration failed: " + str(e)
return 1 return 1

View File

@ -435,7 +435,7 @@ class IPAChangeConf:
try: try:
try: try:
shutil.copy2(file, file+".ipabkp") shutil.copy2(file, file+".ipabkp")
except IOError, err: except IOError as err:
if err.errno == 2: if err.errno == 2:
# The orign file did not exist # The orign file did not exist
pass pass

View File

@ -90,10 +90,10 @@ while watcher_running:
try: try:
log.info('LDAP bind...') log.info('LDAP bind...')
ldap_connection.sasl_interactive_bind_s("", ipaldap.SASL_GSSAPI) ldap_connection.sasl_interactive_bind_s("", ipaldap.SASL_GSSAPI)
except ldap.INVALID_CREDENTIALS, e: except ldap.INVALID_CREDENTIALS as e:
log.exception('Login to LDAP server failed: %s', e) log.exception('Login to LDAP server failed: %s', e)
sys.exit(1) sys.exit(1)
except ldap.SERVER_DOWN, e: except ldap.SERVER_DOWN as e:
log.exception('LDAP server is down, going to retry: %s', e) log.exception('LDAP server is down, going to retry: %s', e)
time.sleep(5) time.sleep(5)
continue continue

View File

@ -213,7 +213,7 @@ def store_cert():
conn.add_entry(entry) conn.add_entry(entry)
except errors.EmptyModlist: except errors.EmptyModlist:
pass pass
except Exception, e: except Exception as e:
attempts += 1 attempts += 1
if attempts < 10: if attempts < 10:
syslog.syslog( syslog.syslog(
@ -365,7 +365,7 @@ def export_csr():
try: try:
with open(csr_file, 'wb') as f: with open(csr_file, 'wb') as f:
f.write(csr) f.write(csr)
except Exception, e: except Exception as e:
return (UNREACHABLE, "Failed to write %s: %s" % (csr_file, e)) return (UNREACHABLE, "Failed to write %s: %s" % (csr_file, e))
return (ISSUED, cert) return (ISSUED, cert)
@ -464,7 +464,7 @@ def main():
try: try:
sys.exit(main()) sys.exit(main())
except Exception, e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, traceback.format_exc()) syslog.syslog(syslog.LOG_ERR, traceback.format_exc())
print "Internal error" print "Internal error"
sys.exit(UNREACHABLE) sys.exit(UNREACHABLE)

View File

@ -49,7 +49,7 @@ def main():
try: try:
sys.exit(main()) sys.exit(main())
except Exception, e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, traceback.format_exc()) syslog.syslog(syslog.LOG_ERR, traceback.format_exc())
print "Internal error" print "Internal error"
sys.exit(3) sys.exit(3)

View File

@ -52,12 +52,12 @@ def bind(ldap_uri, base_dn, username, password):
try: try:
conn = IPAdmin(ldap_uri=ldap_uri) conn = IPAdmin(ldap_uri=ldap_uri)
conn.do_simple_bind(bind_dn, password) conn.do_simple_bind(bind_dn, password)
except (errors.ACIError, errors.DatabaseError, errors.NotFound), e: except (errors.ACIError, errors.DatabaseError, errors.NotFound) as e:
root_logger.error( root_logger.error(
'migration invalid credentials for %s: %s' % (bind_dn, e)) 'migration invalid credentials for %s: %s' % (bind_dn, e))
raise IOError( raise IOError(
errno.EPERM, 'Invalid LDAP credentials for user %s' % username) errno.EPERM, 'Invalid LDAP credentials for user %s' % username)
except Exception, e: except Exception as e:
root_logger.error('migration bind failed: %s' % e) root_logger.error('migration bind failed: %s' % e)
raise IOError(errno.EIO, 'Bind error') raise IOError(errno.EIO, 'Bind error')
finally: finally:

View File

@ -664,7 +664,7 @@ def main():
'style=', 'verbose', 'version', 'width=', 'exclude-file=', 'style=', 'verbose', 'version', 'width=', 'exclude-file=',
'docstrings', 'no-docstrings', 'docstrings', 'no-docstrings',
]) ])
except getopt.error, msg: except getopt.error as msg:
usage(1, msg) usage(1, msg)
# for holding option values # for holding option values
@ -787,7 +787,7 @@ def main():
eater.set_filename(filename) eater.set_filename(filename)
try: try:
tokenize.tokenize(fp.readline, eater) tokenize.tokenize(fp.readline, eater)
except tokenize.TokenError, e: except tokenize.TokenError as e:
print >> sys.stderr, '%s: %s, line %d, column %d' % ( print >> sys.stderr, '%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1]) e[0], filename, e[1][0], e[1][1])
finally: finally:

View File

@ -56,7 +56,7 @@ def _main():
syslog.LOG_NOTICE, "Stopping %s" % dogtag_service.service_name) syslog.LOG_NOTICE, "Stopping %s" % dogtag_service.service_name)
try: try:
dogtag_service.stop(dogtag_instance) dogtag_service.stop(dogtag_instance)
except Exception, e: except Exception as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, syslog.LOG_ERR,
"Cannot stop %s: %s" % (dogtag_service.service_name, e)) "Cannot stop %s: %s" % (dogtag_service.service_name, e))
@ -142,7 +142,7 @@ def _main():
try: try:
conn = ldap2(api) conn = ldap2(api)
conn.connect(ccache=ccache_filename) conn.connect(ccache=ccache_filename)
except Exception, e: except Exception as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, "Failed to connect to LDAP: %s" % e) syslog.LOG_ERR, "Failed to connect to LDAP: %s" % e)
else: else:
@ -152,7 +152,7 @@ def _main():
certstore.update_ca_cert(conn, api.env.basedn, cert) certstore.update_ca_cert(conn, api.env.basedn, cert)
except errors.EmptyModlist: except errors.EmptyModlist:
pass pass
except Exception, e: except Exception as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, syslog.LOG_ERR,
"Updating CA certificate failed: %s" % e) "Updating CA certificate failed: %s" % e)
@ -163,7 +163,7 @@ def _main():
ca_certs = certstore.get_ca_certs( ca_certs = certstore.get_ca_certs(
conn, api.env.basedn, api.env.realm, False, conn, api.env.basedn, api.env.realm, False,
filter_subject=ca_issuer) filter_subject=ca_issuer)
except Exception, e: except Exception as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, syslog.LOG_ERR,
"Failed to get external CA certificates from LDAP: " "Failed to get external CA certificates from LDAP: "
@ -185,7 +185,7 @@ def _main():
try: try:
db.add_cert(ca_cert, nick, flags) db.add_cert(ca_cert, nick, flags)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, syslog.LOG_ERR,
"Failed to add certificate %s" % ca_nick) "Failed to add certificate %s" % ca_nick)
@ -204,7 +204,7 @@ def _main():
'Starting %s' % dogtag_service.service_name) 'Starting %s' % dogtag_service.service_name)
try: try:
dogtag_service.start(dogtag_instance) dogtag_service.start(dogtag_instance)
except Exception, e: except Exception as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, syslog.LOG_ERR,
"Cannot start %s: %s" % (dogtag_service.service_name, e)) "Cannot start %s: %s" % (dogtag_service.service_name, e))

View File

@ -67,7 +67,7 @@ def _main():
syslog.syslog(syslog.LOG_NOTICE, "Restarting httpd") syslog.syslog(syslog.LOG_NOTICE, "Restarting httpd")
try: try:
services.knownservices.httpd.restart() services.knownservices.httpd.restart()
except Exception, e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, "Cannot restart httpd: %s" % e) syslog.syslog(syslog.LOG_ERR, "Cannot restart httpd: %s" % e)
else: else:
syslog.syslog(syslog.LOG_NOTICE, "Restarted httpd") syslog.syslog(syslog.LOG_NOTICE, "Restarted httpd")

View File

@ -40,7 +40,7 @@ def _main():
try: try:
services.knownservices.dirsrv.restart(instance) services.knownservices.dirsrv.restart(instance)
except Exception, e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, "Cannot restart dirsrv (instance: '%s'): %s" % (instance, str(e))) syslog.syslog(syslog.LOG_ERR, "Cannot restart dirsrv (instance: '%s'): %s" % (instance, str(e)))

View File

@ -30,7 +30,7 @@ def _main():
try: try:
services.knownservices.httpd.restart() services.knownservices.httpd.restart()
except Exception, e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, "Cannot restart httpd: %s" % str(e)) syslog.syslog(syslog.LOG_ERR, "Cannot restart httpd: %s" % str(e))

View File

@ -41,7 +41,7 @@ def main():
syslog.syslog(syslog.LOG_NOTICE, "Stopping %s" % dogtag_service.service_name) syslog.syslog(syslog.LOG_NOTICE, "Stopping %s" % dogtag_service.service_name)
try: try:
dogtag_service.stop(dogtag_instance) dogtag_service.stop(dogtag_instance)
except Exception, e: except Exception as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, "Cannot stop %s: %s" % (dogtag_service.service_name, e)) syslog.LOG_ERR, "Cannot stop %s: %s" % (dogtag_service.service_name, e))
else: else:

View File

@ -82,7 +82,7 @@ def add_ca_schema():
continue continue
try: try:
shutil.copyfile(source_fname, target_fname) shutil.copyfile(source_fname, target_fname)
except IOError, e: except IOError as e:
root_logger.warning('Could not install %s: %s', target_fname, e) root_logger.warning('Could not install %s: %s', target_fname, e)
else: else:
root_logger.info('Installed %s', target_fname) root_logger.info('Installed %s', target_fname)

View File

@ -38,7 +38,7 @@ env._finalize_core(**dict(DEFAULT_CONFIG))
api.bootstrap(context='server', debug=env.debug, log=None) api.bootstrap(context='server', debug=env.debug, log=None)
try: try:
api.finalize() api.finalize()
except StandardError, e: except StandardError as e:
api.log.error('Failed to start IPA: %s' % e) api.log.error('Failed to start IPA: %s' % e)
else: else:
api.log.info('*** PROCESS START ***') api.log.info('*** PROCESS START ***')

View File

@ -194,7 +194,7 @@ def set_and_check_netbios_name(netbios_name, unattended):
def ensure_admin_kinit(admin_name, admin_password): def ensure_admin_kinit(admin_name, admin_password):
try: try:
ipautil.run(['kinit', admin_name], stdin=admin_password+'\n') ipautil.run(['kinit', admin_name], stdin=admin_password+'\n')
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
print "There was error to automatically re-kinit your admin user ticket." print "There was error to automatically re-kinit your admin user ticket."
return False return False
return True return True
@ -305,14 +305,14 @@ def main():
ctx = krbV.default_context() ctx = krbV.default_context()
ccache = ctx.default_ccache() ccache = ctx.default_ccache()
principal = ccache.principal() principal = ccache.principal()
except krbV.Krb5Error, e: except krbV.Krb5Error as e:
sys.exit("Must have Kerberos credentials to setup AD trusts on server") sys.exit("Must have Kerberos credentials to setup AD trusts on server")
try: try:
api.Backend.ldap2.connect(ccache) api.Backend.ldap2.connect(ccache)
except errors.ACIError, e: except errors.ACIError as e:
sys.exit("Outdated Kerberos credentials. Use kdestroy and kinit to update your ticket") sys.exit("Outdated Kerberos credentials. Use kdestroy and kinit to update your ticket")
except errors.DatabaseError, e: except errors.DatabaseError as e:
sys.exit("Cannot connect to the LDAP database. Please check if IPA is running") sys.exit("Cannot connect to the LDAP database. Please check if IPA is running")
try: try:
@ -321,9 +321,9 @@ def main():
if not (user['uid'][0] in group['member_user'] and if not (user['uid'][0] in group['member_user'] and
group['cn'][0] in user['memberof_group']): group['cn'][0] in user['memberof_group']):
raise errors.RequirementError(name='admins group membership') raise errors.RequirementError(name='admins group membership')
except errors.RequirementError, e: except errors.RequirementError as e:
sys.exit("Must have administrative privileges to setup AD trusts on server") sys.exit("Must have administrative privileges to setup AD trusts on server")
except Exception, e: except Exception as e:
sys.exit("Unrecognized error during check of admin rights: %s" % (str(e))) sys.exit("Unrecognized error during check of admin rights: %s" % (str(e)))
(netbios_name, reset_netbios_name) = \ (netbios_name, reset_netbios_name) = \
@ -344,7 +344,7 @@ def main():
except errors.NotFound: except errors.NotFound:
# All objects have SIDs assigned # All objects have SIDs assigned
pass pass
except (errors.DatabaseError, errors.NetworkError), e: except (errors.DatabaseError, errors.NetworkError) as e:
print "Could not retrieve a list of objects that need a SID identifier assigned:" print "Could not retrieve a list of objects that need a SID identifier assigned:"
print unicode(e) print unicode(e)
else: else:
@ -400,7 +400,7 @@ def main():
base_dn=masters_dn, attrs_list=['cn'], scope=ldap.SCOPE_ONELEVEL) base_dn=masters_dn, attrs_list=['cn'], scope=ldap.SCOPE_ONELEVEL)
except errors.NotFound: except errors.NotFound:
pass pass
except (errors.DatabaseError, errors.NetworkError), e: except (errors.DatabaseError, errors.NetworkError) as e:
print "Could not retrieve a list of existing IPA masters:" print "Could not retrieve a list of existing IPA masters:"
print unicode(e) print unicode(e)
@ -409,7 +409,7 @@ def main():
base_dn=agents_dn, attrs_list=['member'], scope=ldap.SCOPE_BASE) base_dn=agents_dn, attrs_list=['member'], scope=ldap.SCOPE_BASE)
except errors.NotFound: except errors.NotFound:
pass pass
except (errors.DatabaseError, errors.NetworkError), e: except (errors.DatabaseError, errors.NetworkError) as e:
print "Could not retrieve a list of adtrust agents:" print "Could not retrieve a list of adtrust agents:"
print unicode(e) print unicode(e)

View File

@ -111,9 +111,9 @@ def main():
conn.connect( conn.connect(
bind_dn=DN(('cn', 'directory manager')), bind_pw=dirman_password bind_dn=DN(('cn', 'directory manager')), bind_pw=dirman_password
) )
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
sys.exit("An error occurred while connecting to the server.\n%s\n" % str(lde)) sys.exit("An error occurred while connecting to the server.\n%s\n" % str(lde))
except errors.ACIError, e: except errors.ACIError as e:
sys.exit("Authentication failed: %s" % e.info) sys.exit("Authentication failed: %s" % e.info)
if args[0] == "status": if args[0] == "status":
@ -124,7 +124,7 @@ def main():
print "Plugin Enabled" print "Plugin Enabled"
else: else:
print "Plugin Disabled" print "Plugin Disabled"
except errors.LDAPError, lde: except errors.LDAPError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
@ -146,7 +146,7 @@ def main():
else: else:
entry['nsslapd-pluginenabled'] = ['on'] entry['nsslapd-pluginenabled'] = ['on']
conn.update_entry(entry) conn.update_entry(entry)
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
retval = 1 retval = 1
@ -160,7 +160,7 @@ def main():
print >>sys.stderr, "The NIS plugin is configured, cannot disable compatibility." print >>sys.stderr, "The NIS plugin is configured, cannot disable compatibility."
print >>sys.stderr, "Run 'ipa-nis-manage disable' first." print >>sys.stderr, "Run 'ipa-nis-manage disable' first."
retval = 2 retval = 2
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
retval = 1 retval = 1
@ -177,11 +177,11 @@ def main():
entry['nsslapd-pluginenabled'] = ['off'] entry['nsslapd-pluginenabled'] = ['off']
conn.update_entry(entry) conn.update_entry(entry)
except errors.DatabaseError, dbe: except errors.DatabaseError as dbe:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print dbe print dbe
retval = 1 retval = 1
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
retval = 1 retval = 1

View File

@ -105,7 +105,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
except errors.NotFound: except errors.NotFound:
peers[ent.single_value['cn']] = ['CA not configured', ''] peers[ent.single_value['cn']] = ['CA not configured', '']
except Exception, e: except Exception as e:
sys.exit( sys.exit(
"Failed to get data from '%s' while trying to list replicas: %s" % "Failed to get data from '%s' while trying to list replicas: %s" %
(host, e)) (host, e))
@ -119,7 +119,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
try: try:
repl = replication.get_cs_replication_manager(realm, replica, dirman_passwd) repl = replication.get_cs_replication_manager(realm, replica, dirman_passwd)
except Exception, e: except Exception as e:
sys.exit(str(e)) sys.exit(str(e))
entries = repl.find_replication_agreements() entries = repl.find_replication_agreements()
@ -162,9 +162,9 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
repl1.hostnames = [replica1, replica2] repl1.hostnames = [replica1, replica2]
except errors.NetworkError, e: except errors.NetworkError as e:
sys.exit("Unable to connect to %s: %s" % (replica1, e)) sys.exit("Unable to connect to %s: %s" % (replica1, e))
except Exception, e: except Exception as e:
sys.exit("Failed to get data from '%s': %s" % (replica1, e)) sys.exit("Failed to get data from '%s': %s" % (replica1, e))
try: try:
@ -201,7 +201,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
print "'%s' has no replication agreement for '%s'" % (replica2, replica1) print "'%s' has no replication agreement for '%s'" % (replica2, replica1)
if not force: if not force:
return return
except Exception, e: except Exception as e:
print "Failed to get data from '%s': %s" % (replica2, e) print "Failed to get data from '%s': %s" % (replica2, e)
if not force: if not force:
sys.exit(1) sys.exit(1)
@ -211,7 +211,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
try: try:
repl2.delete_agreement(replica1, replica2_dn) repl2.delete_agreement(replica1, replica2_dn)
repl2.delete_referral(replica1, repl1.port) repl2.delete_referral(replica1, repl1.port)
except Exception, e: except Exception as e:
print "Unable to remove agreement on %s: %s" % (replica2, e) print "Unable to remove agreement on %s: %s" % (replica2, e)
failed = True failed = True
@ -239,7 +239,7 @@ def del_master(realm, hostname, options):
try: try:
thisrepl = replication.get_cs_replication_manager(realm, options.host, thisrepl = replication.get_cs_replication_manager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
except Exception, e: except Exception as e:
sys.exit("Failed to connect to server %s: %s" % (options.host, e)) sys.exit("Failed to connect to server %s: %s" % (options.host, e))
# 2. Ensure we have an agreement with the master # 2. Ensure we have an agreement with the master
@ -250,7 +250,7 @@ def del_master(realm, hostname, options):
try: try:
delrepl = replication.get_cs_replication_manager(realm, hostname, delrepl = replication.get_cs_replication_manager(realm, hostname,
options.dirman_passwd) options.dirman_passwd)
except Exception, e: except Exception as e:
if not options.force: if not options.force:
print "Unable to delete replica %s: %s" % (hostname, e) print "Unable to delete replica %s: %s" % (hostname, e)
sys.exit(1) sys.exit(1)
@ -271,7 +271,7 @@ def del_master(realm, hostname, options):
for r in replica_names: for r in replica_names:
try: try:
del_link(realm, r, hostname, options.dirman_passwd, force=True) del_link(realm, r, hostname, options.dirman_passwd, force=True)
except Exception, e: except Exception as e:
sys.exit("There were issues removing a connection: %s" % e) sys.exit("There were issues removing a connection: %s" % e)
# 6. Pick CA renewal master # 6. Pick CA renewal master
@ -287,7 +287,7 @@ def del_master(realm, hostname, options):
bind_pw=options.dirman_passwd) bind_pw=options.dirman_passwd)
bind = bindinstance.BindInstance() bind = bindinstance.BindInstance()
bind.remove_ipa_ca_dns_records(hostname, realm.lower()) bind.remove_ipa_ca_dns_records(hostname, realm.lower())
except Exception, e: except Exception as e:
print "Failed to cleanup %s DNS entries: %s" % (hostname, e) print "Failed to cleanup %s DNS entries: %s" % (hostname, e)
print "You may need to manually remove them from the tree" print "You may need to manually remove them from the tree"
@ -295,7 +295,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
try: try:
repl2 = replication.get_cs_replication_manager(realm, replica2, repl2 = replication.get_cs_replication_manager(realm, replica2,
dirman_passwd) dirman_passwd)
except Exception, e: except Exception as e:
sys.exit(str(e)) sys.exit(str(e))
try: try:
conn = ipaldap.IPAdmin(replica2, 636, cacert=CACERT) conn = ipaldap.IPAdmin(replica2, 636, cacert=CACERT)
@ -307,9 +307,9 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
conn.unbind() conn.unbind()
except errors.NotFound: except errors.NotFound:
sys.exit('%s does not have a CA configured.' % replica2) sys.exit('%s does not have a CA configured.' % replica2)
except errors.NetworkError, e: except errors.NetworkError as e:
sys.exit("Unable to connect to %s: %s" % (ipautil.format_netloc(replica2, 636), str(e))) sys.exit("Unable to connect to %s: %s" % (ipautil.format_netloc(replica2, 636), str(e)))
except Exception, e: except Exception as e:
sys.exit("Failed to get data while trying to bind to '%s': %s" % (replica1, str(e))) sys.exit("Failed to get data while trying to bind to '%s': %s" % (replica1, str(e)))
try: try:
@ -323,9 +323,9 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
except errors.NotFound: except errors.NotFound:
sys.exit("Cannot find replica '%s'" % replica1) sys.exit("Cannot find replica '%s'" % replica1)
except errors.NetworkError, e: except errors.NetworkError as e:
sys.exit("Unable to connect to %s: %s" % (replica1, e)) sys.exit("Unable to connect to %s: %s" % (replica1, e))
except Exception, e: except Exception as e:
sys.exit( sys.exit(
"Failed to get data from '%s' while trying to get current " "Failed to get data from '%s' while trying to get current "
"agreements: %s" % (replica1, e)) "agreements: %s" % (replica1, e))
@ -347,7 +347,7 @@ def re_initialize(realm, options):
options.dirman_passwd) options.dirman_passwd)
thisrepl = replication.get_cs_replication_manager(realm, thishost, thisrepl = replication.get_cs_replication_manager(realm, thishost,
options.dirman_passwd) options.dirman_passwd)
except Exception, e: except Exception as e:
sys.exit(str(e)) sys.exit(str(e))
filter = repl.get_agreement_filter(host=thishost) filter = repl.get_agreement_filter(host=thishost)
@ -373,7 +373,7 @@ def force_sync(realm, thishost, fromhost, dirman_passwd):
repl = replication.get_cs_replication_manager(realm, fromhost, repl = replication.get_cs_replication_manager(realm, fromhost,
dirman_passwd) dirman_passwd)
repl.force_sync(repl.conn, thishost) repl.force_sync(repl.conn, thishost)
except Exception, e: except Exception as e:
sys.exit(str(e)) sys.exit(str(e))
def set_renewal_master(realm, replica): def set_renewal_master(realm, replica):
@ -386,7 +386,7 @@ def set_renewal_master(realm, replica):
try: try:
ca.set_renewal_master(replica) ca.set_renewal_master(replica)
except Exception, e: except Exception as e:
sys.exit("Failed to set renewal master to %s: %s" % (replica, e)) sys.exit("Failed to set renewal master to %s: %s" % (replica, e))
print "%s is now the renewal master" % replica print "%s is now the renewal master" % replica
@ -465,7 +465,7 @@ try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit(1) sys.exit(1)
except SystemExit, e: except SystemExit as e:
sys.exit(e) sys.exit(e)
except Exception, e: except Exception as e:
sys.exit("unexpected error: %s" % e) sys.exit("unexpected error: %s" % e)

View File

@ -102,7 +102,7 @@ def main():
conn.do_simple_bind(bindpw=dirman_password) conn.do_simple_bind(bindpw=dirman_password)
except errors.ACIError: except errors.ACIError:
sys.exit("Invalid credentials") sys.exit("Invalid credentials")
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
sys.exit("An error occurred while connecting to the server.\n%s\n" % sys.exit("An error occurred while connecting to the server.\n%s\n" %
str(lde)) str(lde))
@ -112,7 +112,7 @@ def main():
try: try:
entries = conn.get_entries( entries = conn.get_entries(
managed_entry_definitions_dn, conn.SCOPE_SUBTREE, filter) managed_entry_definitions_dn, conn.SCOPE_SUBTREE, filter)
except Exception, e: except Exception as e:
root_logger.debug("Search for managed entries failed: %s" % str(e)) root_logger.debug("Search for managed entries failed: %s" % str(e))
sys.exit("Unable to find managed entries at %s" % managed_entry_definitions_dn) sys.exit("Unable to find managed entries at %s" % managed_entry_definitions_dn)
managed_entries = [entry.single_value['cn'] for entry in entries] managed_entries = [entry.single_value['cn'] for entry in entries]
@ -140,7 +140,7 @@ def main():
sys.exit("%s is not a valid Managed Entry" % def_dn) sys.exit("%s is not a valid Managed Entry" % def_dn)
except errors.NotFound: except errors.NotFound:
sys.exit("%s is not a valid Managed Entry" % def_dn) sys.exit("%s is not a valid Managed Entry" % def_dn)
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
@ -166,7 +166,7 @@ def main():
retval = 0 retval = 0
except errors.NotFound: except errors.NotFound:
print "Enabling Plugin" print "Enabling Plugin"
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
retval = 1 retval = 1
@ -190,11 +190,11 @@ def main():
except errors.NotFound: except errors.NotFound:
print "Plugin is already disabled" print "Plugin is already disabled"
retval = 2 retval = 2
except errors.DatabaseError, dbe: except errors.DatabaseError as dbe:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print dbe print dbe
retval = 1 retval = 1
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
retval = 1 retval = 1

View File

@ -124,7 +124,7 @@ def main():
conn.connect( conn.connect(
bind_dn=DN(('cn', 'directory manager')), bind_pw=dirman_password bind_dn=DN(('cn', 'directory manager')), bind_pw=dirman_password
) )
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
sys.exit("An error occurred while connecting to the server: %s" % str(lde)) sys.exit("An error occurred while connecting to the server: %s" % str(lde))
except errors.AuthorizationError: except errors.AuthorizationError:
sys.exit("Incorrect password") sys.exit("Incorrect password")
@ -136,7 +136,7 @@ def main():
entry = None entry = None
try: try:
entry = get_entry(nis_config_dn, conn) entry = get_entry(nis_config_dn, conn)
except errors.ExecutionError, lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
retval = 1 retval = 1
@ -146,13 +146,13 @@ def main():
portmap = services.knownservices.portmap portmap = services.knownservices.portmap
portmap.enable() portmap.enable()
servicemsg = portmap.service_name servicemsg = portmap.service_name
except ipautil.CalledProcessError, cpe: except ipautil.CalledProcessError as cpe:
if cpe.returncode == 1: if cpe.returncode == 1:
try: try:
rpcbind = services.knownservices.rpcbind rpcbind = services.knownservices.rpcbind
rpcbind.enable() rpcbind.enable()
servicemsg = rpcbind.service_name servicemsg = rpcbind.service_name
except ipautil.CalledProcessError, cpe: except ipautil.CalledProcessError as cpe:
print "Unable to enable either %s or %s" % (portmap.service_name, rpcbind.service_name) print "Unable to enable either %s or %s" % (portmap.service_name, rpcbind.service_name)
retval = 3 retval = 3
@ -180,7 +180,7 @@ def main():
except (errors.NotFound, errors.EmptyModlist): except (errors.NotFound, errors.EmptyModlist):
print "Plugin is already disabled" print "Plugin is already disabled"
retval = 2 retval = 2
except errors.LDAPError, lde: except errors.LDAPError as lde:
print "An error occurred while talking to the server." print "An error occurred while talking to the server."
print lde print lde
retval = 1 retval = 1

View File

@ -255,7 +255,7 @@ class PortResponder(threading.Thread):
responder_data="FreeIPA") responder_data="FreeIPA")
except socket.timeout: except socket.timeout:
pass pass
except socket.error, e: except socket.error as e:
if e.errno == errno.EADDRINUSE: if e.errno == errno.EADDRINUSE:
time.sleep(1) time.sleep(1)
else: else:
@ -419,12 +419,12 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
try: try:
sys.exit(main()) sys.exit(main())
except SystemExit, e: except SystemExit as e:
sys.exit(e) sys.exit(e)
except KeyboardInterrupt: except KeyboardInterrupt:
print_info("\nCleaning up...") print_info("\nCleaning up...")
sys.exit(1) sys.exit(1)
except RuntimeError, e: except RuntimeError as e:
sys.exit(e) sys.exit(e)
finally: finally:
clean_responders(RESPONDERS) clean_responders(RESPONDERS)

View File

@ -158,7 +158,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose, nolookup=False):
conn.do_simple_bind(bindpw=dirman_passwd) conn.do_simple_bind(bindpw=dirman_passwd)
else: else:
conn.do_sasl_gssapi_bind() conn.do_sasl_gssapi_bind()
except Exception, e: except Exception as e:
print "Failed to connect to host '%s': %s" % (host, str(e)) print "Failed to connect to host '%s': %s" % (host, str(e))
return return
@ -212,7 +212,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose, nolookup=False):
dirman_passwd) dirman_passwd)
entries = repl.find_replication_agreements() entries = repl.find_replication_agreements()
ent_type = 'replica' ent_type = 'replica'
except Exception, e: except Exception as e:
print "Failed to get data from '%s': %s" % (replica, e) print "Failed to get data from '%s': %s" % (replica, e)
return return
@ -258,7 +258,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
else: else:
print "'%s' has no replication agreement for '%s'" % (replica1, replica2) print "'%s' has no replication agreement for '%s'" % (replica1, replica2)
return False return False
except Exception, e: except Exception as e:
print "Failed to determine agreement type for '%s': %s" % (replica2, e) print "Failed to determine agreement type for '%s': %s" % (replica2, e)
if type1 == replication.IPA_REPLICA and managed_topology: if type1 == replication.IPA_REPLICA and managed_topology:
@ -284,7 +284,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
print "'%s' has no replication agreement for '%s'" % (replica2, replica1) print "'%s' has no replication agreement for '%s'" % (replica2, replica1)
if not force: if not force:
return False return False
except Exception, e: except Exception as e:
print "Failed to get list of agreements from '%s': %s" % (replica2, e) print "Failed to get list of agreements from '%s': %s" % (replica2, e)
if not force: if not force:
return False return False
@ -308,7 +308,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
repl2.delete_agreement(replica1) repl2.delete_agreement(replica1)
repl2.delete_referral(replica1) repl2.delete_referral(replica1)
repl2.set_readonly(readonly=False) repl2.set_readonly(readonly=False)
except Exception, e: except Exception as e:
print "Unable to remove agreement on %s: %s" % (replica2, e) print "Unable to remove agreement on %s: %s" % (replica2, e)
failed = True failed = True
@ -335,7 +335,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
entries.sort(key=lambda x: len(x.dn), reverse=True) entries.sort(key=lambda x: len(x.dn), reverse=True)
for entry in entries: for entry in entries:
repl1.conn.delete_entry(entry) repl1.conn.delete_entry(entry)
except Exception, e: except Exception as e:
print "Error deleting winsync replica shared info: %s" % e print "Error deleting winsync replica shared info: %s" % e
print "Deleted replication agreement from '%s' to '%s'" % (replica1, replica2) print "Deleted replication agreement from '%s' to '%s'" % (replica1, replica2)
@ -352,7 +352,7 @@ def get_ruv(realm, host, dirman_passwd, nolookup=False):
try: try:
thisrepl = replication.ReplicationManager(realm, host, dirman_passwd) thisrepl = replication.ReplicationManager(realm, host, dirman_passwd)
except Exception, e: except Exception as e:
print "Failed to connect to server %s: %s" % (host, e) print "Failed to connect to server %s: %s" % (host, e)
sys.exit(1) sys.exit(1)
@ -687,7 +687,7 @@ def cleanup_server_dns_entries(realm, hostname, suffix, options):
keysyncd = dnskeysyncinstance.DNSKeySyncInstance() keysyncd = dnskeysyncinstance.DNSKeySyncInstance()
keysyncd.remove_replica_public_keys(hostname) keysyncd.remove_replica_public_keys(hostname)
except Exception, e: except Exception as e:
print "Failed to cleanup %s DNS entries: %s" % (hostname, e) print "Failed to cleanup %s DNS entries: %s" % (hostname, e)
print "You may need to manually remove them from the tree" print "You may need to manually remove them from the tree"
@ -740,7 +740,7 @@ def del_master_managed(realm, hostname, options):
# 6. Cleanup # 6. Cleanup
try: try:
thisrepl.replica_cleanup(hostname, realm, force=True) thisrepl.replica_cleanup(hostname, realm, force=True)
except Exception, e: except Exception as e:
print "Failed to cleanup %s entries: %s" % (hostname, e) print "Failed to cleanup %s entries: %s" % (hostname, e)
print "You may need to manually remove them from the tree" print "You may need to manually remove them from the tree"
@ -815,7 +815,7 @@ def del_master_direct(realm, hostname, options):
try: try:
thisrepl = replication.ReplicationManager(realm, options.host, thisrepl = replication.ReplicationManager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
except Exception, e: except Exception as e:
print "Failed to connect to server %s: %s" % (options.host, e) print "Failed to connect to server %s: %s" % (options.host, e)
sys.exit(1) sys.exit(1)
@ -844,7 +844,7 @@ def del_master_direct(realm, hostname, options):
winsync = False winsync = False
try: try:
delrepl = replication.ReplicationManager(realm, hostname, options.dirman_passwd) delrepl = replication.ReplicationManager(realm, hostname, options.dirman_passwd)
except Exception, e: except Exception as e:
print "Connection to '%s' failed: %s" % (hostname, e) print "Connection to '%s' failed: %s" % (hostname, e)
if not options.force: if not options.force:
print "Unable to delete replica '%s'" % hostname print "Unable to delete replica '%s'" % hostname
@ -888,7 +888,7 @@ def del_master_direct(realm, hostname, options):
if delrepl and not winsync: if delrepl and not winsync:
try: try:
masters = api.Command.server_find('', sizelimit=0)['result'] masters = api.Command.server_find('', sizelimit=0)['result']
except Exception, e: except Exception as e:
masters = [] masters = []
print "Failed to read masters data from '%s': %s" % ( print "Failed to read masters data from '%s': %s" % (
delrepl.hostname, e) delrepl.hostname, e)
@ -923,7 +923,7 @@ def del_master_direct(realm, hostname, options):
try: try:
if not del_link(realm, r, hostname, options.dirman_passwd, force=True): if not del_link(realm, r, hostname, options.dirman_passwd, force=True):
print "Unable to remove replication agreement for %s from %s." % (hostname, r) print "Unable to remove replication agreement for %s from %s." % (hostname, r)
except Exception, e: except Exception as e:
print ("There were issues removing a connection for %s " print ("There were issues removing a connection for %s "
"from %s: %s" % (hostname, r, e)) "from %s: %s" % (hostname, r, e))
@ -937,7 +937,7 @@ def del_master_direct(realm, hostname, options):
# 6. Finally clean up the removed replica common entries. # 6. Finally clean up the removed replica common entries.
try: try:
thisrepl.replica_cleanup(hostname, realm, force=True) thisrepl.replica_cleanup(hostname, realm, force=True)
except Exception, e: except Exception as e:
print "Failed to cleanup %s entries: %s" % (hostname, e) print "Failed to cleanup %s entries: %s" % (hostname, e)
print "You may need to manually remove them from the tree" print "You may need to manually remove them from the tree"
@ -965,7 +965,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
except errors.NotFound: except errors.NotFound:
print "Cannot find replica '%s'" % replica1 print "Cannot find replica '%s'" % replica1
return return
except Exception, e: except Exception as e:
print "Failed to connect to '%s': %s" % (replica1, e) print "Failed to connect to '%s': %s" % (replica1, e)
return return
@ -997,7 +997,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
except errors.NotFound: except errors.NotFound:
print "Cannot find replica '%s'" % replica1 print "Cannot find replica '%s'" % replica1
return return
except Exception, e: except Exception as e:
print "Failed to connect to '%s': %s" % (replica1, e) print "Failed to connect to '%s': %s" % (replica1, e)
return return
@ -1117,7 +1117,7 @@ def show_DNA_ranges(hostname, master, realm, dirman_passwd, nextrange=False,
try: try:
repl = replication.ReplicationManager(realm, hostname, dirman_passwd) repl = replication.ReplicationManager(realm, hostname, dirman_passwd)
except Exception, e: except Exception as e:
sys.exit("Connection failed: %s" % e) sys.exit("Connection failed: %s" % e)
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), repl.suffix) dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), repl.suffix)
try: try:
@ -1131,7 +1131,7 @@ def show_DNA_ranges(hostname, master, realm, dirman_passwd, nextrange=False,
continue continue
try: try:
repl2 = replication.ReplicationManager(realm, remote, dirman_passwd) repl2 = replication.ReplicationManager(realm, remote, dirman_passwd)
except Exception, e: except Exception as e:
print "%s: Connection failed: %s" % (remote, e) print "%s: Connection failed: %s" % (remote, e)
continue continue
if not nextrange: if not nextrange:
@ -1187,14 +1187,14 @@ def store_DNA_range(repl, range_start, range_max, deleted_master, realm,
continue continue
try: try:
repl2 = replication.ReplicationManager(realm, candidate, dirman_passwd) repl2 = replication.ReplicationManager(realm, candidate, dirman_passwd)
except Exception, e: except Exception as e:
print "Connection failed: %s" % e print "Connection failed: %s" % e
continue continue
(next_start, next_max) = repl2.get_DNA_next_range(candidate) (next_start, next_max) = repl2.get_DNA_next_range(candidate)
if next_start is None: if next_start is None:
try: try:
return repl2.save_DNA_next_range(range_start, range_max) return repl2.save_DNA_next_range(range_start, range_max)
except Exception, e: except Exception as e:
print '%s: %s' % (candidate, e) print '%s: %s' % (candidate, e)
return False return False
@ -1226,7 +1226,7 @@ def set_DNA_range(hostname, range, realm, dirman_passwd, next_range=False,
""" """
try: try:
(dna_next, dna_max) = range.split('-', 1) (dna_next, dna_max) = range.split('-', 1)
except ValueError, e: except ValueError as e:
return "Invalid range, must be the form x-y" return "Invalid range, must be the form x-y"
try: try:
@ -1263,14 +1263,14 @@ def set_DNA_range(hostname, range, realm, dirman_passwd, next_range=False,
try: try:
repl = replication.ReplicationManager(realm, hostname, dirman_passwd) repl = replication.ReplicationManager(realm, hostname, dirman_passwd)
except Exception, e: except Exception as e:
sys.exit("Connection failed: %s" % e) sys.exit("Connection failed: %s" % e)
if dna_next > 0: if dna_next > 0:
# Verify that the new range doesn't overlap with an existing range # Verify that the new range doesn't overlap with an existing range
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), repl.suffix) dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), repl.suffix)
try: try:
entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL) entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL)
except Exception, e: except Exception as e:
sys.exit("Failed to read master data from '%s': %s" % (repl.conn.host, str(e))) sys.exit("Failed to read master data from '%s': %s" % (repl.conn.host, str(e)))
else: else:
for ent in entries: for ent in entries:
@ -1279,7 +1279,7 @@ def set_DNA_range(hostname, range, realm, dirman_passwd, next_range=False,
continue continue
try: try:
repl2 = replication.ReplicationManager(realm, master, dirman_passwd) repl2 = replication.ReplicationManager(realm, master, dirman_passwd)
except Exception, e: except Exception as e:
print "Connection to %s failed: %s" % (master, e) print "Connection to %s failed: %s" % (master, e)
print "Overlap not checked." print "Overlap not checked."
continue continue
@ -1304,7 +1304,7 @@ def set_DNA_range(hostname, range, realm, dirman_passwd, next_range=False,
try: try:
entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL, entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL,
"(objectclass=ipaDomainIDRange)") "(objectclass=ipaDomainIDRange)")
except errors.NotFound, e: except errors.NotFound as e:
sys.exit('Unable to load IPA ranges: %s' % e.message) sys.exit('Unable to load IPA ranges: %s' % e.message)
for ent in entries: for ent in entries:
@ -1336,7 +1336,7 @@ def set_DNA_range(hostname, range, realm, dirman_passwd, next_range=False,
sys.exit("No changes to make") sys.exit("No changes to make")
except errors.NotFound: except errors.NotFound:
sys.exit("No permission to update ranges") sys.exit("No permission to update ranges")
except Exception, e: except Exception as e:
sys.exit("Updating next range failed: %s" % e) sys.exit("Updating next range failed: %s" % e)
else: else:
try: try:
@ -1346,7 +1346,7 @@ def set_DNA_range(hostname, range, realm, dirman_passwd, next_range=False,
sys.exit("No changes to make") sys.exit("No changes to make")
except errors.NotFound: except errors.NotFound:
sys.exit("No permission to update ranges") sys.exit("No permission to update ranges")
except Exception, e: except Exception as e:
sys.exit("Updating range failed: %s" % e) sys.exit("Updating range failed: %s" % e)
def has_managed_topology(): def has_managed_topology():
@ -1477,13 +1477,13 @@ try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit(1) sys.exit(1)
except SystemExit, e: except SystemExit as e:
sys.exit(e) sys.exit(e)
except RuntimeError, e: except RuntimeError as e:
sys.exit(e) sys.exit(e)
except socket.timeout: except socket.timeout:
print "Connection timed out." print "Connection timed out."
sys.exit(1) sys.exit(1)
except Exception, e: except Exception as e:
print "unexpected error: %s" % str(e) print "unexpected error: %s" % str(e)
sys.exit(1) sys.exit(1)

View File

@ -163,7 +163,7 @@ def get_config(dirsrv):
attrs = ['cn'] attrs = ['cn']
try: try:
entries = con.get_entries(dn, con.SCOPE_ONELEVEL, attrs_list=attrs) entries = con.get_entries(dn, con.SCOPE_ONELEVEL, attrs_list=attrs)
except Exception, e: except Exception as e:
masters_list.append("No master found because of error: %s" % str(e)) masters_list.append("No master found because of error: %s" % str(e))
else: else:
for master_entry in entries: for master_entry in entries:
@ -174,7 +174,7 @@ def get_config(dirsrv):
raise IpactlError("Failed to get list of services to probe status!\n" raise IpactlError("Failed to get list of services to probe status!\n"
"Configured hostname '%s' does not match any master server in LDAP:\n%s" "Configured hostname '%s' does not match any master server in LDAP:\n%s"
% (api.env.host, masters)) % (api.env.host, masters))
except Exception, e: except Exception as e:
raise IpactlError("Unknown error when retrieving list of services from LDAP: " + str(e)) raise IpactlError("Unknown error when retrieving list of services from LDAP: " + str(e))
svc_list = [] svc_list = []
@ -203,7 +203,7 @@ def get_config_from_file():
try: try:
f = open(tasks.get_svc_list_file(), 'r') f = open(tasks.get_svc_list_file(), 'r')
svc_list = json.load(f) svc_list = json.load(f)
except Exception, e: except Exception as e:
raise IpactlError("Unknown error when retrieving list of services from file: " + str(e)) raise IpactlError("Unknown error when retrieving list of services from file: " + str(e))
# the framework can start/stop a number of related services we are not # the framework can start/stop a number of related services we are not
@ -260,13 +260,13 @@ def ipa_start(options):
try: try:
print "Starting Directory Service" print "Starting Directory Service"
dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug)) dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug))
except Exception, e: except Exception as e:
raise IpactlError("Failed to start Directory Service: " + str(e)) raise IpactlError("Failed to start Directory Service: " + str(e))
ldap_list = [] ldap_list = []
try: try:
svc_list = get_config(dirsrv) svc_list = get_config(dirsrv)
except Exception, e: except Exception as e:
emit_err("Failed to read data from service file: " + str(e)) emit_err("Failed to read data from service file: " + str(e))
emit_err("Shutting down") emit_err("Shutting down")
@ -306,13 +306,13 @@ def ipa_stop(options):
dirsrv = services.knownservices.dirsrv dirsrv = services.knownservices.dirsrv
try: try:
svc_list = get_config_from_file() svc_list = get_config_from_file()
except Exception, e: except Exception as e:
# Issue reading the file ? Let's try to get data from LDAP as a # Issue reading the file ? Let's try to get data from LDAP as a
# fallback # fallback
try: try:
dirsrv.start(capture_output=False) dirsrv.start(capture_output=False)
svc_list = get_config(dirsrv) svc_list = get_config(dirsrv)
except Exception, e: except Exception as e:
emit_err("Failed to read data from Directory Service: " + str(e)) emit_err("Failed to read data from Directory Service: " + str(e))
emit_err("Shutting down") emit_err("Shutting down")
try: try:
@ -356,12 +356,12 @@ def ipa_restart(options):
print "Starting Directory Service" print "Starting Directory Service"
dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug)) dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug))
dirsrv_restart = False dirsrv_restart = False
except Exception, e: except Exception as e:
raise IpactlError("Failed to start Directory Service: " + str(e)) raise IpactlError("Failed to start Directory Service: " + str(e))
try: try:
new_svc_list = get_config(dirsrv) new_svc_list = get_config(dirsrv)
except Exception, e: except Exception as e:
emit_err("Failed to read data from Directory Service: " + str(e)) emit_err("Failed to read data from Directory Service: " + str(e))
emit_err("Shutting down") emit_err("Shutting down")
try: try:
@ -377,7 +377,7 @@ def ipa_restart(options):
old_svc_list = [] old_svc_list = []
try: try:
old_svc_list = get_config_from_file() old_svc_list = get_config_from_file()
except Exception, e: except Exception as e:
emit_err("Failed to get service list from file: " + str(e)) emit_err("Failed to get service list from file: " + str(e))
# fallback to what's in LDAP # fallback to what's in LDAP
old_svc_list = new_svc_list old_svc_list = new_svc_list
@ -410,7 +410,7 @@ def ipa_restart(options):
if dirsrv_restart: if dirsrv_restart:
print "Restarting Directory Service" print "Restarting Directory Service"
dirsrv.restart(capture_output=get_capture_output('dirsrv', options.debug)) dirsrv.restart(capture_output=get_capture_output('dirsrv', options.debug))
except Exception, e: except Exception as e:
emit_err("Failed to restart Directory Service: " + str(e)) emit_err("Failed to restart Directory Service: " + str(e))
emit_err("Shutting down") emit_err("Shutting down")
@ -471,12 +471,12 @@ def ipa_status(options):
svc_list = get_config(dirsrv) svc_list = get_config(dirsrv)
else: else:
svc_list = get_config_from_file() svc_list = get_config_from_file()
except IpactlError, e: except IpactlError as e:
if os.path.exists(tasks.get_svc_list_file()): if os.path.exists(tasks.get_svc_list_file()):
raise e raise e
else: else:
svc_list = [] svc_list = []
except Exception, e: except Exception as e:
raise IpactlError("Failed to get list of services to probe status: " + str(e)) raise IpactlError("Failed to get list of services to probe status: " + str(e))
dirsrv = services.knownservices.dirsrv dirsrv = services.knownservices.dirsrv
@ -520,7 +520,7 @@ def main():
# check if IPA is configured at all # check if IPA is configured at all
try: try:
check_IPA_configuration() check_IPA_configuration()
except IpactlError, e: except IpactlError as e:
if args[0].lower() == "status": if args[0].lower() == "status":
# Different LSB return code for status command: # Different LSB return code for status command:
# 4 - program or service status is unknown # 4 - program or service status is unknown

View File

@ -43,7 +43,7 @@ def application(environ, start_response):
try: try:
index = get_plugin_index() index = get_plugin_index()
status = '200 OK' status = '200 OK'
except Exception, e: except Exception as e:
root_logger.error('plugin index generation failed: %s' % e) root_logger.error('plugin index generation failed: %s' % e)
status = '200 OK' status = '200 OK'
index = get_failed() index = get_failed()

View File

@ -77,7 +77,7 @@ def wait_for_sssd():
try: try:
ipautil.run(["getent", "passwd", "admin@%s" % api.env.realm]) ipautil.run(["getent", "passwd", "admin@%s" % api.env.realm])
found = True found = True
except Exception, e: except Exception as e:
time.sleep(1) time.sleep(1)
n = n + 1 n = n + 1
@ -102,7 +102,7 @@ def configure_xml(fstore):
saslconf = etree.fromstring(lines) saslconf = etree.fromstring(lines)
element = saslconf.xpath('//autofs_ldap_sasl_conf') element = saslconf.xpath('//autofs_ldap_sasl_conf')
root = saslconf.getroottree() root = saslconf.getroottree()
except IOError, e: except IOError as e:
root_logger.debug('Unable to open file %s' % e) root_logger.debug('Unable to open file %s' % e)
root_logger.debug('Creating new from template') root_logger.debug('Creating new from template')
element = [etree.Element('autofs_ldap_sasl_conf')] element = [etree.Element('autofs_ldap_sasl_conf')]
@ -121,7 +121,7 @@ def configure_xml(fstore):
try: try:
root.write(newconf, pretty_print=True, xml_declaration=True, encoding='UTF-8') root.write(newconf, pretty_print=True, xml_declaration=True, encoding='UTF-8')
newconf.close() newconf.close()
except IOError, e: except IOError as e:
print "Unable to write %s: %s" % (paths.AUTOFS_LDAP_AUTH_CONF, e) print "Unable to write %s: %s" % (paths.AUTOFS_LDAP_AUTH_CONF, e)
print "Configured %s" % paths.AUTOFS_LDAP_AUTH_CONF print "Configured %s" % paths.AUTOFS_LDAP_AUTH_CONF
@ -149,7 +149,7 @@ def configure_autofs_sssd(fstore, statestore, autodiscover, options):
sssdconfig = SSSDConfig.SSSDConfig() sssdconfig = SSSDConfig.SSSDConfig()
sssdconfig.import_config() sssdconfig.import_config()
domains = sssdconfig.list_active_domains() domains = sssdconfig.list_active_domains()
except Exception, e: except Exception as e:
sys.exit(e) sys.exit(e)
try: try:
@ -230,11 +230,11 @@ def configure_autofs_common(fstore, statestore, options):
try: try:
autofs.restart() autofs.restart()
print "Started %s" % autofs.service_name print "Started %s" % autofs.service_name
except Exception, e: except Exception as e:
root_logger.error("%s failed to restart: %s", autofs.service_name, e) root_logger.error("%s failed to restart: %s", autofs.service_name, e)
try: try:
autofs.enable() autofs.enable()
except Exception, e: except Exception as e:
print "Failed to configure automatic startup of the %s daemon" % (autofs.service_name) print "Failed to configure automatic startup of the %s daemon" % (autofs.service_name)
root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (autofs.service_name, str(e))) root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (autofs.service_name, str(e)))
@ -280,7 +280,7 @@ def uninstall(fstore, statestore):
sssd = services.service('sssd') sssd = services.service('sssd')
sssd.restart() sssd.restart()
wait_for_sssd() wait_for_sssd()
except Exception, e: except Exception as e:
print 'Unable to restore SSSD configuration: %s' % str(e) print 'Unable to restore SSSD configuration: %s' % str(e)
root_logger.debug('Unable to restore SSSD configuration: %s' % str(e)) root_logger.debug('Unable to restore SSSD configuration: %s' % str(e))
if statestore.has_state('rpcidmapd'): if statestore.has_state('rpcidmapd'):
@ -330,11 +330,11 @@ def configure_nfs(fstore, statestore):
try: try:
rpcidmapd.restart() rpcidmapd.restart()
print "Started %s" % rpcidmapd.service_name print "Started %s" % rpcidmapd.service_name
except Exception, e: except Exception as e:
root_logger.error("%s failed to restart: %s", rpcidmapd.service_name, e) root_logger.error("%s failed to restart: %s", rpcidmapd.service_name, e)
try: try:
rpcidmapd.enable() rpcidmapd.enable()
except Exception, e: except Exception as e:
print "Failed to configure automatic startup of the %s daemon" % (rpcidmapd.service_name) print "Failed to configure automatic startup of the %s daemon" % (rpcidmapd.service_name)
root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcidmapd.service_name, str(e))) root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcidmapd.service_name, str(e)))
@ -344,11 +344,11 @@ def configure_nfs(fstore, statestore):
try: try:
rpcgssd.restart() rpcgssd.restart()
print "Started %s" % rpcgssd.service_name print "Started %s" % rpcgssd.service_name
except Exception, e: except Exception as e:
root_logger.error("%s failed to restart: %s", rpcgssd.service_name, e) root_logger.error("%s failed to restart: %s", rpcgssd.service_name, e)
try: try:
rpcgssd.enable() rpcgssd.enable()
except Exception, e: except Exception as e:
print "Failed to configure automatic startup of the %s daemon" % (rpcgssd.service_name) print "Failed to configure automatic startup of the %s daemon" % (rpcgssd.service_name)
root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcgssd.service_name, str(e))) root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcgssd.service_name, str(e)))
@ -440,7 +440,7 @@ def main():
# Now we have a TGT, connect to IPA # Now we have a TGT, connect to IPA
try: try:
api.Backend.rpcclient.connect() api.Backend.rpcclient.connect()
except errors.KerberosError, e: except errors.KerberosError as e:
sys.exit('Cannot connect to the server due to ' + str(e)) sys.exit('Cannot connect to the server due to ' + str(e))
try: try:
# Use the RPC directly so older servers are supported # Use the RPC directly so older servers are supported
@ -449,11 +449,11 @@ def main():
unicode(options.location), unicode(options.location),
version=u'2.0', version=u'2.0',
) )
except errors.VersionError, e: except errors.VersionError as e:
sys.exit('This client is incompatible: ' + str(e)) sys.exit('This client is incompatible: ' + str(e))
except errors.NotFound: except errors.NotFound:
sys.exit("Automount location '%s' does not exist" % options.location) sys.exit("Automount location '%s' does not exist" % options.location)
except errors.PublicError, e: except errors.PublicError as e:
sys.exit("Cannot connect to the server due to generic error: %s" % str(e)) sys.exit("Cannot connect to the server due to generic error: %s" % str(e))
finally: finally:
os.remove(ccache_name) os.remove(ccache_name)
@ -471,7 +471,7 @@ def main():
configure_xml(fstore) configure_xml(fstore)
configure_autofs(fstore, statestore, autodiscover, server, options) configure_autofs(fstore, statestore, autodiscover, server, options)
configure_autofs_common(fstore, statestore, options) configure_autofs_common(fstore, statestore, options)
except Exception, e: except Exception as e:
root_logger.debug('Raised exception %s' % e) root_logger.debug('Raised exception %s' % e)
print "Installation failed. Rolling back changes." print "Installation failed. Rolling back changes."
uninstall(fstore, statestore) uninstall(fstore, statestore)
@ -484,9 +484,9 @@ try:
sys.exit("\nMust be run as root\n") sys.exit("\nMust be run as root\n")
sys.exit(main()) sys.exit(main())
except SystemExit, e: except SystemExit as e:
sys.exit(e) sys.exit(e)
except RuntimeError, e: except RuntimeError as e:
sys.exit(e) sys.exit(e)
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
sys.exit(1) sys.exit(1)

View File

@ -83,7 +83,7 @@ def parse_options():
initialized = nss.nss_is_initialized() initialized = nss.nss_is_initialized()
try: try:
cert = x509.load_certificate_from_file(value) cert = x509.load_certificate_from_file(value)
except Exception, e: except Exception as e:
raise OptionValueError("%s option '%s' is not a valid certificate file" % (opt, value)) raise OptionValueError("%s option '%s' is not a valid certificate file" % (opt, value))
else: else:
del(cert) del(cert)
@ -470,7 +470,7 @@ def uninstall(options, env):
try: try:
run(["ipa-client-automount", "--uninstall", "--debug"]) run(["ipa-client-automount", "--uninstall", "--debug"])
except Exception, e: except Exception as e:
root_logger.error( root_logger.error(
"Unconfigured automount client failed: %s", str(e)) "Unconfigured automount client failed: %s", str(e))
@ -508,7 +508,7 @@ def uninstall(options, env):
ipa_domain = domain.get_option('ipa_domain') ipa_domain = domain.get_option('ipa_domain')
except SSSDConfig.NoOptionError: except SSSDConfig.NoOptionError:
pass pass
except Exception, e: except Exception as e:
# We were unable to read existing SSSD config. This might mean few things: # We were unable to read existing SSSD config. This might mean few things:
# - sssd wasn't installed # - sssd wasn't installed
# - sssd was removed after install and before uninstall # - sssd was removed after install and before uninstall
@ -527,7 +527,7 @@ def uninstall(options, env):
try: try:
certmonger.stop_tracking(paths.IPA_NSSDB_DIR, certmonger.stop_tracking(paths.IPA_NSSDB_DIR,
nickname='Local IPA host') nickname='Local IPA host')
except RuntimeError, e: except RuntimeError as e:
root_logger.error("%s failed to stop tracking certificate: %s", root_logger.error("%s failed to stop tracking certificate: %s",
cmonger.service_name, e) cmonger.service_name, e)
@ -536,14 +536,14 @@ def uninstall(options, env):
try: try:
certmonger.stop_tracking(paths.NSS_DB_DIR, certmonger.stop_tracking(paths.NSS_DB_DIR,
nickname=client_nss_nickname) nickname=client_nss_nickname)
except RuntimeError, e: except RuntimeError as e:
root_logger.error("%s failed to stop tracking certificate: %s", root_logger.error("%s failed to stop tracking certificate: %s",
cmonger.service_name, e) cmonger.service_name, e)
# Remove our host cert and CA cert # Remove our host cert and CA cert
try: try:
ipa_certs = ipa_db.list_certs() ipa_certs = ipa_db.list_certs()
except CalledProcessError, e: except CalledProcessError as e:
root_logger.error( root_logger.error(
"Failed to list certificates in %s: %s", ipa_db.secdir, e) "Failed to list certificates in %s: %s", ipa_db.secdir, e)
ipa_certs = [] ipa_certs = []
@ -558,7 +558,7 @@ def uninstall(options, env):
while sys_db.has_nickname(nickname): while sys_db.has_nickname(nickname):
try: try:
sys_db.delete_cert(nickname) sys_db.delete_cert(nickname)
except Exception, e: except Exception as e:
root_logger.error("Failed to remove %s from %s: %s", root_logger.error("Failed to remove %s from %s: %s",
nickname, sys_db.secdir, e) nickname, sys_db.secdir, e)
break break
@ -568,12 +568,12 @@ def uninstall(options, env):
try: try:
cmonger.stop() cmonger.stop()
except Exception, e: except Exception as e:
log_service_error(cmonger.service_name, 'stop', e) log_service_error(cmonger.service_name, 'stop', e)
try: try:
cmonger.disable() cmonger.disable()
except Exception, e: except Exception as e:
root_logger.error( root_logger.error(
"Failed to disable automatic startup of the %s service: %s", "Failed to disable automatic startup of the %s service: %s",
cmonger.service_name, str(e)) cmonger.service_name, str(e))
@ -598,7 +598,7 @@ def uninstall(options, env):
fp.close() fp.close()
realm = parser.get('global', 'realm') realm = parser.get('global', 'realm')
run([paths.IPA_RMKEYTAB, "-k", paths.KRB5_KEYTAB, "-r", realm]) run([paths.IPA_RMKEYTAB, "-k", paths.KRB5_KEYTAB, "-r", realm])
except Exception, e: except Exception as e:
root_logger.error( root_logger.error(
"Failed to remove Kerberos service principals: %s", str(e)) "Failed to remove Kerberos service principals: %s", str(e))
@ -615,7 +615,7 @@ def uninstall(options, env):
statestore, statestore,
was_sssd_installed, was_sssd_installed,
was_sssd_configured) was_sssd_configured)
except Exception, e: except Exception as e:
root_logger.error( root_logger.error(
"Failed to remove krb5/LDAP configuration: %s", str(e)) "Failed to remove krb5/LDAP configuration: %s", str(e))
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
@ -701,7 +701,7 @@ def uninstall(options, env):
try: try:
sssd.disable() sssd.disable()
except CalledProcessError, e: except CalledProcessError as e:
root_logger.warning( root_logger.warning(
"Failed to disable automatic startup of the SSSD daemon: %s", e) "Failed to disable automatic startup of the SSSD daemon: %s", e)
@ -753,7 +753,7 @@ def uninstall(options, env):
try: try:
ipaclient.ntpconf.restore_forced_ntpd(statestore) ipaclient.ntpconf.restore_forced_ntpd(statestore)
except CalledProcessError, e: except CalledProcessError as e:
root_logger.error('Failed to start chronyd: %s', e) root_logger.error('Failed to start chronyd: %s', e)
if was_sshd_configured and services.knownservices.sshd.is_running(): if was_sshd_configured and services.knownservices.sshd.is_running():
@ -767,7 +767,7 @@ def uninstall(options, env):
if file_exists(preferences_fname): if file_exists(preferences_fname):
try: try:
os.remove(preferences_fname) os.remove(preferences_fname)
except Exception, e: except Exception as e:
root_logger.warning("'%s' could not be removed: %s." % preferences_fname, str(e)) root_logger.warning("'%s' could not be removed: %s." % preferences_fname, str(e))
root_logger.warning("Please remove file '%s' manually." % preferences_fname) root_logger.warning("Please remove file '%s' manually." % preferences_fname)
@ -815,7 +815,7 @@ def uninstall(options, env):
if user_input("Do you want to reboot the machine?", False): if user_input("Do you want to reboot the machine?", False):
try: try:
run([paths.SBIN_REBOOT]) run([paths.SBIN_REBOOT])
except Exception, e: except Exception as e:
root_logger.error( root_logger.error(
"Reboot command failed to exceute: %s", str(e)) "Reboot command failed to exceute: %s", str(e))
return CLIENT_UNINSTALL_ERROR return CLIENT_UNINSTALL_ERROR
@ -901,7 +901,7 @@ def configure_ldap_conf(fstore, cli_basedn, cli_realm, cli_domain, cli_server, d
try: try:
fstore.backup_file(filename) fstore.backup_file(filename)
ldapconf.newConf(filename, opts) ldapconf.newConf(filename, opts)
except Exception, e: except Exception as e:
root_logger.error("Creation of %s failed: %s", filename, str(e)) root_logger.error("Creation of %s failed: %s", filename, str(e))
return (1, 'LDAP', filename) return (1, 'LDAP', filename)
@ -937,7 +937,7 @@ def configure_nslcd_conf(fstore, cli_basedn, cli_realm, cli_domain, cli_server,
try: try:
fstore.backup_file(filename) fstore.backup_file(filename)
nslcdconf.newConf(filename, opts) nslcdconf.newConf(filename, opts)
except Exception, e: except Exception as e:
root_logger.error("Creation of %s failed: %s", filename, str(e)) root_logger.error("Creation of %s failed: %s", filename, str(e))
return (1, None, None) return (1, None, None)
@ -945,12 +945,12 @@ def configure_nslcd_conf(fstore, cli_basedn, cli_realm, cli_domain, cli_server,
if nslcd.is_installed(): if nslcd.is_installed():
try: try:
nslcd.restart() nslcd.restart()
except Exception, e: except Exception as e:
log_service_error(nslcd.service_name, 'restart', e) log_service_error(nslcd.service_name, 'restart', e)
try: try:
nslcd.enable() nslcd.enable()
except Exception, e: except Exception as e:
root_logger.error( root_logger.error(
"Failed to enable automatic startup of the %s daemon: %s", "Failed to enable automatic startup of the %s daemon: %s",
nslcd.service_name, str(e)) nslcd.service_name, str(e))
@ -1004,15 +1004,15 @@ def configure_openldap_conf(fstore, cli_basedn, cli_server):
try: try:
ldapconf.changeConf(target_fname, opts) ldapconf.changeConf(target_fname, opts)
except SyntaxError, e: except SyntaxError as e:
root_logger.info("Could not parse {path}".format(path=target_fname)) root_logger.info("Could not parse {path}".format(path=target_fname))
root_logger.debug(error_msg.format(path=target_fname, err=str(e))) root_logger.debug(error_msg.format(path=target_fname, err=str(e)))
return False return False
except IOError,e : except IOError as e :
root_logger.info("{path} does not exist.".format(path=target_fname)) root_logger.info("{path} does not exist.".format(path=target_fname))
root_logger.debug(error_msg.format(path=target_fname, err=str(e))) root_logger.debug(error_msg.format(path=target_fname, err=str(e)))
return False return False
except Exception, e: # we do not want to fail in an optional step except Exception as e: # we do not want to fail in an optional step
root_logger.debug(error_msg.format(path=target_fname, err=str(e))) root_logger.debug(error_msg.format(path=target_fname, err=str(e)))
return False return False
@ -1135,7 +1135,7 @@ def configure_certmonger(fstore, subject_base, cli_realm, hostname, options,
cmonger = services.knownservices.certmonger cmonger = services.knownservices.certmonger
try: try:
cmonger.enable() cmonger.enable()
except Exception, e: except Exception as e:
root_logger.error( root_logger.error(
"Failed to configure automatic startup of the %s daemon: %s", "Failed to configure automatic startup of the %s daemon: %s",
cmonger.service_name, str(e)) cmonger.service_name, str(e))
@ -1159,7 +1159,7 @@ def configure_sssd_conf(fstore, cli_realm, cli_domain, cli_server, options, clie
try: try:
sssdconfig = SSSDConfig.SSSDConfig() sssdconfig = SSSDConfig.SSSDConfig()
sssdconfig.import_config() sssdconfig.import_config()
except Exception, e: except Exception as e:
if os.path.exists(paths.SSSD_CONF) and options.preserve_sssd: if os.path.exists(paths.SSSD_CONF) and options.preserve_sssd:
# SSSD config is in place but we are unable to read it # SSSD config is in place but we are unable to read it
# In addition, we are instructed to preserve it # In addition, we are instructed to preserve it
@ -1301,7 +1301,7 @@ def change_ssh_config(filename, changes, sections):
try: try:
f = open(filename, 'r') f = open(filename, 'r')
except IOError, e: except IOError as e:
root_logger.error("Failed to open '%s': %s", filename, str(e)) root_logger.error("Failed to open '%s': %s", filename, str(e))
return False return False
@ -1334,7 +1334,7 @@ def change_ssh_config(filename, changes, sections):
try: try:
f = open(filename, 'w') f = open(filename, 'w')
except IOError, e: except IOError as e:
root_logger.error("Failed to open '%s': %s", filename, str(e)) root_logger.error("Failed to open '%s': %s", filename, str(e))
return False return False
@ -1429,7 +1429,7 @@ def configure_sshd_config(fstore, options):
if sshd.is_running(): if sshd.is_running():
try: try:
sshd.restart() sshd.restart()
except Exception, e: except Exception as e:
log_service_error(sshd.service_name, 'restart', e) log_service_error(sshd.service_name, 'restart', e)
@ -1448,7 +1448,7 @@ def configure_automount(options):
try: try:
stdout, _, _ = run(args) stdout, _, _ = run(args)
except Exception, e: except Exception as e:
root_logger.error('Automount configuration failed: %s', str(e)) root_logger.error('Automount configuration failed: %s', str(e))
else: else:
root_logger.info(stdout) root_logger.info(stdout)
@ -1464,7 +1464,7 @@ def configure_nisdomain(options, domain):
if os.path.exists(paths.BIN_NISDOMAINNAME): if os.path.exists(paths.BIN_NISDOMAINNAME):
try: try:
nis_domain_name, _, _ = ipautil.run([paths.BIN_NISDOMAINNAME]) nis_domain_name, _, _ = ipautil.run([paths.BIN_NISDOMAINNAME])
except CalledProcessError, e: except CalledProcessError as e:
pass pass
statestore.backup_state('network', 'nisdomain', nis_domain_name) statestore.backup_state('network', 'nisdomain', nis_domain_name)
@ -1515,7 +1515,7 @@ def resolve_ipaddress(server):
af, socktype, proto, canonname, sa = res af, socktype, proto, canonname, sa = res
try: try:
s = socket.socket(af, socktype, proto) s = socket.socket(af, socktype, proto)
except socket.error, e: except socket.error as e:
last_socket_error = e last_socket_error = e
s = None s = None
continue continue
@ -1526,7 +1526,7 @@ def resolve_ipaddress(server):
# For both IPv4 and IPv6 own IP address is always the first item # For both IPv4 and IPv6 own IP address is always the first item
return (sockname[0], af) return (sockname[0], af)
except socket.error, e: except socket.error as e:
last_socket_error = e last_socket_error = e
finally: finally:
if s: if s:
@ -1548,7 +1548,7 @@ def do_nsupdate(update_txt):
try: try:
ipautil.run([paths.NSUPDATE, '-g', UPDATE_FILE]) ipautil.run([paths.NSUPDATE, '-g', UPDATE_FILE])
result = True result = True
except CalledProcessError, e: except CalledProcessError as e:
root_logger.debug('nsupdate failed: %s', str(e)) root_logger.debug('nsupdate failed: %s', str(e))
try: try:
@ -1585,7 +1585,7 @@ def update_dns(server, hostname):
try: try:
(ip, af) = resolve_ipaddress(server) (ip, af) = resolve_ipaddress(server)
except socket.gaierror, e: except socket.gaierror as e:
root_logger.debug("update_dns: could not connect to server: %s", e) root_logger.debug("update_dns: could not connect to server: %s", e)
root_logger.error("Cannot update DNS records! " root_logger.error("Cannot update DNS records! "
"Failed to connect to server '%s'.", server) "Failed to connect to server '%s'.", server)
@ -1634,7 +1634,7 @@ def update_ssh_keys(server, hostname, ssh_dir, create_sshfp):
try: try:
f = open(filename, 'r') f = open(filename, 'r')
except IOError, e: except IOError as e:
root_logger.warning("Failed to open '%s': %s", filename, str(e)) root_logger.warning("Failed to open '%s': %s", filename, str(e))
continue continue
@ -1644,7 +1644,7 @@ def update_ssh_keys(server, hostname, ssh_dir, create_sshfp):
continue continue
try: try:
pubkey = SSHPublicKey(line) pubkey = SSHPublicKey(line)
except ValueError, UnicodeDecodeError: except ValueError as UnicodeDecodeError:
continue continue
root_logger.info("Adding SSH public key from %s", filename) root_logger.info("Adding SSH public key from %s", filename)
pubkeys.append(pubkey) pubkeys.append(pubkey)
@ -1662,7 +1662,7 @@ def update_ssh_keys(server, hostname, ssh_dir, create_sshfp):
) )
except errors.EmptyModlist: except errors.EmptyModlist:
pass pass
except StandardError, e: except StandardError as e:
root_logger.info("host_mod: %s", str(e)) root_logger.info("host_mod: %s", str(e))
root_logger.warning("Failed to upload host SSH public keys.") root_logger.warning("Failed to upload host SSH public keys.")
return return
@ -1702,9 +1702,9 @@ def get_certs_from_ldap(server, base_dn, realm, ca_enabled):
certs = certstore.get_ca_certs(conn, base_dn, realm, ca_enabled) certs = certstore.get_ca_certs(conn, base_dn, realm, ca_enabled)
except errors.NotFound: except errors.NotFound:
raise errors.NoCertificateError(entry=server) raise errors.NoCertificateError(entry=server)
except errors.NetworkError, e: except errors.NetworkError as e:
raise errors.NetworkError(uri=conn.ldap_uri, error=str(e)) raise errors.NetworkError(uri=conn.ldap_uri, error=str(e))
except Exception, e: except Exception as e:
raise errors.LDAPError(str(e)) raise errors.LDAPError(str(e))
finally: finally:
conn.unbind() conn.unbind()
@ -1739,7 +1739,7 @@ def get_ca_certs_from_file(url):
root_logger.debug("trying to retrieve CA cert from file %s", filename) root_logger.debug("trying to retrieve CA cert from file %s", filename)
try: try:
certs = x509.load_certificate_list_from_file(filename) certs = x509.load_certificate_list_from_file(filename)
except Exception, e: except Exception as e:
raise errors.NoCertificateError(entry=filename) raise errors.NoCertificateError(entry=filename)
return certs return certs
@ -1760,7 +1760,7 @@ def get_ca_certs_from_http(url, warn=True):
try: try:
stdout, stderr, rc = run([paths.BIN_WGET, "-O", "-", url]) stdout, stderr, rc = run([paths.BIN_WGET, "-O", "-", url])
except CalledProcessError, e: except CalledProcessError as e:
raise errors.NoCertificateError(entry=url) raise errors.NoCertificateError(entry=url)
try: try:
@ -1787,7 +1787,7 @@ def get_ca_certs_from_ldap(server, basedn, realm):
try: try:
certs = get_certs_from_ldap(server, basedn, realm, False) certs = get_certs_from_ldap(server, basedn, realm, False)
except Exception, e: except Exception as e:
root_logger.debug("get_ca_certs_from_ldap() error: %s", e) root_logger.debug("get_ca_certs_from_ldap() error: %s", e)
raise raise
@ -1879,10 +1879,10 @@ def get_ca_certs(fstore, options, server, basedn, realm):
url = file_url() url = file_url()
try: try:
ca_certs = get_ca_certs_from_file(url) ca_certs = get_ca_certs_from_file(url)
except errors.FileError, e: except errors.FileError as e:
root_logger.debug(e) root_logger.debug(e)
raise raise
except Exception, e: except Exception as e:
root_logger.debug(e) root_logger.debug(e)
raise errors.NoCertificateError(entry=url) raise errors.NoCertificateError(entry=url)
root_logger.debug("CA cert provided by user, use it!") root_logger.debug("CA cert provided by user, use it!")
@ -1892,7 +1892,7 @@ def get_ca_certs(fstore, options, server, basedn, realm):
try: try:
existing_ca_certs = x509.load_certificate_list_from_file( existing_ca_certs = x509.load_certificate_list_from_file(
CACERT) CACERT)
except Exception, e: except Exception as e:
raise errors.FileError(reason=u"Unable to load existing" + raise errors.FileError(reason=u"Unable to load existing" +
" CA cert '%s': %s" % (CACERT, e)) " CA cert '%s': %s" % (CACERT, e))
else: else:
@ -1912,7 +1912,7 @@ def get_ca_certs(fstore, options, server, basedn, realm):
" download declined by user") " download declined by user")
try: try:
ca_certs = get_ca_certs_from_http(url, override) ca_certs = get_ca_certs_from_http(url, override)
except Exception, e: except Exception as e:
root_logger.debug(e) root_logger.debug(e)
raise errors.NoCertificateError(entry=url) raise errors.NoCertificateError(entry=url)
@ -1924,10 +1924,10 @@ def get_ca_certs(fstore, options, server, basedn, realm):
url = ldap_url() url = ldap_url()
ca_certs = get_ca_certs_from_ldap(server, basedn, realm) ca_certs = get_ca_certs_from_ldap(server, basedn, realm)
validate_new_ca_certs(existing_ca_certs, ca_certs, interactive) validate_new_ca_certs(existing_ca_certs, ca_certs, interactive)
except errors.FileError, e: except errors.FileError as e:
root_logger.debug(e) root_logger.debug(e)
raise raise
except (errors.NoCertificateError, errors.LDAPError), e: except (errors.NoCertificateError, errors.LDAPError) as e:
root_logger.debug(str(e)) root_logger.debug(str(e))
url = http_url() url = http_url()
if existing_ca_certs: if existing_ca_certs:
@ -1950,12 +1950,12 @@ def get_ca_certs(fstore, options, server, basedn, realm):
else: else:
try: try:
ca_certs = get_ca_certs_from_http(url) ca_certs = get_ca_certs_from_http(url)
except Exception, e: except Exception as e:
root_logger.debug(e) root_logger.debug(e)
raise errors.NoCertificateError(entry=url) raise errors.NoCertificateError(entry=url)
validate_new_ca_certs(existing_ca_certs, ca_certs, validate_new_ca_certs(existing_ca_certs, ca_certs,
interactive) interactive)
except Exception, e: except Exception as e:
root_logger.debug(str(e)) root_logger.debug(str(e))
raise errors.NoCertificateError(entry=url) raise errors.NoCertificateError(entry=url)
@ -1967,11 +1967,11 @@ def get_ca_certs(fstore, options, server, basedn, realm):
try: try:
ca_certs = [cert.der_data for cert in ca_certs] ca_certs = [cert.der_data for cert in ca_certs]
x509.write_certificate_list(ca_certs, ca_file) x509.write_certificate_list(ca_certs, ca_file)
except Exception, e: except Exception as e:
if os.path.exists(ca_file): if os.path.exists(ca_file):
try: try:
os.unlink(ca_file) os.unlink(ca_file)
except OSError, e: except OSError as e:
root_logger.error( root_logger.error(
"Failed to remove '%s': %s", ca_file, e) "Failed to remove '%s': %s", ca_file, e)
raise errors.FileError(reason = raise errors.FileError(reason =
@ -1982,7 +1982,7 @@ def get_ca_certs(fstore, options, server, basedn, realm):
# Make sure the file permissions are correct # Make sure the file permissions are correct
try: try:
os.chmod(CACERT, 0o644) os.chmod(CACERT, 0o644)
except Exception, e: except Exception as e:
raise errors.FileError(reason=u"Unable set permissions on ca " raise errors.FileError(reason=u"Unable set permissions on ca "
u"cert '%s': %s" % (CACERT, e)) u"cert '%s': %s" % (CACERT, e))
@ -2046,14 +2046,14 @@ def configure_firefox(options, statestore, domain):
f.write(update_txt) f.write(update_txt)
root_logger.info("Firefox sucessfully configured.") root_logger.info("Firefox sucessfully configured.")
statestore.backup_state('firefox', 'preferences_fname', preferences_fname) statestore.backup_state('firefox', 'preferences_fname', preferences_fname)
except Exception, e: except Exception as e:
root_logger.debug("An error occured during creating preferences file: %s." % str(e)) root_logger.debug("An error occured during creating preferences file: %s." % str(e))
root_logger.error("Firefox configuration failed.") root_logger.error("Firefox configuration failed.")
else: else:
root_logger.debug("Firefox preferences directory not found.") root_logger.debug("Firefox preferences directory not found.")
root_logger.error("Firefox configuration failed.") root_logger.error("Firefox configuration failed.")
except Exception, e: except Exception as e:
root_logger.debug(str(e)) root_logger.debug(str(e))
root_logger.error("Firefox configuration failed.") root_logger.error("Firefox configuration failed.")
@ -2071,7 +2071,7 @@ def install(options, env, fstore, statestore):
if options.conf_ntp and not options.on_master and not options.force_ntpd: if options.conf_ntp and not options.on_master and not options.force_ntpd:
try: try:
ipaclient.ntpconf.check_timedate_services() ipaclient.ntpconf.check_timedate_services()
except ipaclient.ntpconf.NTPConflictingService, e: except ipaclient.ntpconf.NTPConflictingService as e:
print "WARNING: ntpd time&date synchronization service will not" \ print "WARNING: ntpd time&date synchronization service will not" \
" be configured as" " be configured as"
print "conflicting service (%s) is enabled" % e.conflicting_service print "conflicting service (%s) is enabled" % e.conflicting_service
@ -2314,7 +2314,7 @@ def install(options, env, fstore, statestore):
try: try:
ipautil.run([paths.IPA_RMKEYTAB, ipautil.run([paths.IPA_RMKEYTAB,
'-k', paths.KRB5_KEYTAB, '-r', cli_realm]) '-k', paths.KRB5_KEYTAB, '-r', cli_realm])
except CalledProcessError, e: except CalledProcessError as e:
if e.returncode not in (3, 5): if e.returncode not in (3, 5):
# 3 - Unable to open keytab # 3 - Unable to open keytab
# 5 - Principal name or realm not found in keytab # 5 - Principal name or realm not found in keytab
@ -2478,10 +2478,10 @@ def install(options, env, fstore, statestore):
get_ca_certs(fstore, options, cli_server[0], cli_basedn, get_ca_certs(fstore, options, cli_server[0], cli_basedn,
cli_realm) cli_realm)
del os.environ['KRB5_CONFIG'] del os.environ['KRB5_CONFIG']
except errors.FileError, e: except errors.FileError as e:
root_logger.error(e) root_logger.error(e)
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
except Exception, e: except Exception as e:
root_logger.error("Cannot obtain CA certificate\n%s", e) root_logger.error("Cannot obtain CA certificate\n%s", e)
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
@ -2606,7 +2606,7 @@ def install(options, env, fstore, statestore):
for i, cert in enumerate(ca_certs): for i, cert in enumerate(ca_certs):
tmp_db.add_cert(cert, 'CA certificate %d' % (i + 1), 'C,,') tmp_db.add_cert(cert, 'CA certificate %d' % (i + 1), 'C,,')
except CalledProcessError, e: except CalledProcessError as e:
root_logger.info("Failed to add CA to temporary NSS database.") root_logger.info("Failed to add CA to temporary NSS database.")
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
@ -2617,7 +2617,7 @@ def install(options, env, fstore, statestore):
connected = True connected = True
root_logger.debug("Try RPC connection") root_logger.debug("Try RPC connection")
api.Backend.rpcclient.forward('ping') api.Backend.rpcclient.forward('ping')
except errors.KerberosError, e: except errors.KerberosError as e:
if connected: if connected:
api.Backend.rpcclient.disconnect() api.Backend.rpcclient.disconnect()
root_logger.info( root_logger.info(
@ -2640,13 +2640,13 @@ def install(options, env, fstore, statestore):
root_logger.warning( root_logger.warning(
"Some capabilities including the ipa command capability " "Some capabilities including the ipa command capability "
"may not be available") "may not be available")
except errors.PublicError, e2: except errors.PublicError as e2:
root_logger.warning( root_logger.warning(
"Second connect with delegate=True also failed: %s", e2) "Second connect with delegate=True also failed: %s", e2)
root_logger.error( root_logger.error(
"Cannot connect to the IPA server RPC interface: %s", e2) "Cannot connect to the IPA server RPC interface: %s", e2)
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
except errors.PublicError, e: except errors.PublicError as e:
root_logger.error( root_logger.error(
"Cannot connect to the server due to generic error: %s", e) "Cannot connect to the server due to generic error: %s", e)
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
@ -2671,7 +2671,7 @@ def install(options, env, fstore, statestore):
# Create IPA NSS database # Create IPA NSS database
try: try:
certdb.create_ipa_nssdb() certdb.create_ipa_nssdb()
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
root_logger.error("Failed to create IPA NSS database: %s", e) root_logger.error("Failed to create IPA NSS database: %s", e)
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
@ -2695,7 +2695,7 @@ def install(options, env, fstore, statestore):
for cert, nickname, trust_flags in ca_certs_trust: for cert, nickname, trust_flags in ca_certs_trust:
try: try:
ipa_db.add_cert(cert, nickname, trust_flags) ipa_db.add_cert(cert, nickname, trust_flags)
except CalledProcessError, e: except CalledProcessError as e:
root_logger.error( root_logger.error(
"Failed to add %s to the IPA NSS database.", nickname) "Failed to add %s to the IPA NSS database.", nickname)
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
@ -2710,7 +2710,7 @@ def install(options, env, fstore, statestore):
for cert, nickname, trust_flags in ca_certs_trust: for cert, nickname, trust_flags in ca_certs_trust:
try: try:
sys_db.add_cert(cert, nickname, trust_flags) sys_db.add_cert(cert, nickname, trust_flags)
except CalledProcessError, e: except CalledProcessError as e:
root_logger.error( root_logger.error(
"Failed to add %s to the default NSS database.", nickname) "Failed to add %s to the default NSS database.", nickname)
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR
@ -2793,7 +2793,7 @@ def install(options, env, fstore, statestore):
try: try:
sssd.enable() sssd.enable()
except CalledProcessError, e: except CalledProcessError as e:
root_logger.warning( root_logger.warning(
"Failed to enable automatic startup of the SSSD daemon: %s", e) "Failed to enable automatic startup of the SSSD daemon: %s", e)
@ -2829,7 +2829,7 @@ def install(options, env, fstore, statestore):
try: try:
ipautil.run(["getent", "passwd", "admin@%s" % cli_domain]) ipautil.run(["getent", "passwd", "admin@%s" % cli_domain])
found = True found = True
except Exception, e: except Exception as e:
time.sleep(1) time.sleep(1)
n = n + 1 n = n + 1
@ -2845,7 +2845,7 @@ def install(options, env, fstore, statestore):
try: try:
hardcode_ldap_server(cli_server) hardcode_ldap_server(cli_server)
except Exception, e: except Exception as e:
root_logger.error("Adding hardcoded server name to " + root_logger.error("Adding hardcoded server name to " +
"/etc/ldap.conf failed: %s", str(e)) "/etc/ldap.conf failed: %s", str(e))
@ -2935,11 +2935,11 @@ def main():
try: try:
if __name__ == "__main__": if __name__ == "__main__":
sys.exit(main()) sys.exit(main())
except SystemExit, e: except SystemExit as e:
sys.exit(e) sys.exit(e)
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit(1) sys.exit(1)
except RuntimeError, e: except RuntimeError as e:
sys.exit(e) sys.exit(e)
finally: finally:
try: try:

View File

@ -101,7 +101,7 @@ class CertUpdate(admintool.AdminTool):
while sys_db.has_nickname(nickname): while sys_db.has_nickname(nickname):
try: try:
sys_db.delete_cert(nickname) sys_db.delete_cert(nickname)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.log.error("Failed to remove %s from %s: %s", self.log.error("Failed to remove %s from %s: %s",
nickname, sys_db.secdir, e) nickname, sys_db.secdir, e)
break break
@ -111,7 +111,7 @@ class CertUpdate(admintool.AdminTool):
while ipa_db.has_nickname(nickname): while ipa_db.has_nickname(nickname):
try: try:
ipa_db.delete_cert(nickname) ipa_db.delete_cert(nickname)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.log.error("Failed to remove %s from %s: %s", self.log.error("Failed to remove %s from %s: %s",
nickname, ipa_db.secdir, e) nickname, ipa_db.secdir, e)
break break
@ -168,7 +168,7 @@ class CertUpdate(admintool.AdminTool):
certs = (c[0] for c in certs if c[2] is not False) certs = (c[0] for c in certs if c[2] is not False)
try: try:
x509.write_certificate_list(certs, filename) x509.write_certificate_list(certs, filename)
except Exception, e: except Exception as e:
self.log.error("failed to update %s: %s", filename, e) self.log.error("failed to update %s: %s", filename, e)
def update_db(self, path, certs): def update_db(self, path, certs):
@ -178,6 +178,6 @@ class CertUpdate(admintool.AdminTool):
trusted, True, eku) trusted, True, eku)
try: try:
db.add_cert(cert, nickname, trust_flags) db.add_cert(cert, nickname, trust_flags)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.log.error( self.log.error(
"failed to update %s in %s: %s", nickname, path, e) "failed to update %s in %s: %s", nickname, path, e)

View File

@ -515,7 +515,7 @@ class IPAChangeConf:
try: try:
try: try:
shutil.copy2(file, (file + ".ipabkp")) shutil.copy2(file, (file + ".ipabkp"))
except IOError, err: except IOError as err:
if err.errno == 2: if err.errno == 2:
# The orign file did not exist # The orign file did not exist
pass pass

View File

@ -350,7 +350,7 @@ class IPADiscovery(object):
except errors.ACIError: except errors.ACIError:
root_logger.debug("LDAP Error: Anonymous access not allowed") root_logger.debug("LDAP Error: Anonymous access not allowed")
return [NO_ACCESS_TO_LDAP] return [NO_ACCESS_TO_LDAP]
except errors.DatabaseError, err: except errors.DatabaseError as err:
root_logger.error("Error checking LDAP: %s" % err.strerror) root_logger.error("Error checking LDAP: %s" % err.strerror)
# We should only get UNWILLING_TO_PERFORM if the remote LDAP # We should only get UNWILLING_TO_PERFORM if the remote LDAP
# server has minssf > 0 and we have attempted a non-TLS conn. # server has minssf > 0 and we have attempted a non-TLS conn.
@ -409,16 +409,16 @@ class IPADiscovery(object):
except errors.DatabaseTimeout: except errors.DatabaseTimeout:
root_logger.debug("LDAP Error: timeout") root_logger.debug("LDAP Error: timeout")
return [NO_LDAP_SERVER] return [NO_LDAP_SERVER]
except errors.NetworkError, err: except errors.NetworkError as err:
root_logger.debug("LDAP Error: %s" % err.strerror) root_logger.debug("LDAP Error: %s" % err.strerror)
return [NO_LDAP_SERVER] return [NO_LDAP_SERVER]
except errors.ACIError: except errors.ACIError:
root_logger.debug("LDAP Error: Anonymous access not allowed") root_logger.debug("LDAP Error: Anonymous access not allowed")
return [NO_ACCESS_TO_LDAP] return [NO_ACCESS_TO_LDAP]
except errors.DatabaseError, err: except errors.DatabaseError as err:
root_logger.debug("Error checking LDAP: %s" % err.strerror) root_logger.debug("Error checking LDAP: %s" % err.strerror)
return [UNKNOWN_ERROR] return [UNKNOWN_ERROR]
except Exception, err: except Exception as err:
root_logger.debug("Error checking LDAP: %s" % err) root_logger.debug("Error checking LDAP: %s" % err)
return [UNKNOWN_ERROR] return [UNKNOWN_ERROR]
@ -447,7 +447,7 @@ class IPADiscovery(object):
try: try:
answers = resolver.query(qname, rdatatype.SRV) answers = resolver.query(qname, rdatatype.SRV)
except DNSException, e: except DNSException as e:
root_logger.debug("DNS record not found: %s", e.__class__.__name__) root_logger.debug("DNS record not found: %s", e.__class__.__name__)
answers = [] answers = []
@ -476,7 +476,7 @@ class IPADiscovery(object):
try: try:
answers = resolver.query(qname, rdatatype.TXT) answers = resolver.query(qname, rdatatype.TXT)
except DNSException, e: except DNSException as e:
root_logger.debug("DNS record not found: %s", e.__class__.__name__) root_logger.debug("DNS record not found: %s", e.__class__.__name__)
answers = [] answers = []

View File

@ -127,14 +127,14 @@ class Executioner(Backend):
if _name not in self.Command: if _name not in self.Command:
raise CommandError(name=_name) raise CommandError(name=_name)
result = self.Command[_name](*args, **options) result = self.Command[_name](*args, **options)
except PublicError, e: except PublicError as e:
error = e error = e
except StandardError, e: except StandardError as e:
self.exception( self.exception(
'non-public: %s: %s', e.__class__.__name__, str(e) 'non-public: %s: %s', e.__class__.__name__, str(e)
) )
error = InternalError() error = InternalError()
except Exception, e: except Exception as e:
self.exception( self.exception(
'unhandled exception: %s: %s', e.__class__.__name__, str(e) 'unhandled exception: %s: %s', e.__class__.__name__, str(e)
) )

View File

@ -36,7 +36,7 @@ def _parse_cert(dercert):
issuer = x509.get_issuer(dercert, x509.DER) issuer = x509.get_issuer(dercert, x509.DER)
serial_number = x509.get_serial_number(dercert, x509.DER) serial_number = x509.get_serial_number(dercert, x509.DER)
public_key_info = x509.get_der_public_key_info(dercert, x509.DER) public_key_info = x509.get_der_public_key_info(dercert, x509.DER)
except (NSPRError, PyAsn1Error), e: except (NSPRError, PyAsn1Error) as e:
raise ValueError("failed to decode certificate: %s" % e) raise ValueError("failed to decode certificate: %s" % e)
subject = str(subject).replace('\\;', '\\3b') subject = str(subject).replace('\\;', '\\3b')
@ -55,7 +55,7 @@ def init_ca_entry(entry, dercert, nickname, trusted, ext_key_usage):
if ext_key_usage is not None: if ext_key_usage is not None:
try: try:
cert_eku = x509.get_ext_key_usage(dercert, x509.DER) cert_eku = x509.get_ext_key_usage(dercert, x509.DER)
except NSPRError, e: except NSPRError as e:
raise ValueError("failed to decode certificate: %s" % e) raise ValueError("failed to decode certificate: %s" % e)
if cert_eku is not None: if cert_eku is not None:
cert_eku -= {x509.EKU_SERVER_AUTH, x509.EKU_CLIENT_AUTH, cert_eku -= {x509.EKU_SERVER_AUTH, x509.EKU_CLIENT_AUTH,

View File

@ -1283,7 +1283,7 @@ class cli(backend.Executioner):
f = open(fname, 'r') f = open(fname, 'r')
raw = f.read() raw = f.read()
f.close() f.close()
except IOError, e: except IOError as e:
raise ValidationError( raise ValidationError(
name=to_cli(p.cli_name), name=to_cli(p.cli_name),
error='%s: %s:' % (fname, e[1]) error='%s: %s:' % (fname, e[1])
@ -1291,7 +1291,7 @@ class cli(backend.Executioner):
elif p.stdin_if_missing: elif p.stdin_if_missing:
try: try:
raw = sys.stdin.read() raw = sys.stdin.read()
except IOError, e: except IOError as e:
raise ValidationError( raise ValidationError(
name=to_cli(p.cli_name), error=e[1] name=to_cli(p.cli_name), error=e[1]
) )
@ -1341,9 +1341,9 @@ def run(api):
except KeyboardInterrupt: except KeyboardInterrupt:
print '' print ''
api.log.info('operation aborted') api.log.info('operation aborted')
except PublicError, e: except PublicError as e:
error = e error = e
except StandardError, e: except StandardError as e:
api.log.exception('%s: %s', e.__class__.__name__, str(e)) api.log.exception('%s: %s', e.__class__.__name__, str(e))
error = InternalError() error = InternalError()
if error is not None: if error is not None:

View File

@ -463,7 +463,7 @@ class Command(HasParam):
try: try:
value = values.get(p.name) value = values.get(p.name)
values[p.name] = p(value, **values) values[p.name] = p(value, **values)
except InvocationError, e: except InvocationError as e:
errors[p.name] = str(e) errors[p.name] = str(e)
return dict( return dict(
values=values, values=values,
@ -591,7 +591,7 @@ class Command(HasParam):
try: try:
return param(raw, **kw) return param(raw, **kw)
except (ValidationError, ConversionError), e: except (ValidationError, ConversionError) as e:
# Display error and prompt again # Display error and prompt again
self.Backend.textui.print_prompt_attribute_error(unicode(label), self.Backend.textui.print_prompt_attribute_error(unicode(label),
unicode(e.error)) unicode(e.error))

View File

@ -166,7 +166,7 @@ class KRB5_CCache(object):
self.scheme, self.name = krb5_parse_ccache(ccache) self.scheme, self.name = krb5_parse_ccache(ccache)
self.ccache = krbV.CCache(name=str(ccache), context=self.context) self.ccache = krbV.CCache(name=str(ccache), context=self.context)
self.principal = self.ccache.principal() self.principal = self.ccache.principal()
except krbV.Krb5Error, e: except krbV.Krb5Error as e:
error_code = e.args[0] error_code = e.args[0]
message = e.args[1] message = e.args[1]
if error_code == KRB5_FCC_NOFILE: if error_code == KRB5_FCC_NOFILE:
@ -212,7 +212,7 @@ class KRB5_CCache(object):
else: else:
try: try:
krbV_principal = krbV.Principal(str(principal), self.context) krbV_principal = krbV.Principal(str(principal), self.context)
except Exception, e: except Exception as e:
self.error('could not create krbV principal from "%s", %s', principal, e) self.error('could not create krbV principal from "%s", %s', principal, e)
raise e raise e
@ -227,13 +227,13 @@ class KRB5_CCache(object):
None) # adlist None) # adlist
try: try:
cred = self.ccache.get_credentials(creds_tuple, KRB5_GC_CACHED) cred = self.ccache.get_credentials(creds_tuple, KRB5_GC_CACHED)
except krbV.Krb5Error, e: except krbV.Krb5Error as e:
error_code = e.args[0] error_code = e.args[0]
if error_code == KRB5_CC_NOTFOUND: if error_code == KRB5_CC_NOTFOUND:
raise KeyError('"%s" credential not found in "%s" ccache' % \ raise KeyError('"%s" credential not found in "%s" ccache' % \
(krbV_principal.name, self.ccache_str())) (krbV_principal.name, self.ccache_str()))
raise e raise e
except Exception, e: except Exception as e:
raise e raise e
return cred return cred
@ -273,7 +273,7 @@ class KRB5_CCache(object):
else: else:
try: try:
krbV_principal = krbV.Principal(str(principal), self.context) krbV_principal = krbV.Principal(str(principal), self.context)
except Exception, e: except Exception as e:
self.error('could not create krbV principal from "%s", %s', principal, e) self.error('could not create krbV principal from "%s", %s', principal, e)
raise e raise e
@ -288,9 +288,9 @@ class KRB5_CCache(object):
return authtime, starttime, endtime, renew_till return authtime, starttime, endtime, renew_till
except KeyError, e: except KeyError as e:
raise e raise e
except Exception, e: except Exception as e:
self.error('get_credential_times failed, principal="%s" error="%s"', krbV_principal.name, e) self.error('get_credential_times failed, principal="%s" error="%s"', krbV_principal.name, e)
raise e raise e
@ -314,9 +314,9 @@ class KRB5_CCache(object):
try: try:
authtime, starttime, endtime, renew_till = self.get_credential_times(principal) authtime, starttime, endtime, renew_till = self.get_credential_times(principal)
except KeyError, e: except KeyError as e:
return False return False
except Exception, e: except Exception as e:
self.error('credential_is_valid failed, principal="%s" error="%s"', principal, e) self.error('credential_is_valid failed, principal="%s" error="%s"', principal, e)
raise e raise e

View File

@ -1134,7 +1134,7 @@ class Decimal(Number):
if isinstance(value, (basestring, float)): if isinstance(value, (basestring, float)):
try: try:
value = decimal.Decimal(value) value = decimal.Decimal(value)
except Exception, e: except Exception as e:
raise ValueError( raise ValueError(
'%s: cannot parse kwarg %s: %s' % ( '%s: cannot parse kwarg %s: %s' % (
name, kwparam, str(e))) name, kwparam, str(e)))
@ -1189,7 +1189,7 @@ class Decimal(Number):
quantize_exp = decimal.Decimal(10) ** -self.precision quantize_exp = decimal.Decimal(10) ** -self.precision
try: try:
value = value.quantize(quantize_exp) value = value.quantize(quantize_exp)
except decimal.DecimalException, e: except decimal.DecimalException as e:
raise ConversionError(name=self.get_param_name(), raise ConversionError(name=self.get_param_name(),
error=unicode(e)) error=unicode(e))
return value return value
@ -1203,7 +1203,7 @@ class Decimal(Number):
value = value.quantize(decimal.Decimal(1)) \ value = value.quantize(decimal.Decimal(1)) \
if value == value.to_integral() \ if value == value.to_integral() \
else value.normalize() else value.normalize()
except decimal.DecimalException, e: except decimal.DecimalException as e:
raise ConversionError(name=self.get_param_name(), raise ConversionError(name=self.get_param_name(),
error=unicode(e)) error=unicode(e))
@ -1224,7 +1224,7 @@ class Decimal(Number):
if isinstance(value, (basestring, float)): if isinstance(value, (basestring, float)):
try: try:
value = decimal.Decimal(value) value = decimal.Decimal(value)
except decimal.DecimalException, e: except decimal.DecimalException as e:
raise ConversionError(name=self.get_param_name(), index=index, raise ConversionError(name=self.get_param_name(), index=index,
error=unicode(e)) error=unicode(e))
@ -1363,7 +1363,7 @@ class Bytes(Data):
if isinstance(value, unicode): if isinstance(value, unicode):
try: try:
value = base64.b64decode(value) value = base64.b64decode(value)
except TypeError, e: except TypeError as e:
raise Base64DecodeError(reason=str(e)) raise Base64DecodeError(reason=str(e))
return super(Bytes, self)._convert_scalar(value, index) return super(Bytes, self)._convert_scalar(value, index)
@ -1826,7 +1826,7 @@ class AccessTime(Str):
def _rule_required(self, _, value): def _rule_required(self, _, value):
try: try:
self._check(value) self._check(value)
except ValueError, e: except ValueError as e:
raise ValidationError(name=self.get_param_name(), error=e.args[0]) raise ValidationError(name=self.get_param_name(), error=e.args[0])
except IndexError: except IndexError:
raise ValidationError( raise ValidationError(
@ -1847,7 +1847,7 @@ class DNParam(Param):
try: try:
dn = DN(value) dn = DN(value)
except Exception, e: except Exception as e:
raise ConversionError(name=self.get_param_name(), index=index, raise ConversionError(name=self.get_param_name(), index=index,
error=ugettext(e)) error=ugettext(e))
return dn return dn

View File

@ -429,7 +429,7 @@ class API(ReadOnly):
filename=self.env.log, filename=self.env.log,
level=level, level=level,
format=LOGGING_FORMAT_FILE)]) format=LOGGING_FORMAT_FILE)])
except IOError, e: except IOError as e:
log.error('Cannot open log file %r: %s', self.env.log, e) log.error('Cannot open log file %r: %s', self.env.log, e)
return return
@ -541,7 +541,7 @@ class API(ReadOnly):
subpackage = module[:-2] subpackage = module[:-2]
try: try:
plugins = importlib.import_module(subpackage) plugins = importlib.import_module(subpackage)
except ImportError, e: except ImportError as e:
self.log.error("cannot import plugins sub-package %s: %s", self.log.error("cannot import plugins sub-package %s: %s",
subpackage, e) subpackage, e)
raise raise
@ -565,9 +565,9 @@ class API(ReadOnly):
self.log.debug("importing plugin module %s", name) self.log.debug("importing plugin module %s", name)
try: try:
module = importlib.import_module(name) module = importlib.import_module(name)
except errors.SkipPluginModule, e: except errors.SkipPluginModule as e:
self.log.debug("skipping plugin module %s: %s", name, e.reason) self.log.debug("skipping plugin module %s: %s", name, e.reason)
except StandardError, e: except StandardError as e:
if self.env.startup_traceback: if self.env.startup_traceback:
import traceback import traceback
self.log.error("could not load plugin module %s\n%s", name, self.log.error("could not load plugin module %s\n%s", name,

View File

@ -244,7 +244,7 @@ def _make_aci(ldap, current, aciname, kw):
# This will raise NotFound if the permission doesn't exist # This will raise NotFound if the permission doesn't exist
try: try:
entry_attrs = api.Command['permission_show'](kw['permission'])['result'] entry_attrs = api.Command['permission_show'](kw['permission'])['result']
except errors.NotFound, e: except errors.NotFound as e:
if 'test' in kw and not kw.get('test'): if 'test' in kw and not kw.get('test'):
raise e raise e
else: else:
@ -304,7 +304,7 @@ def _make_aci(ldap, current, aciname, kw):
if not target.startswith('ldap:///'): if not target.startswith('ldap:///'):
target = 'ldap:///%s' % target target = 'ldap:///%s' % target
a.set_target(target) a.set_target(target)
except SyntaxError, e: except SyntaxError as e:
raise errors.ValidationError(name='target', error=_('Syntax Error: %(error)s') % dict(error=str(e))) raise errors.ValidationError(name='target', error=_('Syntax Error: %(error)s') % dict(error=str(e)))
return a return a
@ -370,7 +370,7 @@ def _aci_to_kw(ldap, a, test=False, pkey_only=False):
entry = ldap.make_entry(dn) entry = ldap.make_entry(dn)
try: try:
entry = ldap.get_entry(groupdn, ['cn']) entry = ldap.get_entry(groupdn, ['cn'])
except errors.NotFound, e: except errors.NotFound as e:
# FIXME, use real name here # FIXME, use real name here
if test: if test:
dn = DN(('cn', 'test'), api.env.container_permission, dn = DN(('cn', 'test'), api.env.container_permission,
@ -389,7 +389,7 @@ def _convert_strings_to_acis(acistrs):
for a in acistrs: for a in acistrs:
try: try:
acis.append(ACI(a)) acis.append(ACI(a))
except SyntaxError, e: except SyntaxError as e:
root_logger.warning("Failed to parse: %s" % a) root_logger.warning("Failed to parse: %s" % a)
return acis return acis
@ -651,7 +651,7 @@ class aci_mod(crud.Update):
try: try:
result = self.api.Command['aci_add'](aciname, **newkw)['result'] result = self.api.Command['aci_add'](aciname, **newkw)['result']
except Exception, e: except Exception as e:
# ACI could not be added, try to restore the old deleted ACI and # ACI could not be added, try to restore the old deleted ACI and
# report the ADD error back to user # report the ADD error back to user
try: try:

View File

@ -407,7 +407,7 @@ class automountlocation_import(LDAPQuery):
fp = open(filename, 'r') fp = open(filename, 'r')
map = fp.readlines() map = fp.readlines()
fp.close() fp.close()
except IOError, e: except IOError as e:
if e.errno == 2: if e.errno == 2:
raise errors.NotFound( raise errors.NotFound(
reason=_('File %(file)s not found') % {'file': filename} reason=_('File %(file)s not found') % {'file': filename}
@ -453,7 +453,7 @@ class automountlocation_import(LDAPQuery):
automountkey=unicode(am[0]), automountkey=unicode(am[0]),
automountinformation=unicode(' '.join(am[1:]))) automountinformation=unicode(' '.join(am[1:])))
result['keys'].append([am[0], u'auto.master']) result['keys'].append([am[0], u'auto.master'])
except errors.DuplicateEntry, e: except errors.DuplicateEntry as e:
if unicode(am[0]) in DEFAULT_KEYS: if unicode(am[0]) in DEFAULT_KEYS:
# ignore conflict when the key was pre-created by the framework # ignore conflict when the key was pre-created by the framework
pass pass
@ -469,7 +469,7 @@ class automountlocation_import(LDAPQuery):
try: try:
api.Command['automountmap_add'](args[0], unicode(am[1])) api.Command['automountmap_add'](args[0], unicode(am[1]))
result['maps'].append(am[1]) result['maps'].append(am[1])
except errors.DuplicateEntry, e: except errors.DuplicateEntry as e:
if unicode(am[1]) in DEFAULT_MAPS: if unicode(am[1]) in DEFAULT_MAPS:
# ignore conflict when the map was pre-created by the framework # ignore conflict when the map was pre-created by the framework
pass pass
@ -515,7 +515,7 @@ class automountlocation_import(LDAPQuery):
automountkey=key, automountkey=key,
automountinformation=unicode(' '.join(am[1:]))) automountinformation=unicode(' '.join(am[1:])))
result['keys'].append([key,m]) result['keys'].append([key,m])
except errors.DuplicateEntry, e: except errors.DuplicateEntry as e:
if options.get('continue', False): if options.get('continue', False):
result['duplicatekeys'].append(am[0]) result['duplicatekeys'].append(am[0])
pass pass

View File

@ -311,7 +311,7 @@ def wait_for_value(ldap, dn, attr, value):
def validate_externalhost(ugettext, hostname): def validate_externalhost(ugettext, hostname):
try: try:
validate_hostname(hostname, check_fqdn=False, allow_underscore=True) validate_hostname(hostname, check_fqdn=False, allow_underscore=True)
except ValueError, e: except ValueError as e:
return unicode(e) return unicode(e)
@ -1099,9 +1099,9 @@ last, after all sets and adds."""),
# validate, convert and encode params # validate, convert and encode params
try: try:
value = param(value) value = param(value)
except errors.ValidationError, err: except errors.ValidationError as err:
raise errors.ValidationError(name=attr, error=err.error) raise errors.ValidationError(name=attr, error=err.error)
except errors.ConversionError, err: except errors.ConversionError as err:
raise errors.ConversionError(name=attr, error=err.error) raise errors.ConversionError(name=attr, error=err.error)
if isinstance(value, tuple): if isinstance(value, tuple):
value = list(value) value = list(value)
@ -1143,7 +1143,7 @@ last, after all sets and adds."""),
while True: while True:
try: try:
return func(*call_args, **call_kwargs) return func(*call_args, **call_kwargs)
except errors.ExecutionError, e: except errors.ExecutionError as e:
if not callbacks: if not callbacks:
raise raise
# call exc_callback in the next loop # call exc_callback in the next loop
@ -1507,7 +1507,7 @@ class LDAPUpdate(LDAPQuery, crud.Update):
update.update(entry_attrs) update.update(entry_attrs)
self._exc_wrapper(keys, options, ldap.update_entry)(update) self._exc_wrapper(keys, options, ldap.update_entry)(update)
except errors.EmptyModlist, e: except errors.EmptyModlist as e:
if not rdnupdate: if not rdnupdate:
raise e raise e
except errors.NotFound: except errors.NotFound:
@ -1684,7 +1684,7 @@ class LDAPModMember(LDAPQuery):
ldap_obj = self.api.Object[ldap_obj_name] ldap_obj = self.api.Object[ldap_obj_name]
try: try:
dns[attr][ldap_obj_name].append(ldap_obj.get_dn(name)) dns[attr][ldap_obj_name].append(ldap_obj.get_dn(name))
except errors.PublicError, e: except errors.PublicError as e:
failed[attr][ldap_obj_name].append((name, unicode(e))) failed[attr][ldap_obj_name].append((name, unicode(e)))
return (dns, failed) return (dns, failed)
@ -1732,7 +1732,7 @@ class LDAPAddMember(LDAPModMember):
continue continue
try: try:
ldap.add_entry_to_group(m_dn, dn, attr, allow_same=self.allow_same) ldap.add_entry_to_group(m_dn, dn, attr, allow_same=self.allow_same)
except errors.PublicError, e: except errors.PublicError as e:
ldap_obj = self.api.Object[ldap_obj_name] ldap_obj = self.api.Object[ldap_obj_name]
failed[attr][ldap_obj_name].append(( failed[attr][ldap_obj_name].append((
ldap_obj.get_primary_key_from_dn(m_dn), ldap_obj.get_primary_key_from_dn(m_dn),
@ -1833,7 +1833,7 @@ class LDAPRemoveMember(LDAPModMember):
continue continue
try: try:
ldap.remove_entry_from_group(m_dn, dn, attr) ldap.remove_entry_from_group(m_dn, dn, attr)
except errors.PublicError, e: except errors.PublicError as e:
ldap_obj = self.api.Object[ldap_obj_name] ldap_obj = self.api.Object[ldap_obj_name]
failed[attr][ldap_obj_name].append(( failed[attr][ldap_obj_name].append((
ldap_obj.get_primary_key_from_dn(m_dn), ldap_obj.get_primary_key_from_dn(m_dn),
@ -2193,12 +2193,12 @@ class LDAPAddReverseMember(LDAPModReverseMember):
completed = completed + 1 completed = completed + 1
else: else:
failed['member'][self.reverse_attr].append((attr, result['failed']['member'][self.member_attr][0][1])) failed['member'][self.reverse_attr].append((attr, result['failed']['member'][self.member_attr][0][1]))
except errors.NotFound, e: except errors.NotFound as e:
msg = str(e) msg = str(e)
(attr, msg) = msg.split(':', 1) (attr, msg) = msg.split(':', 1)
failed['member'][self.reverse_attr].append((attr, unicode(msg.strip()))) failed['member'][self.reverse_attr].append((attr, unicode(msg.strip())))
except errors.PublicError, e: except errors.PublicError as e:
failed['member'][self.reverse_attr].append((attr, unicode(msg))) failed['member'][self.reverse_attr].append((attr, unicode(msg)))
# Update the member data. # Update the member data.
@ -2294,12 +2294,12 @@ class LDAPRemoveReverseMember(LDAPModReverseMember):
completed = completed + 1 completed = completed + 1
else: else:
failed['member'][self.reverse_attr].append((attr, result['failed']['member'][self.member_attr][0][1])) failed['member'][self.reverse_attr].append((attr, result['failed']['member'][self.member_attr][0][1]))
except errors.NotFound, e: except errors.NotFound as e:
msg = str(e) msg = str(e)
(attr, msg) = msg.split(':', 1) (attr, msg) = msg.split(':', 1)
failed['member'][self.reverse_attr].append((attr, unicode(msg.strip()))) failed['member'][self.reverse_attr].append((attr, unicode(msg.strip())))
except errors.PublicError, e: except errors.PublicError as e:
failed['member'][self.reverse_attr].append((attr, unicode(msg))) failed['member'][self.reverse_attr].append((attr, unicode(msg)))
# Update the member data. # Update the member data.

View File

@ -106,7 +106,7 @@ class batch(Command):
'%s: batch: %s(%s): SUCCESS', context.principal, name, ', '.join(api.Command[name]._repr_iter(**params)) '%s: batch: %s(%s): SUCCESS', context.principal, name, ', '.join(api.Command[name]._repr_iter(**params))
) )
result['error']=None result['error']=None
except Exception, e: except Exception as e:
if isinstance(e, errors.RequirementError) or \ if isinstance(e, errors.RequirementError) or \
isinstance(e, errors.CommandError): isinstance(e, errors.CommandError):
self.info( self.info(

View File

@ -134,7 +134,7 @@ def validate_pkidate(ugettext, value):
""" """
try: try:
ts = time.strptime(value, '%Y-%m-%d') ts = time.strptime(value, '%Y-%m-%d')
except ValueError, e: except ValueError as e:
return str(e) return str(e)
return None return None
@ -151,9 +151,9 @@ def validate_csr(ugettext, csr):
return return
try: try:
request = pkcs10.load_certificate_request(csr) request = pkcs10.load_certificate_request(csr)
except TypeError, e: except TypeError as e:
raise errors.Base64DecodeError(reason=str(e)) raise errors.Base64DecodeError(reason=str(e))
except Exception, e: except Exception as e:
raise errors.CertificateOperationError(error=_('Failure decoding Certificate Signing Request: %s') % e) raise errors.CertificateOperationError(error=_('Failure decoding Certificate Signing Request: %s') % e)
def normalize_csr(csr): def normalize_csr(csr):
@ -365,7 +365,7 @@ class cert_request(VirtualCommand):
subject = pkcs10.get_subject(csr) subject = pkcs10.get_subject(csr)
extensions = pkcs10.get_extensions(csr) extensions = pkcs10.get_extensions(csr)
subjectaltname = pkcs10.get_subjectaltname(csr) or () subjectaltname = pkcs10.get_subjectaltname(csr) or ()
except (NSPRError, PyAsn1Error), e: except (NSPRError, PyAsn1Error) as e:
raise errors.CertificateOperationError( raise errors.CertificateOperationError(
error=_("Failure decoding Certificate Signing Request: %s") % e) error=_("Failure decoding Certificate Signing Request: %s") % e)
@ -613,7 +613,7 @@ class cert_show(VirtualCommand):
hostname = None hostname = None
try: try:
self.check_access() self.check_access()
except errors.ACIError, acierr: except errors.ACIError as acierr:
self.debug("Not granted by ACI to retrieve certificate, looking at principal") self.debug("Not granted by ACI to retrieve certificate, looking at principal")
bind_principal = getattr(context, 'principal') bind_principal = getattr(context, 'principal')
if not bind_principal.startswith('host/'): if not bind_principal.startswith('host/'):
@ -681,7 +681,7 @@ class cert_revoke(VirtualCommand):
hostname = None hostname = None
try: try:
self.check_access() self.check_access()
except errors.ACIError, acierr: except errors.ACIError as acierr:
self.debug("Not granted by ACI to revoke certificate, looking at principal") self.debug("Not granted by ACI to revoke certificate, looking at principal")
try: try:
# Let cert_show() handle verifying that the subject of the # Let cert_show() handle verifying that the subject of the

View File

@ -395,7 +395,7 @@ def _validate_bind_aci(ugettext, bind_acis):
try: try:
ip = CheckedIPAddress(bind_aci, parse_netmask=True, ip = CheckedIPAddress(bind_aci, parse_netmask=True,
allow_network=True, allow_loopback=True) allow_network=True, allow_loopback=True)
except (netaddr.AddrFormatError, ValueError), e: except (netaddr.AddrFormatError, ValueError) as e:
return unicode(e) return unicode(e)
except UnboundLocalError: except UnboundLocalError:
return _(u"invalid address format") return _(u"invalid address format")
@ -481,7 +481,7 @@ def _validate_nsec3param_record(ugettext, value):
try: try:
binascii.a2b_hex(salt) binascii.a2b_hex(salt)
except TypeError, e: except TypeError as e:
return _('salt value: %(err)s') % {'err': e} return _('salt value: %(err)s') % {'err': e}
return None return None
@ -575,7 +575,7 @@ def add_records_for_host_validation(option_name, host, domain, ip_addresses, che
for ip_address in ip_addresses: for ip_address in ip_addresses:
try: try:
ip = CheckedIPAddress(ip_address, match_local=False) ip = CheckedIPAddress(ip_address, match_local=False)
except Exception, e: except Exception as e:
raise errors.ValidationError(name=option_name, error=unicode(e)) raise errors.ValidationError(name=option_name, error=unicode(e))
if check_forward: if check_forward:
@ -977,7 +977,7 @@ class ForwardRecord(DNSRecord):
try: try:
add_records_for_host(keys[-1], keys[-2], record, add_records_for_host(keys[-1], keys[-2], record,
add_forward=False, add_reverse=True) add_forward=False, add_reverse=True)
except Exception, e: except Exception as e:
raise errors.NonFatalError( raise errors.NonFatalError(
reason=_('Cannot create reverse record for "%(value)s": %(exc)s') \ reason=_('Cannot create reverse record for "%(value)s": %(exc)s') \
% dict(value=record, exc=unicode(e))) % dict(value=record, exc=unicode(e)))
@ -2073,7 +2073,7 @@ class DNSZoneBase(LDAPObject):
permission_name = self.permission_name(zone) permission_name = self.permission_name(zone)
try: try:
api.Command['permission_del'](permission_name, force=True) api.Command['permission_del'](permission_name, force=True)
except errors.NotFound, e: except errors.NotFound as e:
if zone == DNSName.root: # special case root zone if zone == DNSName.root: # special case root zone
raise raise
# compatibility, older IPA versions which allows to create zone # compatibility, older IPA versions which allows to create zone
@ -3544,12 +3544,12 @@ class dnsrecord_add(LDAPCreate):
try: try:
idnsname = DNSName(kw['idnsname']) idnsname = DNSName(kw['idnsname'])
except Exception, e: except Exception as e:
raise errors.ValidationError(name='idnsname', error=unicode(e)) raise errors.ValidationError(name='idnsname', error=unicode(e))
try: try:
zonename = DNSName(kw['dnszoneidnsname']) zonename = DNSName(kw['dnszoneidnsname'])
except Exception, e: except Exception as e:
raise errors.ValidationError(name='dnszoneidnsname', error=unicode(e)) raise errors.ValidationError(name='dnszoneidnsname', error=unicode(e))
# check zone type # check zone type
@ -4181,7 +4181,7 @@ class dns_is_enabled(Command):
ent = ldap.find_entries(filter=self.filter, base_dn=self.base_dn) ent = ldap.find_entries(filter=self.filter, base_dn=self.base_dn)
if len(ent): if len(ent):
dns_enabled = True dns_enabled = True
except Exception, e: except Exception as e:
pass pass
return dict(result=dns_enabled, value=pkey_to_value(None, options)) return dict(result=dns_enabled, value=pkey_to_value(None, options))

View File

@ -520,7 +520,7 @@ class group_add_member(LDAPAddMember):
else: else:
try: try:
actual_sid = domain_validator.get_trusted_domain_object_sid(sid) actual_sid = domain_validator.get_trusted_domain_object_sid(sid)
except errors.PublicError, e: except errors.PublicError as e:
failed_sids.append((sid, e.strerror)) failed_sids.append((sid, e.strerror))
else: else:
sids.append(actual_sid) sids.append(actual_sid)
@ -577,7 +577,7 @@ class group_remove_member(LDAPRemoveMember):
else: else:
try: try:
actual_sid = domain_validator.get_trusted_domain_object_sid(sid) actual_sid = domain_validator.get_trusted_domain_object_sid(sid)
except errors.PublicError, e: except errors.PublicError as e:
failed_sids.append((sid, unicode(e))) failed_sids.append((sid, unicode(e)))
else: else:
sids.append(actual_sid) sids.append(actual_sid)

View File

@ -256,7 +256,7 @@ def validate_ipaddr(ugettext, ipaddr):
""" """
try: try:
CheckedIPAddress(ipaddr, match_local=False) CheckedIPAddress(ipaddr, match_local=False)
except Exception, e: except Exception as e:
return unicode(e) return unicode(e)
return None return None
@ -272,7 +272,7 @@ def normalize_hostname(hostname):
def _hostname_validator(ugettext, value): def _hostname_validator(ugettext, value):
try: try:
validate_hostname(value) validate_hostname(value)
except ValueError, e: except ValueError as e:
return _('invalid domain-name: %s') % unicode(e) return _('invalid domain-name: %s') % unicode(e)
return None return None
@ -674,7 +674,7 @@ class host_add(LDAPCreate):
del options['ip_address'] del options['ip_address']
update_sshfp_record(domain, unicode(parts[0]), entry_attrs) update_sshfp_record(domain, unicode(parts[0]), entry_attrs)
except Exception, e: except Exception as e:
exc = e exc = e
if options.get('random', False): if options.get('random', False):
try: try:

View File

@ -29,7 +29,7 @@ from ipalib.plugins.user import NO_UPG_MAGIC
if api.env.in_server and api.env.context in ['lite', 'server']: if api.env.in_server and api.env.context in ['lite', 'server']:
try: try:
from ipaserver.plugins.ldap2 import ldap2 from ipaserver.plugins.ldap2 import ldap2
except StandardError, e: except StandardError as e:
raise e raise e
from ipalib import _ from ipalib import _
from ipapython.dn import DN from ipapython.dn import DN
@ -176,11 +176,11 @@ def _pre_migrate_user(ldap, pkey, dn, entry_attrs, failed, config, ctx, **kwargs
api.log.warn('GID number %s of migrated user %s does not point to a known group.' \ api.log.warn('GID number %s of migrated user %s does not point to a known group.' \
% (entry_attrs['gidnumber'][0], pkey)) % (entry_attrs['gidnumber'][0], pkey))
invalid_gids.add(entry_attrs['gidnumber'][0]) invalid_gids.add(entry_attrs['gidnumber'][0])
except errors.SingleMatchExpected, e: except errors.SingleMatchExpected as e:
# GID number matched more groups, this should not happen # GID number matched more groups, this should not happen
api.log.warn('GID number %s of migrated user %s should match 1 group, but it matched %d groups' \ api.log.warn('GID number %s of migrated user %s should match 1 group, but it matched %d groups' \
% (entry_attrs['gidnumber'][0], pkey, e.found)) % (entry_attrs['gidnumber'][0], pkey, e.found))
except errors.LimitsExceeded, e: except errors.LimitsExceeded as e:
api.log.warn('Search limit exceeded searching for GID %s' % entry_attrs['gidnumber'][0]) api.log.warn('Search limit exceeded searching for GID %s' % entry_attrs['gidnumber'][0])
# We don't want to create a UPG so set the magic value in description # We don't want to create a UPG so set the magic value in description
@ -240,7 +240,7 @@ def _pre_migrate_user(ldap, pkey, dn, entry_attrs, failed, config, ctx, **kwargs
', convert it', pkey, value, type(value), attr) ', convert it', pkey, value, type(value), attr)
try: try:
value = DN(value) value = DN(value)
except ValueError, e: except ValueError as e:
api.log.warn('%s: skipping normalization of value %s of type %s ' api.log.warn('%s: skipping normalization of value %s of type %s '
'in attribute %s which could not be converted to DN: %s', 'in attribute %s which could not be converted to DN: %s',
pkey, value, type(value), attr, e) pkey, value, type(value), attr, e)
@ -331,7 +331,7 @@ def _pre_migrate_group(ldap, pkey, dn, entry_attrs, failed, config, ctx, **kwarg
for m in entry_attrs[member_attr]: for m in entry_attrs[member_attr]:
try: try:
m = DN(m) m = DN(m)
except ValueError, e: except ValueError as e:
# This should be impossible unless the remote server # This should be impossible unless the remote server
# doesn't enforce syntax checking. # doesn't enforce syntax checking.
api.log.error('Malformed DN %s: %s' % (m, e)) api.log.error('Malformed DN %s: %s' % (m, e))
@ -826,19 +826,19 @@ can use their Kerberos accounts.''')
) )
if not entry_attrs.dn: if not entry_attrs.dn:
continue continue
except errors.NotFound, e: except errors.NotFound as e:
failed[ldap_obj_name][pkey] = unicode(e.reason) failed[ldap_obj_name][pkey] = unicode(e.reason)
continue continue
try: try:
ldap.add_entry(entry_attrs) ldap.add_entry(entry_attrs)
except errors.ExecutionError, e: except errors.ExecutionError as e:
callback = self.migrate_objects[ldap_obj_name]['exc_callback'] callback = self.migrate_objects[ldap_obj_name]['exc_callback']
if callable(callback): if callable(callback):
try: try:
callback( callback(
ldap, entry_attrs.dn, entry_attrs, e, options) ldap, entry_attrs.dn, entry_attrs, e, options)
except errors.ExecutionError, e: except errors.ExecutionError as e:
failed[ldap_obj_name][pkey] = unicode(e) failed[ldap_obj_name][pkey] = unicode(e)
continue continue
else: else:
@ -916,7 +916,7 @@ can use their Kerberos accounts.''')
try: try:
ds_base_dn = DN(entries[0]['namingcontexts'][0]) ds_base_dn = DN(entries[0]['namingcontexts'][0])
assert isinstance(ds_base_dn, DN) assert isinstance(ds_base_dn, DN)
except (IndexError, KeyError), e: except (IndexError, KeyError) as e:
raise StandardError(str(e)) raise StandardError(str(e))
# migrate! # migrate!

View File

@ -90,7 +90,7 @@ class OTPTokenKey(Bytes):
if isinstance(value, unicode): if isinstance(value, unicode):
try: try:
value = base64.b32decode(value, True) value = base64.b32decode(value, True)
except TypeError, e: except TypeError as e:
raise ConversionError(name=self.name, index=index, error=str(e)) raise ConversionError(name=self.name, index=index, error=str(e))
return super(OTPTokenKey, self)._convert_scalar(value, index) return super(OTPTokenKey, self)._convert_scalar(value, index)

View File

@ -1002,7 +1002,7 @@ class permission_add(baseldap.LDAPCreate):
def post_callback(self, ldap, dn, entry, *keys, **options): def post_callback(self, ldap, dn, entry, *keys, **options):
try: try:
self.obj.add_aci(entry) self.obj.add_aci(entry)
except Exception, e: except Exception as e:
# Adding the ACI failed. # Adding the ACI failed.
# We want to be 100% sure the ACI is not there, so try to # We want to be 100% sure the ACI is not there, so try to
# remove it. (This is a no-op if the ACI was not added.) # remove it. (This is a no-op if the ACI was not added.)
@ -1185,7 +1185,7 @@ class permission_mod(baseldap.LDAPUpdate):
context.permision_moving_aci = True context.permision_moving_aci = True
try: try:
context.old_aci_info = self.obj.remove_aci(old_entry) context.old_aci_info = self.obj.remove_aci(old_entry)
except errors.NotFound, e: except errors.NotFound as e:
self.log.error('permission ACI not found: %s' % e) self.log.error('permission ACI not found: %s' % e)
# To pass data to postcallback, we currently need to use the context # To pass data to postcallback, we currently need to use the context

View File

@ -491,7 +491,7 @@ class pwpolicy_mod(LDAPUpdate):
self.api.Command.cosentry_mod( self.api.Command.cosentry_mod(
keys[-1], cospriority=options['cospriority'] keys[-1], cospriority=options['cospriority']
) )
except errors.EmptyModlist, e: except errors.EmptyModlist as e:
if len(entry_attrs) == 1: # cospriority only was passed if len(entry_attrs) == 1: # cospriority only was passed
raise e raise e
else: else:

View File

@ -76,7 +76,7 @@ def validate_radiusserver(ugettext, server):
try: try:
validate_hostname(server, check_fqdn=True, allow_underscore=True) validate_hostname(server, check_fqdn=True, allow_underscore=True)
except ValueError, e: except ValueError as e:
raise errors.ValidationError(name="ipatokenradiusserver", raise errors.ValidationError(name="ipatokenradiusserver",
error=e.message) error=e.message)

View File

@ -56,7 +56,7 @@ def _domain_name_normalizer(d):
def _domain_name_validator(ugettext, value): def _domain_name_validator(ugettext, value):
try: try:
validate_domain_name(value, allow_slash=False) validate_domain_name(value, allow_slash=False)
except ValueError, e: except ValueError as e:
return unicode(e) return unicode(e)

View File

@ -307,7 +307,7 @@ def check_required_principal(ldap, hostname, service):
""" """
try: try:
host_is_master(ldap, hostname) host_is_master(ldap, hostname)
except errors.ValidationError, e: except errors.ValidationError as e:
service_types = ['HTTP', 'ldap', 'DNS', 'dogtagldap'] service_types = ['HTTP', 'ldap', 'DNS', 'dogtagldap']
if service in service_types: if service in service_types:
raise errors.ValidationError(name='principal', error=_('This principal is required by the IPA master')) raise errors.ValidationError(name='principal', error=_('This principal is required by the IPA master'))

View File

@ -32,13 +32,13 @@ from time import sleep
try: try:
import pysss_murmur #pylint: disable=F0401 import pysss_murmur #pylint: disable=F0401
_murmur_installed = True _murmur_installed = True
except Exception, e: except Exception as e:
_murmur_installed = False _murmur_installed = False
try: try:
import pysss_nss_idmap #pylint: disable=F0401 import pysss_nss_idmap #pylint: disable=F0401
_nss_idmap_installed = True _nss_idmap_installed = True
except Exception, e: except Exception as e:
_nss_idmap_installed = False _nss_idmap_installed = False
if api.env.in_server and api.env.context in ['lite', 'server']: if api.env.in_server and api.env.context in ['lite', 'server']:
@ -365,7 +365,7 @@ def fetch_trusted_domains_over_dbus(myapi, log, forest_name):
intf = bus.get_object(DBUS_IFACE_TRUST,"/", follow_name_owner_changes=True) intf = bus.get_object(DBUS_IFACE_TRUST,"/", follow_name_owner_changes=True)
fetch_domains_method = intf.get_dbus_method('fetch_domains', dbus_interface=DBUS_IFACE_TRUST) fetch_domains_method = intf.get_dbus_method('fetch_domains', dbus_interface=DBUS_IFACE_TRUST)
(_ret, _stdout, _stderr) = fetch_domains_method(forest_name) (_ret, _stdout, _stderr) = fetch_domains_method(forest_name)
except dbus.DBusException, e: except dbus.DBusException as e:
log.error('Failed to call %(iface)s.fetch_domains helper.' log.error('Failed to call %(iface)s.fetch_domains helper.'
'DBus exception is %(exc)s.' % dict(iface=DBUS_IFACE_TRUST, exc=str(e))) 'DBus exception is %(exc)s.' % dict(iface=DBUS_IFACE_TRUST, exc=str(e)))
if _ret != 0: if _ret != 0:
@ -1173,7 +1173,7 @@ class trust_resolve(Command):
entry['name'] = [unicode(xlate[sid][pysss_nss_idmap.NAME_KEY])] entry['name'] = [unicode(xlate[sid][pysss_nss_idmap.NAME_KEY])]
entry['type'] = [idmap_type_string(xlate[sid][pysss_nss_idmap.TYPE_KEY])] entry['type'] = [idmap_type_string(xlate[sid][pysss_nss_idmap.TYPE_KEY])]
result.append(entry) result.append(entry)
except ValueError, e: except ValueError as e:
pass pass
return dict(result=result) return dict(result=result)

View File

@ -974,7 +974,7 @@ class user_status(LDAPQuery):
other_ldap = ldap2(self.api, ldap_uri='ldap://%s' % host) other_ldap = ldap2(self.api, ldap_uri='ldap://%s' % host)
try: try:
other_ldap.connect(ccache=os.environ['KRB5CCNAME']) other_ldap.connect(ccache=os.environ['KRB5CCNAME'])
except Exception, e: except Exception as e:
self.error("user_status: Connecting to %s failed with %s" % (host, str(e))) self.error("user_status: Connecting to %s failed with %s" % (host, str(e)))
newresult = {'dn': dn} newresult = {'dn': dn}
newresult['server'] = _("%(host)s failed: %(error)s") % dict(host=host, error=str(e)) newresult['server'] = _("%(host)s failed: %(error)s") % dict(host=host, error=str(e))
@ -994,7 +994,7 @@ class user_status(LDAPQuery):
continue continue
newtime = time.strptime(newresult[attr][0], '%Y%m%d%H%M%SZ') newtime = time.strptime(newresult[attr][0], '%Y%m%d%H%M%SZ')
newresult[attr][0] = unicode(time.strftime('%Y-%m-%dT%H:%M:%SZ', newtime)) newresult[attr][0] = unicode(time.strftime('%Y-%m-%dT%H:%M:%SZ', newtime))
except Exception, e: except Exception as e:
self.debug("time conversion failed with %s" % str(e)) self.debug("time conversion failed with %s" % str(e))
pass pass
newresult['server'] = host newresult['server'] = host
@ -1011,7 +1011,7 @@ class user_status(LDAPQuery):
count += 1 count += 1
except errors.NotFound: except errors.NotFound:
self.obj.handle_not_found(*keys) self.obj.handle_not_found(*keys)
except Exception, e: except Exception as e:
self.error("user_status: Retrieving status for %s failed with %s" % (dn, str(e))) self.error("user_status: Retrieving status for %s failed with %s" % (dn, str(e)))
newresult = {'dn': dn} newresult = {'dn': dn}
newresult['server'] = _("%(host)s failed") % dict(host=host) newresult['server'] = _("%(host)s failed") % dict(host=host)

View File

@ -715,7 +715,7 @@ class vault_add_internal(LDAPCreate):
try: try:
parent_dn = DN(*dn[1:]) parent_dn = DN(*dn[1:])
self.obj.create_container(parent_dn, owner_dn) self.obj.create_container(parent_dn, owner_dn)
except errors.DuplicateEntry, e: except errors.DuplicateEntry as e:
pass pass
entry_attrs['owner'] = owner_dn entry_attrs['owner'] = owner_dn

View File

@ -95,7 +95,7 @@ def update_persistent_client_session_data(principal, data):
try: try:
keyname = client_session_keyring_keyname(principal) keyname = client_session_keyring_keyname(principal)
except Exception, e: except Exception as e:
raise ValueError(str(e)) raise ValueError(str(e))
# kernel_keyring only raises ValueError (why??) # kernel_keyring only raises ValueError (why??)
@ -111,7 +111,7 @@ def read_persistent_client_session_data(principal):
try: try:
keyname = client_session_keyring_keyname(principal) keyname = client_session_keyring_keyname(principal)
except Exception, e: except Exception as e:
raise ValueError(str(e)) raise ValueError(str(e))
# kernel_keyring only raises ValueError (why??) # kernel_keyring only raises ValueError (why??)
@ -127,7 +127,7 @@ def delete_persistent_client_session_data(principal):
try: try:
keyname = client_session_keyring_keyname(principal) keyname = client_session_keyring_keyname(principal)
except Exception, e: except Exception as e:
raise ValueError(str(e)) raise ValueError(str(e))
# kernel_keyring only raises ValueError (why??) # kernel_keyring only raises ValueError (why??)
@ -384,7 +384,7 @@ def xml_loads(data, encoding='UTF-8'):
try: try:
(params, method) = loads(data) (params, method) = loads(data)
return (xml_unwrap(params), method) return (xml_unwrap(params), method)
except Fault, e: except Fault as e:
raise decode_fault(e) raise decode_fault(e)
@ -668,7 +668,7 @@ class KerbTransport(SSLTransport):
try: try:
session_cookie = Cookie.get_named_cookie_from_string(cookie_header, session_cookie = Cookie.get_named_cookie_from_string(cookie_header,
COOKIE_NAME, request_url) COOKIE_NAME, request_url)
except Exception, e: except Exception as e:
root_logger.error("unable to parse cookie header '%s': %s", cookie_header, e) root_logger.error("unable to parse cookie header '%s': %s", cookie_header, e)
return return
@ -679,7 +679,7 @@ class KerbTransport(SSLTransport):
root_logger.debug("storing cookie '%s' for principal %s", cookie_string, principal) root_logger.debug("storing cookie '%s' for principal %s", cookie_string, principal)
try: try:
update_persistent_client_session_data(principal, cookie_string) update_persistent_client_session_data(principal, cookie_string)
except Exception, e: except Exception as e:
# Not fatal, we just can't use the session cookie we were sent. # Not fatal, we just can't use the session cookie we were sent.
pass pass
@ -723,7 +723,7 @@ class RPCClient(Connectible):
try: try:
answers = resolver.query(name, rdatatype.SRV) answers = resolver.query(name, rdatatype.SRV)
except DNSException, e: except DNSException as e:
answers = [] answers = []
for answer in answers: for answer in answers:
@ -756,13 +756,13 @@ class RPCClient(Connectible):
# (possibly with more than one cookie). # (possibly with more than one cookie).
try: try:
cookie_string = read_persistent_client_session_data(principal) cookie_string = read_persistent_client_session_data(principal)
except Exception, e: except Exception as e:
return None return None
# Search for the session cookie within the cookie string # Search for the session cookie within the cookie string
try: try:
session_cookie = Cookie.get_named_cookie_from_string(cookie_string, COOKIE_NAME) session_cookie = Cookie.get_named_cookie_from_string(cookie_string, COOKIE_NAME)
except Exception, e: except Exception as e:
return None return None
return session_cookie return session_cookie
@ -805,17 +805,17 @@ class RPCClient(Connectible):
# Decide if we should send the cookie to the server # Decide if we should send the cookie to the server
try: try:
session_cookie.http_return_ok(original_url) session_cookie.http_return_ok(original_url)
except Cookie.Expired, e: except Cookie.Expired as e:
self.debug("deleting session data for principal '%s': %s", principal, e) self.debug("deleting session data for principal '%s': %s", principal, e)
try: try:
delete_persistent_client_session_data(principal) delete_persistent_client_session_data(principal)
except Exception, e: except Exception as e:
pass pass
return original_url return original_url
except Cookie.URLMismatch, e: except Cookie.URLMismatch as e:
self.debug("not sending session cookie, URL mismatch: %s", e) self.debug("not sending session cookie, URL mismatch: %s", e)
return original_url return original_url
except Exception, e: except Exception as e:
self.error("not sending session cookie, unknown error: %s", e) self.error("not sending session cookie, unknown error: %s", e)
return original_url return original_url
@ -872,7 +872,7 @@ class RPCClient(Connectible):
command = getattr(serverproxy, 'ping') command = getattr(serverproxy, 'ping')
try: try:
response = command([], {}) response = command([], {})
except Fault, e: except Fault as e:
e = decode_fault(e) e = decode_fault(e)
if e.faultCode in errors_by_code: if e.faultCode in errors_by_code:
error = errors_by_code[e.faultCode] error = errors_by_code[e.faultCode]
@ -885,23 +885,23 @@ class RPCClient(Connectible):
) )
# We don't care about the response, just that we got one # We don't care about the response, just that we got one
break break
except KerberosError, krberr: except KerberosError as krberr:
# kerberos error on one server is likely on all # kerberos error on one server is likely on all
raise errors.KerberosError(major=str(krberr), minor='') raise errors.KerberosError(major=str(krberr), minor='')
except ProtocolError, e: except ProtocolError as e:
if hasattr(context, 'session_cookie') and e.errcode == 401: if hasattr(context, 'session_cookie') and e.errcode == 401:
# Unauthorized. Remove the session and try again. # Unauthorized. Remove the session and try again.
delattr(context, 'session_cookie') delattr(context, 'session_cookie')
try: try:
delete_persistent_client_session_data(principal) delete_persistent_client_session_data(principal)
except Exception, e: except Exception as e:
# This shouldn't happen if we have a session but it isn't fatal. # This shouldn't happen if we have a session but it isn't fatal.
pass pass
return self.create_connection(ccache, verbose, fallback, delegate) return self.create_connection(ccache, verbose, fallback, delegate)
if not fallback: if not fallback:
raise raise
serverproxy = None serverproxy = None
except Exception, e: except Exception as e:
if not fallback: if not fallback:
raise raise
else: else:
@ -948,7 +948,7 @@ class RPCClient(Connectible):
params = [args, kw] params = [args, kw]
try: try:
return self._call_command(command, params) return self._call_command(command, params)
except Fault, e: except Fault as e:
e = decode_fault(e) e = decode_fault(e)
self.debug('Caught fault %d from server %s: %s', e.faultCode, self.debug('Caught fault %d from server %s: %s', e.faultCode,
server, e.faultString) server, e.faultString)
@ -960,9 +960,9 @@ class RPCClient(Connectible):
error=e.faultString, error=e.faultString,
server=server, server=server,
) )
except NSPRError, e: except NSPRError as e:
raise NetworkError(uri=server, error=str(e)) raise NetworkError(uri=server, error=str(e))
except ProtocolError, e: except ProtocolError as e:
# By catching a 401 here we can detect the case where we have # By catching a 401 here we can detect the case where we have
# a single IPA server and the session is invalid. Otherwise # a single IPA server and the session is invalid. Otherwise
# we always have to do a ping(). # we always have to do a ping().
@ -973,7 +973,7 @@ class RPCClient(Connectible):
try: try:
principal = getattr(context, 'principal', None) principal = getattr(context, 'principal', None)
delete_persistent_client_session_data(principal) delete_persistent_client_session_data(principal)
except Exception, e: except Exception as e:
# This shouldn't happen if we have a session but it isn't fatal. # This shouldn't happen if we have a session but it isn't fatal.
pass pass
@ -995,9 +995,9 @@ class RPCClient(Connectible):
current_conn.conn._ServerProxy__transport.dbdir = dbdir current_conn.conn._ServerProxy__transport.dbdir = dbdir
return self.forward(name, *args, **kw) return self.forward(name, *args, **kw)
raise NetworkError(uri=server, error=e.errmsg) raise NetworkError(uri=server, error=e.errmsg)
except socket.error, e: except socket.error as e:
raise NetworkError(uri=server, error=str(e)) raise NetworkError(uri=server, error=str(e))
except (OverflowError, TypeError), e: except (OverflowError, TypeError) as e:
raise XMLRPCMarshallError(error=str(e)) raise XMLRPCMarshallError(error=str(e))
@ -1049,7 +1049,7 @@ class JSONServerProxy(object):
try: try:
response = json_decode_binary(json.loads(response)) response = json_decode_binary(json.loads(response))
except ValueError, e: except ValueError as e:
raise JSONError(str(e)) raise JSONError(str(e))
if self.__verbose >= 2: if self.__verbose >= 2:

View File

@ -706,7 +706,7 @@ class SessionAuthManager(object):
for auth_mgr in self.auth_managers.values(): for auth_mgr in self.auth_managers.values():
try: try:
auth_mgr.logout(session_data) auth_mgr.logout(session_data)
except Exception, e: except Exception as e:
self.error('%s auth_mgr logout failed: %s', auth_mgr.name, e) self.error('%s auth_mgr logout failed: %s', auth_mgr.name, e)
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
@ -963,7 +963,7 @@ class MemcacheSessionManager(SessionManager):
try: try:
session_cookie = Cookie.get_named_cookie_from_string(cookie_header, self.session_cookie_name) session_cookie = Cookie.get_named_cookie_from_string(cookie_header, self.session_cookie_name)
except Exception, e: except Exception as e:
session_cookie = None session_cookie = None
if session_cookie: if session_cookie:
session_id = session_cookie.value session_id = session_cookie.value
@ -1272,7 +1272,7 @@ def release_ipa_ccache(ccache_name):
if os.path.exists(name): if os.path.exists(name):
try: try:
os.unlink(name) os.unlink(name)
except Exception, e: except Exception as e:
root_logger.error('unable to delete session ccache file "%s", %s', name, e) root_logger.error('unable to delete session ccache file "%s", %s', name, e)
else: else:
raise ValueError('ccache scheme "%s" unsupported (%s)', scheme, ccache_name) raise ValueError('ccache scheme "%s" unsupported (%s)', scheme, ccache_name)

View File

@ -83,7 +83,7 @@ def validate_host_dns(log, fqdn):
'IPA: found %d A records for %s: %s' % (len(answers), fqdn, 'IPA: found %d A records for %s: %s' % (len(answers), fqdn,
' '.join(str(answer) for answer in answers)) ' '.join(str(answer) for answer in answers))
) )
except DNSException, e: except DNSException as e:
log.debug( log.debug(
'IPA: DNS A record lookup failed for %s' % fqdn 'IPA: DNS A record lookup failed for %s' % fqdn
) )
@ -94,7 +94,7 @@ def validate_host_dns(log, fqdn):
'IPA: found %d AAAA records for %s: %s' % (len(answers), fqdn, 'IPA: found %d AAAA records for %s: %s' % (len(answers), fqdn,
' '.join(str(answer) for answer in answers)) ' '.join(str(answer) for answer in answers))
) )
except DNSException, e: except DNSException as e:
log.debug( log.debug(
'IPA: DNS AAAA record lookup failed for %s' % fqdn 'IPA: DNS AAAA record lookup failed for %s' % fqdn
) )
@ -186,7 +186,7 @@ def check_writable_file(filename):
else: else:
fp = open(filename, 'w') fp = open(filename, 'w')
fp.close() fp.close()
except (IOError, OSError), e: except (IOError, OSError) as e:
raise errors.FileError(reason=str(e)) raise errors.FileError(reason=str(e))
def normalize_zonemgr(zonemgr): def normalize_zonemgr(zonemgr):
@ -287,13 +287,13 @@ def normalize_sshpubkey(value):
def validate_sshpubkey(ugettext, value): def validate_sshpubkey(ugettext, value):
try: try:
SSHPublicKey(value) SSHPublicKey(value)
except ValueError, UnicodeDecodeError: except ValueError as UnicodeDecodeError:
return _('invalid SSH public key') return _('invalid SSH public key')
def validate_sshpubkey_no_options(ugettext, value): def validate_sshpubkey_no_options(ugettext, value):
try: try:
pubkey = SSHPublicKey(value) pubkey = SSHPublicKey(value)
except ValueError, UnicodeDecodeError: except ValueError as UnicodeDecodeError:
return _('invalid SSH public key') return _('invalid SSH public key')
if pubkey.has_options(): if pubkey.has_options():
@ -313,7 +313,7 @@ def convert_sshpubkey_post(ldap, dn, entry_attrs):
for pubkey in pubkeys: for pubkey in pubkeys:
try: try:
pubkey = SSHPublicKey(pubkey) pubkey = SSHPublicKey(pubkey)
except ValueError, UnicodeDecodeError: except ValueError as UnicodeDecodeError:
continue continue
fp = pubkey.fingerprint_hex_md5() fp = pubkey.fingerprint_hex_md5()
@ -525,7 +525,7 @@ def get_reverse_zone_default(ip_address):
def validate_rdn_param(ugettext, value): def validate_rdn_param(ugettext, value):
try: try:
rdn = RDN(value) rdn = RDN(value)
except Exception, e: except Exception as e:
return str(e) return str(e)
return None return None

View File

@ -285,7 +285,7 @@ def normalize_certificate(rawcert):
if util.isvalid_base64(rawcert): if util.isvalid_base64(rawcert):
try: try:
dercert = base64.b64decode(rawcert) dercert = base64.b64decode(rawcert)
except Exception, e: except Exception as e:
raise errors.Base64DecodeError(reason=str(e)) raise errors.Base64DecodeError(reason=str(e))
else: else:
dercert = rawcert dercert = rawcert
@ -326,7 +326,7 @@ def write_certificate(rawcert, filename):
fp = open(filename, 'w') fp = open(filename, 'w')
fp.write(make_pem(base64.b64encode(dercert))) fp.write(make_pem(base64.b64encode(dercert)))
fp.close() fp.close()
except (IOError, OSError), e: except (IOError, OSError) as e:
raise errors.FileError(reason=str(e)) raise errors.FileError(reason=str(e))
def write_certificate_list(rawcerts, filename): def write_certificate_list(rawcerts, filename):
@ -344,7 +344,7 @@ def write_certificate_list(rawcerts, filename):
cert = base64.b64encode(cert) cert = base64.b64encode(cert)
cert = make_pem(cert) cert = make_pem(cert)
f.write(cert + '\n') f.write(cert + '\n')
except (IOError, OSError), e: except (IOError, OSError) as e:
raise errors.FileError(reason=str(e)) raise errors.FileError(reason=str(e))
def verify_cert_subject(ldap, hostname, dercert): def verify_cert_subject(ldap, hostname, dercert):

View File

@ -164,7 +164,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
def reload_systemwide_ca_store(self): def reload_systemwide_ca_store(self):
try: try:
ipautil.run([paths.UPDATE_CA_TRUST]) ipautil.run([paths.UPDATE_CA_TRUST])
except CalledProcessError, e: except CalledProcessError as e:
root_logger.error( root_logger.error(
"Could not update systemwide CA trust database: %s", e) "Could not update systemwide CA trust database: %s", e)
return False return False
@ -178,7 +178,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
if os.path.exists(new_cacert_path): if os.path.exists(new_cacert_path):
try: try:
os.remove(new_cacert_path) os.remove(new_cacert_path)
except OSError, e: except OSError as e:
root_logger.error( root_logger.error(
"Could not remove %s: %s", new_cacert_path, e) "Could not remove %s: %s", new_cacert_path, e)
return False return False
@ -187,7 +187,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
try: try:
f = open(new_cacert_path, 'w') f = open(new_cacert_path, 'w')
except IOError, e: except IOError as e:
root_logger.info("Failed to open %s: %s" % (new_cacert_path, e)) root_logger.info("Failed to open %s: %s" % (new_cacert_path, e))
return False return False
@ -201,7 +201,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
issuer = x509.get_der_issuer(cert, x509.DER) issuer = x509.get_der_issuer(cert, x509.DER)
serial_number = x509.get_der_serial_number(cert, x509.DER) serial_number = x509.get_der_serial_number(cert, x509.DER)
public_key_info = x509.get_der_public_key_info(cert, x509.DER) public_key_info = x509.get_der_public_key_info(cert, x509.DER)
except (NSPRError, PyAsn1Error), e: except (NSPRError, PyAsn1Error) as e:
root_logger.warning( root_logger.warning(
"Failed to decode certificate \"%s\": %s", nickname, e) "Failed to decode certificate \"%s\": %s", nickname, e)
continue continue
@ -241,7 +241,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
ext_key_usage = {x509.EKU_PLACEHOLDER} ext_key_usage = {x509.EKU_PLACEHOLDER}
try: try:
ext_key_usage = x509.encode_ext_key_usage(ext_key_usage) ext_key_usage = x509.encode_ext_key_usage(ext_key_usage)
except PyAsn1Error, e: except PyAsn1Error as e:
root_logger.warning( root_logger.warning(
"Failed to encode extended key usage for \"%s\": %s", "Failed to encode extended key usage for \"%s\": %s",
nickname, e) nickname, e)
@ -278,7 +278,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
continue continue
try: try:
os.remove(new_cacert_path) os.remove(new_cacert_path)
except OSError, e: except OSError as e:
root_logger.error( root_logger.error(
"Could not remove %s: %s", new_cacert_path, e) "Could not remove %s: %s", new_cacert_path, e)
result = False result = False
@ -295,7 +295,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
old_hostname = socket.gethostname() old_hostname = socket.gethostname()
try: try:
ipautil.run([paths.BIN_HOSTNAME, hostname]) ipautil.run([paths.BIN_HOSTNAME, hostname])
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
print >>sys.stderr, ("Failed to set this machine hostname to " print >>sys.stderr, ("Failed to set this machine hostname to "
"%s (%s)." % (hostname, str(e))) "%s (%s)." % (hostname, str(e)))
@ -373,7 +373,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
if original_state != state: if original_state != state:
updated_vars[setting] = state updated_vars[setting] = state
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
log.error("Cannot get SELinux boolean '%s': %s", setting, e) log.error("Cannot get SELinux boolean '%s': %s", setting, e)
failed_vars[setting] = state failed_vars[setting] = state

View File

@ -178,7 +178,7 @@ class NSSDatabase(object):
args = args + ["-w", paths.DEV_STDIN] args = args + ["-w", paths.DEV_STDIN]
try: try:
ipautil.run(args, stdin=pkcs12_passwd) ipautil.run(args, stdin=pkcs12_passwd)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
if e.returncode == 17: if e.returncode == 17:
raise RuntimeError("incorrect password for pkcs#12 file %s" % raise RuntimeError("incorrect password for pkcs#12 file %s" %
pkcs12_filename) pkcs12_filename)
@ -390,7 +390,7 @@ class NSSDatabase(object):
try: try:
self.run_certutil(["-M", "-n", root_nickname, self.run_certutil(["-M", "-n", root_nickname,
"-t", trust_flags]) "-t", trust_flags])
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
raise RuntimeError( raise RuntimeError(
"Setting trust on %s failed" % root_nickname) "Setting trust on %s failed" % root_nickname)
@ -470,7 +470,7 @@ class NSSDatabase(object):
intended_usage = nss.certificateUsageSSLServer intended_usage = nss.certificateUsageSSLServer
try: try:
approved_usage = cert.verify_now(certdb, True, intended_usage) approved_usage = cert.verify_now(certdb, True, intended_usage)
except NSPRError, e: except NSPRError as e:
if e.errno != -8102: if e.errno != -8102:
raise ValueError(e.strerror) raise ValueError(e.strerror)
approved_usage = 0 approved_usage = 0
@ -504,7 +504,7 @@ class NSSDatabase(object):
intended_usage = nss.certificateUsageSSLCA intended_usage = nss.certificateUsageSSLCA
try: try:
approved_usage = cert.verify_now(certdb, True, intended_usage) approved_usage = cert.verify_now(certdb, True, intended_usage)
except NSPRError, e: except NSPRError as e:
if e.errno != -8102: # SEC_ERROR_INADEQUATE_KEY_USAGE if e.errno != -8102: # SEC_ERROR_INADEQUATE_KEY_USAGE
raise ValueError(e.strerror) raise ValueError(e.strerror)
approved_usage = 0 approved_usage = 0

View File

@ -212,7 +212,7 @@ def get_request_value(request_id, directive):
""" """
try: try:
request = _get_request(dict(nickname=request_id)) request = _get_request(dict(nickname=request_id))
except RuntimeError, e: except RuntimeError as e:
root_logger.error('Failed to get request: %s' % e) root_logger.error('Failed to get request: %s' % e)
raise raise
if request: if request:
@ -240,7 +240,7 @@ def get_request_id(criteria):
""" """
try: try:
request = _get_request(criteria) request = _get_request(criteria)
except RuntimeError, e: except RuntimeError as e:
root_logger.error('Failed to get request: %s' % e) root_logger.error('Failed to get request: %s' % e)
raise raise
if request: if request:
@ -270,7 +270,7 @@ def add_request_value(request_id, directive, value):
""" """
try: try:
request = _get_request({'nickname': request_id}) request = _get_request({'nickname': request_id})
except RuntimeError, e: except RuntimeError as e:
root_logger.error('Failed to get request: %s' % e) root_logger.error('Failed to get request: %s' % e)
raise raise
if request: if request:
@ -356,7 +356,7 @@ def start_tracking(nickname, secdir, password_file=None, command=None):
if result[0]: if result[0]:
request = _cm_dbus_object(cm.bus, cm, result[1], DBUS_CM_REQUEST_IF, request = _cm_dbus_object(cm.bus, cm, result[1], DBUS_CM_REQUEST_IF,
DBUS_CM_IF, True) DBUS_CM_IF, True)
except TypeError, e: except TypeError as e:
root_logger.error('Failed to add new request.') root_logger.error('Failed to add new request.')
raise raise
return request.prop_if.Get(DBUS_CM_REQUEST_IF, 'nickname') return request.prop_if.Get(DBUS_CM_REQUEST_IF, 'nickname')
@ -378,7 +378,7 @@ def stop_tracking(secdir, request_id=None, nickname=None):
criteria['cert-nickname'] = nickname criteria['cert-nickname'] = nickname
try: try:
request = _get_request(criteria) request = _get_request(criteria)
except RuntimeError, e: except RuntimeError as e:
root_logger.error('Failed to get request: %s' % e) root_logger.error('Failed to get request: %s' % e)
raise raise
if request: if request:

View File

@ -64,7 +64,7 @@ def check_ip_option(option, opt, value):
def check_dn_option(option, opt, value): def check_dn_option(option, opt, value):
try: try:
return DN(value) return DN(value)
except Exception, e: except Exception as e:
raise OptionValueError("option %s: invalid DN: %s" % (opt, e)) raise OptionValueError("option %s: invalid DN: %s" % (opt, e))
class IPAOption(Option): class IPAOption(Option):

View File

@ -185,7 +185,7 @@ class Cookie(object):
try: try:
dt = datetime.datetime(*email.utils.parsedate(s)[0:6]) dt = datetime.datetime(*email.utils.parsedate(s)[0:6])
except Exception, e: except Exception as e:
raise ValueError("unable to parse expires datetime '%s': %s" % (s, e)) raise ValueError("unable to parse expires datetime '%s': %s" % (s, e))
return dt return dt
@ -594,7 +594,7 @@ class Cookie(object):
from ipalib.util import validate_domain_name from ipalib.util import validate_domain_name
try: try:
validate_domain_name(url_domain) validate_domain_name(url_domain)
except Exception, e: except Exception as e:
return False return False
if cookie_domain is None: if cookie_domain is None:

View File

@ -37,7 +37,7 @@ class DNSName(dns.name.Name):
labels = labels.labels labels = labels.labels
super(DNSName, self).__init__(labels) super(DNSName, self).__init__(labels)
except UnicodeError, e: except UnicodeError as e:
# dnspython bug, an invalid domain name returns the UnicodeError # dnspython bug, an invalid domain name returns the UnicodeError
# instead of a dns.exception # instead of a dns.exception
raise dns.exception.SyntaxError(e) raise dns.exception.SyntaxError(e)

View File

@ -163,7 +163,7 @@ def error_from_xml(doc, message_template):
item_node = doc.getElementsByTagName("Error") item_node = doc.getElementsByTagName("Error")
reason = item_node[0].childNodes[0].data reason = item_node[0].childNodes[0].data
return errors.RemoteRetrieveError(reason=reason) return errors.RemoteRetrieveError(reason=reason)
except Exception, e: except Exception as e:
return errors.RemoteRetrieveError(reason=message_template % e) return errors.RemoteRetrieveError(reason=message_template % e)
@ -332,7 +332,7 @@ def _httplib_request(
http_headers = res.msg.dict http_headers = res.msg.dict
http_body = res.read() http_body = res.read()
conn.close() conn.close()
except Exception, e: except Exception as e:
raise NetworkError(uri=uri, error=str(e)) raise NetworkError(uri=uri, error=str(e))
root_logger.debug('request status %d', http_status) root_logger.debug('request status %d', http_status)

View File

@ -168,7 +168,7 @@ class SchemaCache(object):
except ldap.SERVER_DOWN: except ldap.SERVER_DOWN:
raise errors.NetworkError(uri=url, raise errors.NetworkError(uri=url,
error=u'LDAP Server Down, unable to retrieve LDAP schema') error=u'LDAP Server Down, unable to retrieve LDAP schema')
except ldap.LDAPError, e: except ldap.LDAPError as e:
desc = e.args[0]['desc'].strip() desc = e.args[0]['desc'].strip()
info = e.args[0].get('info', '').strip() info = e.args[0].get('info', '').strip()
raise errors.DatabaseError(desc = u'uri=%s' % url, raise errors.DatabaseError(desc = u'uri=%s' % url,
@ -865,7 +865,7 @@ class LDAPClient(object):
return datetime.datetime.strptime(val, LDAP_GENERALIZED_TIME_FORMAT) return datetime.datetime.strptime(val, LDAP_GENERALIZED_TIME_FORMAT)
else: else:
return target_type(val) return target_type(val)
except Exception, e: except Exception as e:
msg = 'unable to convert the attribute %r value %r to type %s' % (attr, val, target_type) msg = 'unable to convert the attribute %r value %r to type %s' % (attr, val, target_type)
self.log.error(msg) self.log.error(msg)
raise ValueError(msg) raise ValueError(msg)
@ -927,7 +927,7 @@ class LDAPClient(object):
yield yield
except ldap.TIMEOUT: except ldap.TIMEOUT:
raise errors.DatabaseTimeout() raise errors.DatabaseTimeout()
except ldap.LDAPError, e: except ldap.LDAPError as e:
desc = e.args[0]['desc'].strip() desc = e.args[0]['desc'].strip()
info = e.args[0].get('info', '').strip() info = e.args[0].get('info', '').strip()
if arg_desc is not None: if arg_desc is not None:
@ -984,7 +984,7 @@ class LDAPClient(object):
raise errors.DatabaseError(desc=desc, info=info) raise errors.DatabaseError(desc=desc, info=info)
except ldap.AUTH_UNKNOWN: except ldap.AUTH_UNKNOWN:
raise errors.ACIError(info='%s (%s)' % (info,desc)) raise errors.ACIError(info='%s (%s)' % (info,desc))
except ldap.LDAPError, e: except ldap.LDAPError as e:
if 'NOT_ALLOWED_TO_DELEGATE' in info: if 'NOT_ALLOWED_TO_DELEGATE' in info:
raise errors.ACIError( raise errors.ACIError(
info="KDC returned NOT_ALLOWED_TO_DELEGATE") info="KDC returned NOT_ALLOWED_TO_DELEGATE")
@ -1354,7 +1354,7 @@ class LDAPClient(object):
break break
else: else:
cookie = '' cookie = ''
except ldap.LDAPError, e: except ldap.LDAPError as e:
# If paged search is in progress, try to cancel it # If paged search is in progress, try to cancel it
if paged_search and cookie: if paged_search and cookie:
sctrls = [SimplePagedResultsControl(0, 0, cookie)] sctrls = [SimplePagedResultsControl(0, 0, cookie)]
@ -1363,7 +1363,7 @@ class LDAPClient(object):
str(base_dn), scope, filter, attrs_list, str(base_dn), scope, filter, attrs_list,
serverctrls=sctrls, timeout=time_limit, serverctrls=sctrls, timeout=time_limit,
sizelimit=size_limit) sizelimit=size_limit)
except ldap.LDAPError, e: except ldap.LDAPError as e:
self.log.warning( self.log.warning(
"Error cancelling paged search: %s", e) "Error cancelling paged search: %s", e)
cookie = '' cookie = ''
@ -1630,7 +1630,7 @@ class IPAdmin(LDAPClient):
pw_name = pwd.getpwuid(os.geteuid()).pw_name pw_name = pwd.getpwuid(os.geteuid()).pw_name
self.do_external_bind(pw_name, timeout=timeout) self.do_external_bind(pw_name, timeout=timeout)
return return
except errors.NotFound, e: except errors.NotFound as e:
if autobind == AUTOBIND_ENABLED: if autobind == AUTOBIND_ENABLED:
# autobind was required and failed, raise # autobind was required and failed, raise
# exception that it failed # exception that it failed

View File

@ -803,7 +803,7 @@ def host_port_open(host, port, socket_type=socket.SOCK_STREAM, socket_timeout=No
s.recv(512) s.recv(512)
return True return True
except socket.error, e: except socket.error as e:
pass pass
finally: finally:
if s: if s:
@ -824,14 +824,14 @@ def bind_port_responder(port, socket_type=socket.SOCK_STREAM, socket_timeout=Non
try: try:
addr_infos = socket.getaddrinfo(host, port, family, socket_type, 0, addr_infos = socket.getaddrinfo(host, port, family, socket_type, 0,
socket.AI_PASSIVE) socket.AI_PASSIVE)
except socket.error, e: except socket.error as e:
last_socket_error = e last_socket_error = e
continue continue
for res in addr_infos: for res in addr_infos:
af, socktype, proto, canonname, sa = res af, socktype, proto, canonname, sa = res
try: try:
s = socket.socket(af, socktype, proto) s = socket.socket(af, socktype, proto)
except socket.error, e: except socket.error as e:
last_socket_error = e last_socket_error = e
s = None s = None
continue continue
@ -870,7 +870,7 @@ def bind_port_responder(port, socket_type=socket.SOCK_STREAM, socket_timeout=Non
# Timeout is expectable as it was requested by caller, raise # Timeout is expectable as it was requested by caller, raise
# the exception back to him # the exception back to him
raise raise
except socket.error, e: except socket.error as e:
last_socket_error = e last_socket_error = e
s.close() s.close()
s = None s = None
@ -1177,7 +1177,7 @@ def wait_for_open_socket(socket_name, timeout=0):
s.connect(socket_name) s.connect(socket_name)
s.close() s.close()
break break
except socket.error, e: except socket.error as e:
if e.errno in (2,111): # 111: Connection refused, 2: File not found if e.errno in (2,111): # 111: Connection refused, 2: File not found
if timeout and time.time() > op_timeout: # timeout exceeded if timeout and time.time() > op_timeout: # timeout exceeded
raise e raise e
@ -1298,7 +1298,7 @@ def restore_hostname(statestore):
if old_hostname is not None and old_hostname != system_hostname: if old_hostname is not None and old_hostname != system_hostname:
try: try:
run([paths.BIN_HOSTNAME, old_hostname]) run([paths.BIN_HOSTNAME, old_hostname])
except CalledProcessError, e: except CalledProcessError as e:
print >>sys.stderr, "Failed to set this machine hostname back to %s: %s" % (old_hostname, str(e)) print >>sys.stderr, "Failed to set this machine hostname back to %s: %s" % (old_hostname, str(e))

View File

@ -936,7 +936,7 @@ class LogManager(object):
if value is not None: if value is not None:
try: try:
level = parse_log_level(value) level = parse_log_level(value)
except Exception, e: except Exception as e:
raise ValueError("could not set %s (%s)" % (attr, e)) raise ValueError("could not set %s (%s)" % (attr, e))
setattr(self, attr, level) setattr(self, attr, level)
@ -1239,7 +1239,7 @@ class LogManager(object):
if level is not None: if level is not None:
try: try:
level = parse_log_level(level) level = parse_log_level(level)
except Exception, e: except Exception as e:
print >>sys.stderr, 'could not set handler log level "%s" (%s)' % (level, e) print >>sys.stderr, 'could not set handler log level "%s" (%s)' % (level, e)
level = None level = None
if level is None: if level is None:

View File

@ -59,7 +59,7 @@ def auth_certificate_callback(sock, check_sig, is_server, certdb):
# will be set to the error code matching the reason why the validation failed # will be set to the error code matching the reason why the validation failed
# and the strerror attribute will contain a string describing the reason. # and the strerror attribute will contain a string describing the reason.
approved_usage = cert.verify_now(certdb, check_sig, intended_usage, *pin_args) approved_usage = cert.verify_now(certdb, check_sig, intended_usage, *pin_args)
except Exception, e: except Exception as e:
root_logger.error('cert validation failed for "%s" (%s)', cert.subject, e.strerror) root_logger.error('cert validation failed for "%s" (%s)', cert.subject, e.strerror)
cert_is_valid = False cert_is_valid = False
return cert_is_valid return cert_is_valid
@ -88,7 +88,7 @@ def auth_certificate_callback(sock, check_sig, is_server, certdb):
try: try:
# If the cert fails validation it will raise an exception # If the cert fails validation it will raise an exception
cert_is_valid = cert.verify_hostname(hostname) cert_is_valid = cert.verify_hostname(hostname)
except Exception, e: except Exception as e:
root_logger.error('failed verifying socket hostname "%s" matches cert subject "%s" (%s)', root_logger.error('failed verifying socket hostname "%s" matches cert subject "%s" (%s)',
hostname, cert.subject, e.strerror) hostname, cert.subject, e.strerror)
cert_is_valid = False cert_is_valid = False
@ -159,7 +159,7 @@ class NSSAddressFamilyFallback(object):
self._create_socket() self._create_socket()
self.sock.connect(net_addr) self.sock.connect(net_addr)
return return
except Exception, e: except Exception as e:
root_logger.debug("Could not connect socket to %s, error: %s", root_logger.debug("Could not connect socket to %s, error: %s",
net_addr, str(e)) net_addr, str(e))
root_logger.debug("Try to continue with next family...") root_logger.debug("Try to continue with next family...")
@ -199,7 +199,7 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
ssl.clear_session_cache() ssl.clear_session_cache()
try: try:
nss.nss_shutdown() nss.nss_shutdown()
except NSPRError, e: except NSPRError as e:
if e.errno != error.SEC_ERROR_NOT_INITIALIZED: if e.errno != error.SEC_ERROR_NOT_INITIALIZED:
raise e raise e
@ -236,7 +236,7 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True) self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
try: try:
self.sock.set_ssl_version_range(self.tls_version_min, self.tls_version_max) self.sock.set_ssl_version_range(self.tls_version_min, self.tls_version_max)
except NSPRError, e: except NSPRError as e:
root_logger.error('Failed to set TLS range to %s, %s' % (self.tls_version_min, self.tls_version_max)) root_logger.error('Failed to set TLS range to %s, %s' % (self.tls_version_min, self.tls_version_max))
raise raise
self.sock.set_ssl_option(ssl_require_safe_negotiation, False) self.sock.set_ssl_option(ssl_require_safe_negotiation, False)
@ -289,7 +289,7 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
httplib.HTTPConnection.endheaders(self) httplib.HTTPConnection.endheaders(self)
else: else:
httplib.HTTPConnection.endheaders(self, message) httplib.HTTPConnection.endheaders(self, message)
except NSPRError, e: except NSPRError as e:
self.close() self.close()
raise e raise e

View File

@ -276,7 +276,7 @@ class FileStore:
try: try:
os.unlink(backup_path) os.unlink(backup_path)
except Exception, e: except Exception as e:
root_logger.error('Error removing %s: %s' % (backup_path, str(e))) root_logger.error('Error removing %s: %s' % (backup_path, str(e)))
del self.files[filename] del self.files[filename]

View File

@ -179,7 +179,7 @@ class DomainValidator(object):
self.sid = entry_attrs[self.ATTR_SID][0] self.sid = entry_attrs[self.ATTR_SID][0]
self.dn = entry_attrs.dn self.dn = entry_attrs.dn
self.domain = self.api.env.domain self.domain = self.api.env.domain
except errors.NotFound, e: except errors.NotFound as e:
return False return False
return True return True
@ -211,7 +211,7 @@ class DomainValidator(object):
trust_partner = entry[self.ATTR_TRUST_PARTNER][0] trust_partner = entry[self.ATTR_TRUST_PARTNER][0]
flatname_normalized = entry[self.ATTR_FLATNAME][0].lower() flatname_normalized = entry[self.ATTR_FLATNAME][0].lower()
trusted_sid = entry[self.ATTR_TRUSTED_SID][0] trusted_sid = entry[self.ATTR_TRUSTED_SID][0]
except KeyError, e: except KeyError as e:
# Some piece of trusted domain info in LDAP is missing # Some piece of trusted domain info in LDAP is missing
# Skip the domain, but leave log entry for investigation # Skip the domain, but leave log entry for investigation
api.log.warn("Trusted domain '%s' entry misses an " api.log.warn("Trusted domain '%s' entry misses an "
@ -221,7 +221,7 @@ class DomainValidator(object):
result[trust_partner] = (flatname_normalized, result[trust_partner] = (flatname_normalized,
security.dom_sid(trusted_sid)) security.dom_sid(trusted_sid))
return result return result
except errors.NotFound, e: except errors.NotFound as e:
return [] return []
def set_trusted_domains(self): def set_trusted_domains(self):
@ -381,7 +381,7 @@ class DomainValidator(object):
try: try:
test_sid = security.dom_sid(sid) test_sid = security.dom_sid(sid)
return unicode(test_sid) return unicode(test_sid)
except TypeError, e: except TypeError as e:
raise errors.ValidationError(name=_('trusted domain object'), raise errors.ValidationError(name=_('trusted domain object'),
error= _('Trusted domain did not return a valid SID for the object')) error= _('Trusted domain did not return a valid SID for the object'))
@ -707,7 +707,7 @@ class DomainValidator(object):
basedn = ipautil.realm_to_suffix(info['dns_domain']) basedn = ipautil.realm_to_suffix(info['dns_domain'])
entries = conn.get_entries(basedn, scope, filter, attrs) entries = conn.get_entries(basedn, scope, filter, attrs)
except Exception, e: except Exception as e:
msg = "Search on AD DC {host}:{port} failed with: {err}"\ msg = "Search on AD DC {host}:{port} failed with: {err}"\
.format(host=host, port=str(port), err=str(e)) .format(host=host, port=str(port), err=str(e))
if quiet: if quiet:
@ -742,11 +742,11 @@ class DomainValidator(object):
result = None result = None
try: try:
result = netrc.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_GC | nbt.NBT_SERVER_CLOSEST) result = netrc.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_GC | nbt.NBT_SERVER_CLOSEST)
except RuntimeError, e: except RuntimeError as e:
try: try:
# If search of closest GC failed, attempt to find any one # If search of closest GC failed, attempt to find any one
result = netrc.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_GC) result = netrc.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_GC)
except RuntimeError, e: except RuntimeError as e:
finddc_error = e finddc_error = e
if not self._domains: if not self._domains:
@ -767,7 +767,7 @@ class DomainValidator(object):
try: try:
answers = resolver.query(gc_name, rdatatype.SRV) answers = resolver.query(gc_name, rdatatype.SRV)
except DNSException, e: except DNSException as e:
answers = [] answers = []
for answer in answers: for answer in answers:
@ -838,9 +838,9 @@ class TrustDomainInstance(object):
self._pipe = self.__gen_lsa_connection(binding) self._pipe = self.__gen_lsa_connection(binding)
if self._pipe and self._pipe.session_key: if self._pipe and self._pipe.session_key:
break break
except errors.ACIError, e: except errors.ACIError as e:
attempts = attempts + 1 attempts = attempts + 1
except RuntimeError, e: except RuntimeError as e:
# When session key is not available, we just skip this binding # When session key is not available, we just skip this binding
session_attempts = session_attempts + 1 session_attempts = session_attempts + 1
@ -880,7 +880,7 @@ class TrustDomainInstance(object):
result = netrc.finddc(domain=remote_host, flags=flags) result = netrc.finddc(domain=remote_host, flags=flags)
else: else:
result = netrc.finddc(address=remote_host, flags=flags) result = netrc.finddc(address=remote_host, flags=flags)
except RuntimeError, e: except RuntimeError as e:
raise assess_dcerpc_exception(message=str(e)) raise assess_dcerpc_exception(message=str(e))
if not result: if not result:
@ -902,11 +902,11 @@ class TrustDomainInstance(object):
(objtype, res) = conn.search_s('', _ldap.SCOPE_BASE)[0] (objtype, res) = conn.search_s('', _ldap.SCOPE_BASE)[0]
search_result = res['defaultNamingContext'][0] search_result = res['defaultNamingContext'][0]
self.info['dns_hostname'] = res['dnsHostName'][0] self.info['dns_hostname'] = res['dnsHostName'][0]
except _ldap.LDAPError, e: except _ldap.LDAPError as e:
root_logger.error( root_logger.error(
"LDAP error when connecting to %(host)s: %(error)s" % "LDAP error when connecting to %(host)s: %(error)s" %
dict(host=unicode(result.pdc_name), error=str(e))) dict(host=unicode(result.pdc_name), error=str(e)))
except KeyError, e: except KeyError as e:
root_logger.error("KeyError: {err}, LDAP entry from {host} " root_logger.error("KeyError: {err}, LDAP entry from {host} "
"returned malformed. Your DNS might be " "returned malformed. Your DNS might be "
"misconfigured." "misconfigured."
@ -1035,7 +1035,7 @@ class TrustDomainInstance(object):
ftinfo, 0) ftinfo, 0)
if collision_info: if collision_info:
root_logger.error("When setting forest trust information, got collision info back:\n%s" % (ndr_print(collision_info))) root_logger.error("When setting forest trust information, got collision info back:\n%s" % (ndr_print(collision_info)))
except RuntimeError, e: except RuntimeError as e:
# We can ignore the error here -- setting up name suffix routes may fail # We can ignore the error here -- setting up name suffix routes may fail
pass pass
@ -1091,7 +1091,7 @@ class TrustDomainInstance(object):
infoclass.enc_types |= security.KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96 infoclass.enc_types |= security.KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96
infoclass.enc_types |= security.KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96 infoclass.enc_types |= security.KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96
self._pipe.SetInformationTrustedDomain(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES, infoclass) self._pipe.SetInformationTrustedDomain(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES, infoclass)
except RuntimeError, e: except RuntimeError as e:
# We can ignore the error here -- changing enctypes is for # We can ignore the error here -- changing enctypes is for
# improved security but the trust will work with default values as # improved security but the trust will work with default values as
# well. In particular, the call may fail against Windows 2003 # well. In particular, the call may fail against Windows 2003
@ -1102,7 +1102,7 @@ class TrustDomainInstance(object):
info = self._pipe.QueryTrustedDomainInfo(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX) info = self._pipe.QueryTrustedDomainInfo(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX)
info.trust_attributes |= lsa.LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE info.trust_attributes |= lsa.LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE
self._pipe.SetInformationTrustedDomain(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX, info) self._pipe.SetInformationTrustedDomain(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX, info)
except RuntimeError, e: except RuntimeError as e:
root_logger.error('unable to set trust to transitive: %s' % (str(e))) root_logger.error('unable to set trust to transitive: %s' % (str(e)))
pass pass
if self.info['is_pdc']: if self.info['is_pdc']:
@ -1213,7 +1213,7 @@ def fetch_domains(api, mydomain, trustdomain, creds=None, server=None):
else: else:
result = netrc.finddc(domain=trustdomain, result = netrc.finddc(domain=trustdomain,
flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS) flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS)
except RuntimeError, e: except RuntimeError as e:
raise assess_dcerpc_exception(message=str(e)) raise assess_dcerpc_exception(message=str(e))
td.info['dc'] = unicode(result.pdc_dns_name) td.info['dc'] = unicode(result.pdc_dns_name)

View File

@ -71,7 +71,7 @@ def check_inst():
def ipa_smb_conf_exists(): def ipa_smb_conf_exists():
try: try:
conf_fd = open(paths.SMB_CONF, 'r') conf_fd = open(paths.SMB_CONF, 'r')
except IOError, err: except IOError as err:
if err.errno == errno.ENOENT: if err.errno == errno.ENOENT:
return False return False
@ -247,7 +247,7 @@ class ADTRUSTInstance(service.Service):
except errors.NotFound: except errors.NotFound:
try: try:
self._ldap_mod('default-trust-view.ldif', self.sub_dict) self._ldap_mod('default-trust-view.ldif', self.sub_dict)
except Exception, e: except Exception as e:
self.print_msg("Failed to add default trust view.") self.print_msg("Failed to add default trust view.")
raise e raise e
else: else:
@ -291,7 +291,7 @@ class ADTRUSTInstance(service.Service):
except errors.NotFound: except errors.NotFound:
try: try:
self._ldap_mod('default-smb-group.ldif', self.sub_dict) self._ldap_mod('default-smb-group.ldif', self.sub_dict)
except Exception, e: except Exception as e:
self.print_msg("Failed to add fallback group.") self.print_msg("Failed to add fallback group.")
raise e raise e
@ -358,7 +358,7 @@ class ADTRUSTInstance(service.Service):
str(self.rid_base)), str(self.rid_base)),
(ldap.MOD_ADD, "ipaSecondaryBaseRID", (ldap.MOD_ADD, "ipaSecondaryBaseRID",
str(self.secondary_rid_base))]) str(self.secondary_rid_base))])
except ldap.CONSTRAINT_VIOLATION, e: except ldap.CONSTRAINT_VIOLATION as e:
self.print_msg("Failed to add RID bases to the local range " self.print_msg("Failed to add RID bases to the local range "
"object:\n %s" % e[0]['info']) "object:\n %s" % e[0]['info'])
raise RuntimeError("Constraint violation.\n") raise RuntimeError("Constraint violation.\n")
@ -401,7 +401,7 @@ class ADTRUSTInstance(service.Service):
except errors.NotFound: except errors.NotFound:
try: try:
name = new_dn[1].attr name = new_dn[1].attr
except Exception, e: except Exception as e:
self.print_msg('Cannot extract RDN attribute value from "%s": %s' % \ self.print_msg('Cannot extract RDN attribute value from "%s": %s' % \
(new_dn, e)) (new_dn, e))
return return
@ -518,7 +518,7 @@ class ADTRUSTInstance(service.Service):
# adtrustinstance is managed # adtrustinstance is managed
# That's fine, we we'll re-extract the key again. # That's fine, we we'll re-extract the key again.
pass pass
except Exception, e: except Exception as e:
self.print_msg("Cannot add CIFS service: %s" % e) self.print_msg("Cannot add CIFS service: %s" % e)
self.clean_samba_keytab() self.clean_samba_keytab()
@ -536,7 +536,7 @@ class ADTRUSTInstance(service.Service):
try: try:
ipautil.run(["ipa-rmkeytab", "--principal", self.cifs_principal, ipautil.run(["ipa-rmkeytab", "--principal", self.cifs_principal,
"-k", self.samba_keytab]) "-k", self.samba_keytab])
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
if e.returncode != 5: if e.returncode != 5:
root_logger.critical("Failed to remove old key for %s" root_logger.critical("Failed to remove old key for %s"
% self.cifs_principal) % self.cifs_principal)
@ -653,7 +653,7 @@ class ADTRUSTInstance(service.Service):
try: try:
krb5conf = open(paths.KRB5_CONF, 'r') krb5conf = open(paths.KRB5_CONF, 'r')
except IOError, e: except IOError as e:
self.print_msg("Cannot open /etc/krb5.conf (%s)\n" % str(e)) self.print_msg("Cannot open /etc/krb5.conf (%s)\n" % str(e))
return return
@ -689,7 +689,7 @@ class ADTRUSTInstance(service.Service):
# SRV records for _msdcs # SRV records for _msdcs
self.cifs_hosts.append(fqdn.split(".")[0]) self.cifs_hosts.append(fqdn.split(".")[0])
except Exception, e: except Exception as e:
root_logger.critical("Checking replicas for cifs principals failed with error '%s'" % e) root_logger.critical("Checking replicas for cifs principals failed with error '%s'" % e)
def __enable_compat_tree(self): def __enable_compat_tree(self):
@ -703,7 +703,7 @@ class ADTRUSTInstance(service.Service):
if not(config[1] in lookup_nsswitch): if not(config[1] in lookup_nsswitch):
current[lookup_nsswitch_name] = [config[1]] current[lookup_nsswitch_name] = [config[1]]
self.admin_conn.update_entry(current) self.admin_conn.update_entry(current)
except Exception, e: except Exception as e:
root_logger.critical("Enabling nsswitch support in slapi-nis failed with error '%s'" % e) root_logger.critical("Enabling nsswitch support in slapi-nis failed with error '%s'" % e)
def __enable_and_start_oddjobd(self): def __enable_and_start_oddjobd(self):
@ -740,13 +740,13 @@ class ADTRUSTInstance(service.Service):
try: try:
self.ldap_enable('ADTRUST', self.fqdn, self.dm_password, \ self.ldap_enable('ADTRUST', self.fqdn, self.dm_password, \
self.suffix) self.suffix)
except (ldap.ALREADY_EXISTS, errors.DuplicateEntry), e: except (ldap.ALREADY_EXISTS, errors.DuplicateEntry) as e:
root_logger.info("ADTRUST Service startup entry already exists.") root_logger.info("ADTRUST Service startup entry already exists.")
try: try:
self.ldap_enable('EXTID', self.fqdn, self.dm_password, \ self.ldap_enable('EXTID', self.fqdn, self.dm_password, \
self.suffix) self.suffix)
except (ldap.ALREADY_EXISTS, errors.DuplicateEntry), e: except (ldap.ALREADY_EXISTS, errors.DuplicateEntry) as e:
root_logger.info("EXTID Service startup entry already exists.") root_logger.info("EXTID Service startup entry already exists.")
def __setup_sub_dict(self): def __setup_sub_dict(self):

View File

@ -392,7 +392,7 @@ def zonemgr_callback(option, opt_str, value, parser):
encoding = 'utf-8' encoding = 'utf-8'
value = value.decode(encoding) value = value.decode(encoding)
validate_zonemgr_str(value) validate_zonemgr_str(value)
except ValueError, e: except ValueError as e:
# FIXME we can do this in better way # FIXME we can do this in better way
# https://fedorahosted.org/freeipa/ticket/4804 # https://fedorahosted.org/freeipa/ticket/4804
# decode to proper stderr encoding # decode to proper stderr encoding
@ -935,7 +935,7 @@ class BindInstance(service.Service):
self.admin_conn.modify_s(dns_group, mod) self.admin_conn.modify_s(dns_group, mod)
except ldap.TYPE_OR_VALUE_EXISTS: except ldap.TYPE_OR_VALUE_EXISTS:
pass pass
except Exception, e: except Exception as e:
root_logger.critical("Could not modify principal's %s entry: %s" \ root_logger.critical("Could not modify principal's %s entry: %s" \
% (dns_principal, str(e))) % (dns_principal, str(e)))
raise raise
@ -948,7 +948,7 @@ class BindInstance(service.Service):
(ldap.MOD_REPLACE, 'nsLookThroughLimit', '-1')] (ldap.MOD_REPLACE, 'nsLookThroughLimit', '-1')]
try: try:
self.admin_conn.modify_s(dns_principal, mod) self.admin_conn.modify_s(dns_principal, mod)
except Exception, e: except Exception as e:
root_logger.critical("Could not set principal's %s LDAP limits: %s" \ root_logger.critical("Could not set principal's %s LDAP limits: %s" \
% (dns_principal, str(e))) % (dns_principal, str(e)))
raise raise
@ -1180,7 +1180,7 @@ class BindInstance(service.Service):
for f in [NAMED_CONF, RESOLV_CONF]: for f in [NAMED_CONF, RESOLV_CONF]:
try: try:
self.fstore.restore_file(f) self.fstore.restore_file(f)
except ValueError, error: except ValueError as error:
root_logger.debug(error) root_logger.debug(error)
pass pass

View File

@ -248,7 +248,7 @@ def install_step_1(standalone, replica_config, options):
str(dogtag_constants.DOGTAG_VERSION)) str(dogtag_constants.DOGTAG_VERSION))
with open(paths.IPA_DEFAULT_CONF, 'w') as f: with open(paths.IPA_DEFAULT_CONF, 'w') as f:
parser.write(f) parser.write(f)
except IOError, e: except IOError as e:
print "Failed to update /etc/ipa/default.conf" print "Failed to update /etc/ipa/default.conf"
root_logger.error(str(e)) root_logger.error(str(e))
sys.exit(1) sys.exit(1)

View File

@ -106,7 +106,7 @@ def get_preop_pin(instance_root, instance_name):
# read the config file and get the preop pin # read the config file and get the preop pin
try: try:
f = open(filename) f = open(filename)
except IOError, e: except IOError as e:
root_logger.error("Cannot open configuration file." + str(e)) root_logger.error("Cannot open configuration file." + str(e))
raise e raise e
data = f.read() data = f.read()
@ -752,7 +752,7 @@ class CAInstance(DogtagInstance):
nolog = (self.admin_password, self.dm_password,) nolog = (self.admin_password, self.dm_password,)
ipautil.run(args, env={'PKI_HOSTNAME':self.fqdn}, nolog=nolog) ipautil.run(args, env={'PKI_HOSTNAME':self.fqdn}, nolog=nolog)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.handle_setup_error(e) self.handle_setup_error(e)
if self.external == 1: if self.external == 1:
@ -770,7 +770,7 @@ class CAInstance(DogtagInstance):
def backup_config(self): def backup_config(self):
try: try:
backup_config(self.dogtag_constants) backup_config(self.dogtag_constants)
except Exception, e: except Exception as e:
root_logger.warning("Failed to backup CS.cfg: %s", e) root_logger.warning("Failed to backup CS.cfg: %s", e)
def __disable_nonce(self): def __disable_nonce(self):
@ -976,7 +976,7 @@ class CAInstance(DogtagInstance):
try: try:
return dogtag.get_ca_certchain(ca_host=self.fqdn, return dogtag.get_ca_certchain(ca_host=self.fqdn,
dogtag_constants=self.dogtag_constants) dogtag_constants=self.dogtag_constants)
except Exception, e: except Exception as e:
raise RuntimeError("Unable to retrieve CA chain: %s" % str(e)) raise RuntimeError("Unable to retrieve CA chain: %s" % str(e))
def __create_ca_agent_pkcs12(self): def __create_ca_agent_pkcs12(self):
@ -1194,7 +1194,7 @@ class CAInstance(DogtagInstance):
"-pki_instance_name=%s" % "-pki_instance_name=%s" %
self.dogtag_constants.PKI_INSTANCE_NAME, self.dogtag_constants.PKI_INSTANCE_NAME,
"--force"]) "--force"])
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.log.critical("failed to uninstall CA instance %s", e) self.log.critical("failed to uninstall CA instance %s", e)
self.restore_state("installed") self.restore_state("installed")
@ -1234,7 +1234,7 @@ class CAInstance(DogtagInstance):
for f in get_crl_files(): for f in get_crl_files():
self.log.debug("Remove %s", f) self.log.debug("Remove %s", f)
installutils.remove_file(f) installutils.remove_file(f)
except OSError, e: except OSError as e:
self.log.warning("Error while removing old CRL files: %s", e) self.log.warning("Error while removing old CRL files: %s", e)
# remove CRL directory # remove CRL directory
@ -1242,7 +1242,7 @@ class CAInstance(DogtagInstance):
if os.path.exists(self.dogtag_constants.CRL_PUBLISH_PATH): if os.path.exists(self.dogtag_constants.CRL_PUBLISH_PATH):
try: try:
shutil.rmtree(self.dogtag_constants.CRL_PUBLISH_PATH) shutil.rmtree(self.dogtag_constants.CRL_PUBLISH_PATH)
except OSError, e: except OSError as e:
self.log.warning("Error while removing CRL publish " self.log.warning("Error while removing CRL publish "
"directory: %s", e) "directory: %s", e)
@ -1294,7 +1294,7 @@ class CAInstance(DogtagInstance):
secdir=paths.HTTPD_ALIAS_DIR, secdir=paths.HTTPD_ALIAS_DIR,
pre_command=None, pre_command=None,
post_command='renew_ra_cert') post_command='renew_ra_cert')
except RuntimeError, e: except RuntimeError as e:
self.log.error( self.log.error(
"certmonger failed to start tracking certificate: %s", e) "certmonger failed to start tracking certificate: %s", e)
@ -1305,7 +1305,7 @@ class CAInstance(DogtagInstance):
try: try:
certmonger.stop_tracking(paths.HTTPD_ALIAS_DIR, nickname='ipaCert') certmonger.stop_tracking(paths.HTTPD_ALIAS_DIR, nickname='ipaCert')
except RuntimeError, e: except RuntimeError as e:
root_logger.error( root_logger.error(
"certmonger failed to stop tracking certificate: %s", e) "certmonger failed to stop tracking certificate: %s", e)
@ -1418,7 +1418,7 @@ class CAInstance(DogtagInstance):
try: try:
backup_config(dogtag_constants) backup_config(dogtag_constants)
except Exception, e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, "Failed to backup CS.cfg: %s" % e) syslog.syslog(syslog.LOG_ERR, "Failed to backup CS.cfg: %s" % e)
DogtagInstance.update_cert_cs_cfg( DogtagInstance.update_cert_cs_cfg(
@ -1613,7 +1613,7 @@ def update_people_entry(dercert):
conn.update_entry(entry) conn.update_entry(entry)
except errors.EmptyModlist: except errors.EmptyModlist:
pass pass
except Exception, e: except Exception as e:
syslog.syslog( syslog.syslog(
syslog.LOG_ERR, syslog.LOG_ERR,
'Updating entry %s failed: %s' % (str(entry.dn), e)) 'Updating entry %s failed: %s' % (str(entry.dn), e))
@ -1626,7 +1626,7 @@ def update_people_entry(dercert):
'Connection to %s failed, sleeping 30s' % dogtag_uri) 'Connection to %s failed, sleeping 30s' % dogtag_uri)
time.sleep(30) time.sleep(30)
attempts += 1 attempts += 1
except Exception, e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, 'Caught unhandled exception: %s' % e) syslog.syslog(syslog.LOG_ERR, 'Caught unhandled exception: %s' % e)
break break
finally: finally:

View File

@ -95,7 +95,7 @@ class CertDB(object):
self.subject_base = subject_base self.subject_base = subject_base
try: try:
self.cwd = os.getcwd() self.cwd = os.getcwd()
except OSError, e: except OSError as e:
raise RuntimeError("Unable to determine the current directory: %s" % str(e)) raise RuntimeError("Unable to determine the current directory: %s" % str(e))
if not subject_base: if not subject_base:
@ -300,7 +300,7 @@ class CertDB(object):
command = paths.CERTMONGER_COMMAND_TEMPLATE % (libpath, command) command = paths.CERTMONGER_COMMAND_TEMPLATE % (libpath, command)
try: try:
request_id = certmonger.start_tracking(nickname, self.secdir, password_file, command) request_id = certmonger.start_tracking(nickname, self.secdir, password_file, command)
except RuntimeError, e: except RuntimeError as e:
root_logger.error("certmonger failed starting to track certificate: %s" % str(e)) root_logger.error("certmonger failed starting to track certificate: %s" % str(e))
return return
@ -316,7 +316,7 @@ class CertDB(object):
""" """
try: try:
certmonger.stop_tracking(self.secdir, nickname=nickname) certmonger.stop_tracking(self.secdir, nickname=nickname)
except RuntimeError, e: except RuntimeError as e:
root_logger.error("certmonger failed to stop tracking certificate: %s" % str(e)) root_logger.error("certmonger failed to stop tracking certificate: %s" % str(e))
def create_server_cert(self, nickname, hostname, other_certdb=None, subject=None): def create_server_cert(self, nickname, hostname, other_certdb=None, subject=None):

View File

@ -442,7 +442,7 @@ class DNSKeySyncInstance(service.Service):
self.admin_conn.modify_s(dns_group, mod) self.admin_conn.modify_s(dns_group, mod)
except ldap.TYPE_OR_VALUE_EXISTS: except ldap.TYPE_OR_VALUE_EXISTS:
pass pass
except Exception, e: except Exception as e:
self.logger.critical("Could not modify principal's %s entry: %s" self.logger.critical("Could not modify principal's %s entry: %s"
% (dnssynckey_principal_dn, str(e))) % (dnssynckey_principal_dn, str(e)))
raise raise
@ -456,7 +456,7 @@ class DNSKeySyncInstance(service.Service):
(ldap.MOD_REPLACE, 'nsLookThroughLimit', '-1')] (ldap.MOD_REPLACE, 'nsLookThroughLimit', '-1')]
try: try:
self.admin_conn.modify_s(dnssynckey_principal_dn, mod) self.admin_conn.modify_s(dnssynckey_principal_dn, mod)
except Exception, e: except Exception as e:
self.logger.critical("Could not set principal's %s LDAP limits: %s" self.logger.critical("Could not set principal's %s LDAP limits: %s"
% (dnssynckey_principal_dn, str(e))) % (dnssynckey_principal_dn, str(e)))
raise raise
@ -485,7 +485,7 @@ class DNSKeySyncInstance(service.Service):
for f in [paths.SYSCONFIG_NAMED]: for f in [paths.SYSCONFIG_NAMED]:
try: try:
self.fstore.restore_file(f) self.fstore.restore_file(f)
except ValueError, error: except ValueError as error:
self.logger.debug(error) self.logger.debug(error)
pass pass

View File

@ -175,7 +175,7 @@ class DogtagInstance(service.Service):
try: try:
ipautil.run(args, nolog=nolog) ipautil.run(args, nolog=nolog)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.handle_setup_error(e) self.handle_setup_error(e)
def restart_instance(self): def restart_instance(self):
@ -270,7 +270,7 @@ class DogtagInstance(service.Service):
ipautil.run([paths.PKIDESTROY, "-i", ipautil.run([paths.PKIDESTROY, "-i",
self.dogtag_constants.PKI_INSTANCE_NAME, self.dogtag_constants.PKI_INSTANCE_NAME,
"-s", self.subsystem]) "-s", self.subsystem])
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.log.critical("failed to uninstall %s instance %s", self.log.critical("failed to uninstall %s instance %s",
self.subsystem, e) self.subsystem, e)
@ -310,7 +310,7 @@ class DogtagInstance(service.Service):
try: try:
return certmonger.get_pin('internal', return certmonger.get_pin('internal',
dogtag_constants=self.dogtag_constants) dogtag_constants=self.dogtag_constants)
except IOError, e: except IOError as e:
self.log.debug( self.log.debug(
'Unable to determine PIN for the Dogtag instance: %s', e) 'Unable to determine PIN for the Dogtag instance: %s', e)
raise RuntimeError(e) raise RuntimeError(e)
@ -330,7 +330,7 @@ class DogtagInstance(service.Service):
pre_command='stop_pkicad', pre_command='stop_pkicad',
post_command='renew_ca_cert "%s"' % nickname, post_command='renew_ca_cert "%s"' % nickname,
profile=profile) profile=profile)
except RuntimeError, e: except RuntimeError as e:
self.log.error( self.log.error(
"certmonger failed to start tracking certificate: %s", e) "certmonger failed to start tracking certificate: %s", e)
@ -350,7 +350,7 @@ class DogtagInstance(service.Service):
secdir=self.dogtag_constants.ALIAS_DIR, secdir=self.dogtag_constants.ALIAS_DIR,
pre_command='stop_pkicad', pre_command='stop_pkicad',
post_command='renew_ca_cert "%s"' % self.server_cert_name) post_command='renew_ca_cert "%s"' % self.server_cert_name)
except RuntimeError, e: except RuntimeError as e:
self.log.error( self.log.error(
"certmonger failed to start tracking certificate: %s" % e) "certmonger failed to start tracking certificate: %s" % e)
@ -373,7 +373,7 @@ class DogtagInstance(service.Service):
try: try:
certmonger.stop_tracking( certmonger.stop_tracking(
self.dogtag_constants.ALIAS_DIR, nickname=nickname) self.dogtag_constants.ALIAS_DIR, nickname=nickname)
except RuntimeError, e: except RuntimeError as e:
self.log.error( self.log.error(
"certmonger failed to stop tracking certificate: %s", e) "certmonger failed to stop tracking certificate: %s", e)

View File

@ -442,7 +442,7 @@ class DsInstance(service.Service):
try: try:
ipautil.run(args) ipautil.run(args)
root_logger.debug("completed creating ds instance") root_logger.debug("completed creating ds instance")
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
root_logger.critical("failed to create ds instance %s" % e) root_logger.critical("failed to create ds instance %s" % e)
# check for open port 389 from now on # check for open port 389 from now on
@ -452,7 +452,7 @@ class DsInstance(service.Service):
try: try:
self.__restart_instance() self.__restart_instance()
root_logger.debug("done restarting ds instance") root_logger.debug("done restarting ds instance")
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
print "failed to restart ds instance", e print "failed to restart ds instance", e
root_logger.debug("failed to restart ds instance %s" % e) root_logger.debug("failed to restart ds instance %s" % e)
inf_fd.close() inf_fd.close()
@ -484,9 +484,9 @@ class DsInstance(service.Service):
if not is_ds_running(instance): if not is_ds_running(instance):
root_logger.critical("Failed to restart the directory server. See the installation log for details.") root_logger.critical("Failed to restart the directory server. See the installation log for details.")
sys.exit(1) sys.exit(1)
except SystemExit, e: except SystemExit as e:
raise e raise e
except Exception, e: except Exception as e:
# TODO: roll back here? # TODO: roll back here?
root_logger.critical("Failed to restart the directory server (%s). See the installation log for details." % e) root_logger.critical("Failed to restart the directory server (%s). See the installation log for details." % e)
@ -771,7 +771,7 @@ class DsInstance(service.Service):
'LDAPTLS_CACERT':CACERT } 'LDAPTLS_CACERT':CACERT }
ipautil.run(args, env=env) ipautil.run(args, env=env)
root_logger.debug("ldappasswd done") root_logger.debug("ldappasswd done")
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
print "Unable to set admin password", e print "Unable to set admin password", e
root_logger.debug("Unable to set admin password %s" % e) root_logger.debug("Unable to set admin password %s" % e)
@ -793,7 +793,7 @@ class DsInstance(service.Service):
try: try:
self.fstore.restore_file(paths.LIMITS_CONF) self.fstore.restore_file(paths.LIMITS_CONF)
self.fstore.restore_file(paths.SYSCONFIG_DIRSRV) self.fstore.restore_file(paths.SYSCONFIG_DIRSRV)
except ValueError, error: except ValueError as error:
root_logger.debug(error) root_logger.debug(error)
pass pass
@ -829,7 +829,7 @@ class DsInstance(service.Service):
for ds_instance in get_ds_instances(): for ds_instance in get_ds_instances():
try: try:
services.knownservices.dirsrv.restart(ds_instance, wait=False) services.knownservices.dirsrv.restart(ds_instance, wait=False)
except Exception, e: except Exception as e:
root_logger.error('Unable to restart ds instance %s: %s', ds_instance, e) root_logger.error('Unable to restart ds instance %s: %s', ds_instance, e)
def stop_tracking_certificates(self, serverid=None): def stop_tracking_certificates(self, serverid=None):
@ -859,7 +859,7 @@ class DsInstance(service.Service):
root_logger.critical("The given CA cert file named [%s] could not be read" % root_logger.critical("The given CA cert file named [%s] could not be read" %
cacert_fname) cacert_fname)
return False return False
except OSError, e: except OSError as e:
root_logger.critical("The given CA cert file named [%s] could not be read: %s" % root_logger.critical("The given CA cert file named [%s] could not be read: %s" %
(cacert_fname, str(e))) (cacert_fname, str(e)))
return False return False
@ -876,7 +876,7 @@ class DsInstance(service.Service):
status = True status = True
try: try:
certdb.load_cacert(cacert_fname, 'C,,') certdb.load_cacert(cacert_fname, 'C,,')
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
root_logger.critical("Error importing CA cert file named [%s]: %s" % root_logger.critical("Error importing CA cert file named [%s]: %s" %
(cacert_fname, str(e))) (cacert_fname, str(e)))
status = False status = False
@ -1025,7 +1025,7 @@ class DsInstance(service.Service):
ret['result']['ipacertificatesubjectbase'][0]) ret['result']['ipacertificatesubjectbase'][0])
root_logger.debug( root_logger.debug(
'Found certificate subject base in DS: %s', subject_base) 'Found certificate subject base in DS: %s', subject_base)
except errors.PublicError, e: except errors.PublicError as e:
root_logger.error('Cannot connect to DS to find certificate ' root_logger.error('Cannot connect to DS to find certificate '
'subject base: %s', e) 'subject base: %s', e)
finally: finally:

View File

@ -60,7 +60,7 @@ def httpd_443_configured():
""" """
try: try:
(stdout, stderr, rc) = ipautil.run([paths.HTTPD, '-t', '-D', 'DUMP_VHOSTS']) (stdout, stderr, rc) = ipautil.run([paths.HTTPD, '-t', '-D', 'DUMP_VHOSTS'])
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
service.print_msg("WARNING: cannot check if port 443 is already configured") service.print_msg("WARNING: cannot check if port 443 is already configured")
service.print_msg("httpd returned error when checking: %s" % e) service.print_msg("httpd returned error when checking: %s" % e)
return False return False
@ -470,7 +470,7 @@ class HTTPInstance(service.Service):
for f in [paths.HTTPD_IPA_CONF, paths.HTTPD_SSL_CONF, paths.HTTPD_NSS_CONF]: for f in [paths.HTTPD_IPA_CONF, paths.HTTPD_SSL_CONF, paths.HTTPD_NSS_CONF]:
try: try:
self.fstore.restore_file(f) self.fstore.restore_file(f)
except ValueError, error: except ValueError as error:
root_logger.debug(error) root_logger.debug(error)
pass pass

View File

@ -144,7 +144,7 @@ def verify_fqdn(host_name, no_host_dns=False, local_hostname=True):
try: try:
# make sure that the host name meets the requirements in ipalib # make sure that the host name meets the requirements in ipalib
validate_hostname(host_name) validate_hostname(host_name)
except ValueError, e: except ValueError as e:
raise BadHostError("Invalid hostname '%s', %s" % (host_name, unicode(e))) raise BadHostError("Invalid hostname '%s', %s" % (host_name, unicode(e)))
if local_hostname: if local_hostname:
@ -157,7 +157,7 @@ def verify_fqdn(host_name, no_host_dns=False, local_hostname=True):
"Please check /etc/hosts or DNS name resolution" % (host_name, ex_name[0])) "Please check /etc/hosts or DNS name resolution" % (host_name, ex_name[0]))
except socket.gaierror: except socket.gaierror:
pass pass
except socket.error, e: except socket.error as e:
root_logger.debug('socket.gethostbyaddr() error: %d: %s' % (e.errno, e.strerror)) root_logger.debug('socket.gethostbyaddr() error: %d: %s' % (e.errno, e.strerror))
if no_host_dns: if no_host_dns:
@ -167,7 +167,7 @@ def verify_fqdn(host_name, no_host_dns=False, local_hostname=True):
try: try:
root_logger.debug('Search DNS for %s', host_name) root_logger.debug('Search DNS for %s', host_name)
hostaddr = socket.getaddrinfo(host_name, None) hostaddr = socket.getaddrinfo(host_name, None)
except Exception, e: except Exception as e:
root_logger.debug('Search failed: %s', e) root_logger.debug('Search failed: %s', e)
raise HostForwardLookupError("Unable to resolve host name, check /etc/hosts or DNS name resolution") raise HostForwardLookupError("Unable to resolve host name, check /etc/hosts or DNS name resolution")
@ -193,7 +193,7 @@ def verify_fqdn(host_name, no_host_dns=False, local_hostname=True):
try: try:
root_logger.debug('Check reverse address of %s', address) root_logger.debug('Check reverse address of %s', address)
revname = socket.gethostbyaddr(address)[0] revname = socket.gethostbyaddr(address)[0]
except Exception, e: except Exception as e:
root_logger.debug('Check failed: %s', e) root_logger.debug('Check failed: %s', e)
raise HostReverseLookupError( raise HostReverseLookupError(
"Unable to resolve the IP address %s to a host name, " "Unable to resolve the IP address %s to a host name, "
@ -256,7 +256,7 @@ def read_ip_address(host_name, fstore):
ip = ipautil.user_input("Please provide the IP address to be used for this host name", allow_empty = False) ip = ipautil.user_input("Please provide the IP address to be used for this host name", allow_empty = False)
try: try:
ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True) ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True)
except Exception, e: except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e) print "Error: Invalid IP Address %s: %s" % (ip, e)
continue continue
else: else:
@ -273,7 +273,7 @@ def read_ip_addresses(host_name, fstore):
break break
try: try:
ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True) ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True)
except Exception, e: except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e) print "Error: Invalid IP Address %s: %s" % (ip, e)
continue continue
ips.append(ip_parsed) ips.append(ip_parsed)
@ -291,7 +291,7 @@ def read_dns_forwarders():
break break
try: try:
ip_parsed = ipautil.CheckedIPAddress(ip, parse_netmask=False) ip_parsed = ipautil.CheckedIPAddress(ip, parse_netmask=False)
except Exception, e: except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e) print "Error: Invalid IP Address %s: %s" % (ip, e)
print "DNS forwarder %s not added." % ip print "DNS forwarder %s not added." % ip
continue continue
@ -333,7 +333,7 @@ def read_password(user, confirm=True, validate=True, retry=True, validator=_read
if validate: if validate:
try: try:
validator(pwd) validator(pwd)
except ValueError, e: except ValueError as e:
print str(e) print str(e)
pwd = None pwd = None
continue continue
@ -490,7 +490,7 @@ def get_server_ip_address(host_name, fstore, unattended, setup_dns, ip_addresses
for ha in hostaddr: for ha in hostaddr:
try: try:
ips.append(ipautil.CheckedIPAddress(ha, match_local=True)) ips.append(ipautil.CheckedIPAddress(ha, match_local=True))
except ValueError, e: except ValueError as e:
root_logger.warning("Invalid IP address %s for %s: %s", ha, host_name, unicode(e)) root_logger.warning("Invalid IP address %s for %s: %s", ha, host_name, unicode(e))
if not ips and not ip_addresses: if not ips and not ip_addresses:
@ -583,7 +583,7 @@ def read_replica_info_dogtag_port(config_dir):
with open(portfile) as fd: with open(portfile) as fd:
try: try:
dogtag_master_ds_port = int(fd.read()) dogtag_master_ds_port = int(fd.read())
except (ValueError, IOError), e: except (ValueError, IOError) as e:
root_logger.debug('Cannot parse dogtag DS port: %s', e) root_logger.debug('Cannot parse dogtag DS port: %s', e)
root_logger.debug('Default to %d', default_port) root_logger.debug('Default to %d', default_port)
dogtag_master_ds_port = default_port dogtag_master_ds_port = default_port
@ -595,7 +595,7 @@ def create_replica_config(dirman_password, filename, options):
top_dir = None top_dir = None
try: try:
top_dir, dir = expand_replica_info(filename, dirman_password) top_dir, dir = expand_replica_info(filename, dirman_password)
except Exception, e: except Exception as e:
root_logger.error("Failed to decrypt or open the replica file.") root_logger.error("Failed to decrypt or open the replica file.")
print "ERROR: Failed to decrypt or open the replica file." print "ERROR: Failed to decrypt or open the replica file."
print "Verify you entered the correct Directory Manager password." print "Verify you entered the correct Directory Manager password."
@ -613,7 +613,7 @@ def create_replica_config(dirman_password, filename, options):
config.dirman_password = dirman_password config.dirman_password = dirman_password
try: try:
host = get_host_name(options.no_host_dns) host = get_host_name(options.no_host_dns)
except BadHostError, e: except BadHostError as e:
root_logger.error(str(e)) root_logger.error(str(e))
sys.exit(1) sys.exit(1)
if config.host_name != host: if config.host_name != host:
@ -659,7 +659,7 @@ def remove_file(filename):
try: try:
if os.path.lexists(filename): if os.path.lexists(filename):
os.unlink(filename) os.unlink(filename)
except Exception, e: except Exception as e:
root_logger.error('Error removing %s: %s' % (filename, str(e))) root_logger.error('Error removing %s: %s' % (filename, str(e)))
@ -670,7 +670,7 @@ def rmtree(path):
try: try:
if os.path.exists(path): if os.path.exists(path):
shutil.rmtree(path) shutil.rmtree(path)
except Exception, e: except Exception as e:
root_logger.error('Error removing %s: %s' % (path, str(e))) root_logger.error('Error removing %s: %s' % (path, str(e)))
@ -720,7 +720,7 @@ def run_script(main_function, operation_name, log_file_name=None,
try: try:
try: try:
return_value = main_function() return_value = main_function()
except BaseException, e: except BaseException as e:
if isinstance(e, SystemExit) and (e.code is None or e.code == 0): if isinstance(e, SystemExit) and (e.code is None or e.code == 0):
# Not an error after all # Not an error after all
root_logger.info('The %s command was successful', root_logger.info('The %s command was successful',
@ -745,7 +745,7 @@ def run_script(main_function, operation_name, log_file_name=None,
operation_name) operation_name)
sys.exit(return_value) sys.exit(return_value)
except BaseException, error: except BaseException as error:
message, exitcode = handle_error(error, log_file_name) message, exitcode = handle_error(error, log_file_name)
if message: if message:
print >> sys.stderr, message print >> sys.stderr, message
@ -881,7 +881,7 @@ def load_pkcs12(cert_files, key_password, key_nickname, ca_cert_files,
for nickname in trust_chain[1:]: for nickname in trust_chain[1:]:
try: try:
nssdb.verify_ca_cert_validity(nickname) nssdb.verify_ca_cert_validity(nickname)
except ValueError, e: except ValueError as e:
raise ScriptError( raise ScriptError(
"CA certificate %s in %s is not valid: %s" % "CA certificate %s in %s is not valid: %s" %
(subject, ", ".join(cert_files), e)) (subject, ", ".join(cert_files), e))
@ -1020,7 +1020,7 @@ def load_external_cert(files, subject_base):
for nickname in trust_chain: for nickname in trust_chain:
try: try:
nssdb.verify_ca_cert_validity(nickname) nssdb.verify_ca_cert_validity(nickname)
except ValueError, e: except ValueError as e:
raise ScriptError( raise ScriptError(
"CA certificate %s in %s is not valid: %s" % "CA certificate %s in %s is not valid: %s" %
(subject, ", ".join(files), e)) (subject, ", ".join(files), e))

View File

@ -314,7 +314,7 @@ class Backup(admintool.AdminTool):
finally: finally:
try: try:
os.chdir(cwd) os.chdir(cwd)
except Exception, e: except Exception as e:
self.log.error('Cannot change directory to %s: %s' % (cwd, e)) self.log.error('Cannot change directory to %s: %s' % (cwd, e))
shutil.rmtree(self.top_dir) shutil.rmtree(self.top_dir)
@ -368,7 +368,7 @@ class Backup(admintool.AdminTool):
try: try:
pw_name = pwd.getpwuid(os.geteuid()).pw_name pw_name = pwd.getpwuid(os.geteuid()).pw_name
self._conn.do_external_bind(pw_name) self._conn.do_external_bind(pw_name)
except Exception, e: except Exception as e:
self.log.error("Unable to bind to LDAP server %s: %s" % self.log.error("Unable to bind to LDAP server %s: %s" %
(self._conn.host, e)) (self._conn.host, e))
@ -411,7 +411,7 @@ class Backup(admintool.AdminTool):
try: try:
conn.add_entry(ent) conn.add_entry(ent)
except Exception, e: except Exception as e:
raise admintool.ScriptError('Unable to add LDIF task: %s' raise admintool.ScriptError('Unable to add LDIF task: %s'
% e) % e)
@ -459,7 +459,7 @@ class Backup(admintool.AdminTool):
try: try:
conn.add_entry(ent) conn.add_entry(ent)
except Exception, e: except Exception as e:
raise admintool.ScriptError('Unable to to add backup task: %s' raise admintool.ScriptError('Unable to to add backup task: %s'
% e) % e)
@ -523,7 +523,7 @@ class Backup(admintool.AdminTool):
except errors.NetworkError: except errors.NetworkError:
self.log.critical( self.log.critical(
"Unable to obtain list of master services, continuing anyway") "Unable to obtain list of master services, continuing anyway")
except Exception, e: except Exception as e:
self.log.error("Failed to read services from '%s': %s" % self.log.error("Failed to read services from '%s': %s" %
(conn.host, e)) (conn.host, e))
else: else:

View File

@ -248,7 +248,7 @@ class CACertManage(admintool.AdminTool):
try: try:
tmpdb.add_cert(cert, 'IPA CA', 'C,,') tmpdb.add_cert(cert, 'IPA CA', 'C,,')
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Not compatible with the current CA certificate: %s" % e) "Not compatible with the current CA certificate: %s" % e)
@ -260,7 +260,7 @@ class CACertManage(admintool.AdminTool):
try: try:
tmpdb.verify_ca_cert_validity('IPA CA') tmpdb.verify_ca_cert_validity('IPA CA')
except ValueError, e: except ValueError as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Not a valid CA certificate: %s (visit " "Not a valid CA certificate: %s (visit "
"http://www.freeipa.org/page/Troubleshooting for " "http://www.freeipa.org/page/Troubleshooting for "
@ -330,10 +330,10 @@ class CACertManage(admintool.AdminTool):
try: try:
try: try:
nss_cert = x509.load_certificate_from_file(cert_filename) nss_cert = x509.load_certificate_from_file(cert_filename)
except IOError, e: except IOError as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Can't open \"%s\": %s" % (cert_filename, e)) "Can't open \"%s\": %s" % (cert_filename, e))
except (TypeError, NSPRError), e: except (TypeError, NSPRError) as e:
raise admintool.ScriptError("Not a valid certificate: %s" % e) raise admintool.ScriptError("Not a valid certificate: %s" % e)
subject = nss_cert.subject subject = nss_cert.subject
cert = nss_cert.der_data cert = nss_cert.der_data
@ -349,7 +349,7 @@ class CACertManage(admintool.AdminTool):
try: try:
tmpdb.verify_ca_cert_validity(nickname) tmpdb.verify_ca_cert_validity(nickname)
except ValueError, e: except ValueError as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Not a valid CA certificate: %s (visit " "Not a valid CA certificate: %s (visit "
"http://www.freeipa.org/page/Troubleshooting for " "http://www.freeipa.org/page/Troubleshooting for "
@ -363,7 +363,7 @@ class CACertManage(admintool.AdminTool):
try: try:
certstore.put_ca_cert_nss( certstore.put_ca_cert_nss(
self.conn, api.env.basedn, cert, nickname, trust_flags) self.conn, api.env.basedn, cert, nickname, trust_flags)
except ValueError, e: except ValueError as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Failed to install the certificate: %s" % e) "Failed to install the certificate: %s" % e)

View File

@ -76,7 +76,7 @@ class LDAPUpdater(admintool.AdminTool):
try: try:
installutils.check_server_configuration() installutils.check_server_configuration()
except RuntimeError, e: except RuntimeError as e:
print unicode(e) print unicode(e)
sys.exit(1) sys.exit(1)

View File

@ -211,7 +211,7 @@ class ReplicaPrepare(admintool.AdminTool):
except errors.LDAPError: except errors.LDAPError:
raise admintool.ScriptError( raise admintool.ScriptError(
"Unable to connect to LDAP server %s" % api.env.host) "Unable to connect to LDAP server %s" % api.env.host)
except errors.DatabaseError, e: except errors.DatabaseError as e:
raise admintool.ScriptError(e.desc) raise admintool.ScriptError(e.desc)
if not ca_enabled and not options.http_cert_files: if not ca_enabled and not options.http_cert_files:
@ -226,7 +226,7 @@ class ReplicaPrepare(admintool.AdminTool):
# Validate more options using the password # Validate more options using the password
try: try:
installutils.verify_fqdn(self.replica_fqdn, local_hostname=False) installutils.verify_fqdn(self.replica_fqdn, local_hostname=False)
except installutils.BadHostError, e: except installutils.BadHostError as e:
msg = str(e) msg = str(e)
if isinstance(e, installutils.HostLookupError): if isinstance(e, installutils.HostLookupError):
if not options.ip_addresses: if not options.ip_addresses:
@ -498,7 +498,7 @@ class ReplicaPrepare(admintool.AdminTool):
ip_address = str(ip) ip_address = str(ip)
try: try:
add_fwd_rr(domain, name, ip_address) add_fwd_rr(domain, name, ip_address)
except errors.PublicError, e: except errors.PublicError as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Could not add A/AAAA DNS record for the replica: %s" % e) "Could not add A/AAAA DNS record for the replica: %s" % e)
@ -506,7 +506,7 @@ class ReplicaPrepare(admintool.AdminTool):
reverse_zone = bindinstance.find_reverse_zone(ip) reverse_zone = bindinstance.find_reverse_zone(ip)
try: try:
add_ptr_rr(reverse_zone, ip_address, self.replica_fqdn) add_ptr_rr(reverse_zone, ip_address, self.replica_fqdn)
except errors.PublicError, e: except errors.PublicError as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Could not add PTR DNS record for the replica: %s" "Could not add PTR DNS record for the replica: %s"
% e) % e)
@ -565,7 +565,7 @@ class ReplicaPrepare(admintool.AdminTool):
self.log.debug('Copying %s to %s', source, dest_path) self.log.debug('Copying %s to %s', source, dest_path)
try: try:
shutil.copy(source, dest_path) shutil.copy(source, dest_path)
except IOError, e: except IOError as e:
raise admintool.ScriptError("File copy failed: %s" % e) raise admintool.ScriptError("File copy failed: %s" % e)
def remove_info_file(self, filename): def remove_info_file(self, filename):
@ -609,7 +609,7 @@ class ReplicaPrepare(admintool.AdminTool):
nickname, os.path.join(self.dir, "kdc.pem")) nickname, os.path.join(self.dir, "kdc.pem"))
else: else:
db.export_pkcs12(pkcs12_fname, passwd_fname, nickname) db.export_pkcs12(pkcs12_fname, passwd_fname, nickname)
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
self.log.info("error exporting Server certificate: %s", e) self.log.info("error exporting Server certificate: %s", e)
installutils.remove_file(pkcs12_fname) installutils.remove_file(pkcs12_fname)
installutils.remove_file(passwd_fname) installutils.remove_file(passwd_fname)
@ -625,7 +625,7 @@ class ReplicaPrepare(admintool.AdminTool):
orig_filename = passwd_fname + ".orig" orig_filename = passwd_fname + ".orig"
if ipautil.file_exists(orig_filename): if ipautil.file_exists(orig_filename):
installutils.remove_file(orig_filename) installutils.remove_file(orig_filename)
except errors.CertificateOperationError, e: except errors.CertificateOperationError as e:
raise admintool.ScriptError(str(e)) raise admintool.ScriptError(str(e))
def export_ra_pkcs12(self): def export_ra_pkcs12(self):

View File

@ -401,7 +401,7 @@ class Restore(admintool.AdminTool):
finally: finally:
try: try:
os.chdir(cwd) os.chdir(cwd)
except Exception, e: except Exception as e:
self.log.error('Cannot change directory to %s: %s' % (cwd, e)) self.log.error('Cannot change directory to %s: %s' % (cwd, e))
shutil.rmtree(self.top_dir) shutil.rmtree(self.top_dir)
@ -421,7 +421,7 @@ class Restore(admintool.AdminTool):
try: try:
pw_name = pwd.getpwuid(os.geteuid()).pw_name pw_name = pwd.getpwuid(os.geteuid()).pw_name
self._conn.do_external_bind(pw_name) self._conn.do_external_bind(pw_name)
except Exception, e: except Exception as e:
raise admintool.ScriptError('Unable to bind to LDAP server: %s' raise admintool.ScriptError('Unable to bind to LDAP server: %s'
% e) % e)
return self._conn return self._conn
@ -435,14 +435,14 @@ class Restore(admintool.AdminTool):
''' '''
try: try:
conn = self.get_connection() conn = self.get_connection()
except Exception, e : except Exception as e:
self.log.error('Unable to get connection, skipping disabling agreements: %s' % e) self.log.error('Unable to get connection, skipping disabling agreements: %s' % e)
return return
masters = [] masters = []
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn) dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
try: try:
entries = conn.get_entries(dn, conn.SCOPE_ONELEVEL) entries = conn.get_entries(dn, conn.SCOPE_ONELEVEL)
except Exception, e: except Exception as e:
raise admintool.ScriptError( raise admintool.ScriptError(
"Failed to read master data: %s" % e) "Failed to read master data: %s" % e)
else: else:
@ -455,7 +455,7 @@ class Restore(admintool.AdminTool):
try: try:
repl = ReplicationManager(api.env.realm, master, repl = ReplicationManager(api.env.realm, master,
self.dirman_password) self.dirman_password)
except Exception, e: except Exception as e:
self.log.critical("Unable to disable agreement on %s: %s" % (master, e)) self.log.critical("Unable to disable agreement on %s: %s" % (master, e))
continue continue
@ -480,7 +480,7 @@ class Restore(admintool.AdminTool):
try: try:
repl = get_cs_replication_manager(api.env.realm, master, repl = get_cs_replication_manager(api.env.realm, master,
self.dirman_password) self.dirman_password)
except Exception, e: except Exception as e:
self.log.critical("Unable to disable agreement on %s: %s" % (master, e)) self.log.critical("Unable to disable agreement on %s: %s" % (master, e))
continue continue
@ -537,7 +537,7 @@ class Restore(admintool.AdminTool):
try: try:
conn.add_entry(ent) conn.add_entry(ent)
except Exception, e: except Exception as e:
self.log.error("Unable to bind to LDAP server: %s" % e) self.log.error("Unable to bind to LDAP server: %s" % e)
return return
@ -595,7 +595,7 @@ class Restore(admintool.AdminTool):
try: try:
conn.add_entry(ent) conn.add_entry(ent)
except Exception, e: except Exception as e:
raise admintool.ScriptError('Unable to bind to LDAP server: %s' raise admintool.ScriptError('Unable to bind to LDAP server: %s'
% e) % e)
@ -773,7 +773,7 @@ class Restore(admintool.AdminTool):
os.mkdir(dir, 0o770) os.mkdir(dir, 0o770)
os.chown(dir, pent.pw_uid, pent.pw_gid) os.chown(dir, pent.pw_uid, pent.pw_gid)
tasks.restore_context(dir) tasks.restore_context(dir)
except Exception, e: except Exception as e:
# This isn't so fatal as to side-track the restore # This isn't so fatal as to side-track the restore
self.log.error('Problem with %s: %s' % (dir, e)) self.log.error('Problem with %s: %s' % (dir, e))

View File

@ -177,7 +177,7 @@ class ServerCertInstall(admintool.AdminTool):
if ca_enabled: if ca_enabled:
cdb.track_server_cert(server_cert, principal, cdb.passwd_fname, cdb.track_server_cert(server_cert, principal, cdb.passwd_fname,
command) command)
except RuntimeError, e: except RuntimeError as e:
raise admintool.ScriptError(str(e)) raise admintool.ScriptError(str(e))
return server_cert return server_cert

View File

@ -319,11 +319,11 @@ class WinsyncMigrate(admintool.AdminTool):
ccache = ctx.default_ccache() ccache = ctx.default_ccache()
api.Backend.ldap2.connect(ccache) api.Backend.ldap2.connect(ccache)
cls.ldap = api.Backend.ldap2 cls.ldap = api.Backend.ldap2
except krbV.Krb5Error, e: except krbV.Krb5Error as e:
sys.exit("Must have Kerberos credentials to migrate Winsync users.") sys.exit("Must have Kerberos credentials to migrate Winsync users.")
except errors.ACIError, e: except errors.ACIError as e:
sys.exit("Outdated Kerberos credentials. Use kdestroy and kinit to update your ticket.") sys.exit("Outdated Kerberos credentials. Use kdestroy and kinit to update your ticket.")
except errors.DatabaseError, e: except errors.DatabaseError as e:
sys.exit("Cannot connect to the LDAP database. Please check if IPA is running.") sys.exit("Cannot connect to the LDAP database. Please check if IPA is running.")
super(WinsyncMigrate, cls).main(argv) super(WinsyncMigrate, cls).main(argv)

View File

@ -277,11 +277,11 @@ class KrbInstance(service.Service):
for r in res: for r in res:
try: try:
self.admin_conn.delete_entry(r) self.admin_conn.delete_entry(r)
except Exception, e: except Exception as e:
root_logger.critical( root_logger.critical(
"Error during SASL mapping removal: %s", e) "Error during SASL mapping removal: %s", e)
raise raise
except Exception, e: except Exception as e:
root_logger.critical("Error while enumerating SASL mappings %s", e) root_logger.critical("Error while enumerating SASL mappings %s", e)
raise raise
@ -343,7 +343,7 @@ class KrbInstance(service.Service):
) )
try: try:
ipautil.run(args, nolog=(self.master_password,), stdin=''.join(dialogue)) ipautil.run(args, nolog=(self.master_password,), stdin=''.join(dialogue))
except ipautil.CalledProcessError, e: except ipautil.CalledProcessError as e:
print "Failed to initialize the realm container" print "Failed to initialize the realm container"
def __configure_instance(self): def __configure_instance(self):
@ -452,7 +452,7 @@ class KrbInstance(service.Service):
for f in [paths.KRB5KDC_KDC_CONF, paths.KRB5_CONF]: for f in [paths.KRB5KDC_KDC_CONF, paths.KRB5_CONF]:
try: try:
self.fstore.restore_file(f) self.fstore.restore_file(f)
except ValueError, error: except ValueError as error:
root_logger.debug(error) root_logger.debug(error)
pass pass

View File

@ -73,7 +73,7 @@ def connect(ldapi=False, realm=None, fqdn=None, dm_password=None, pw_name=None):
except ldap.INVALID_CREDENTIALS: except ldap.INVALID_CREDENTIALS:
raise RuntimeError( raise RuntimeError(
"The password provided is incorrect for LDAP server %s" % fqdn) "The password provided is incorrect for LDAP server %s" % fqdn)
except ldap.LOCAL_ERROR, e: except ldap.LOCAL_ERROR as e:
raise RuntimeError('%s' % e.args[0].get('info', '').strip()) raise RuntimeError('%s' % e.args[0].get('info', '').strip())
return conn return conn
@ -335,7 +335,7 @@ class LDAPUpdate:
def _template_str(self, s): def _template_str(self, s):
try: try:
return ipautil.template_str(s, self.sub_dict) return ipautil.template_str(s, self.sub_dict)
except KeyError, e: except KeyError as e:
raise BadSyntax("Unknown template keyword %s" % e) raise BadSyntax("Unknown template keyword %s" % e)
def read_file(self, filename): def read_file(self, filename):
@ -565,10 +565,10 @@ class LDAPUpdate:
while True: while True:
try: try:
entry = self.conn.get_entry(dn, attrlist) entry = self.conn.get_entry(dn, attrlist)
except errors.NotFound, e: except errors.NotFound as e:
self.error("Task not found: %s", dn) self.error("Task not found: %s", dn)
return return
except errors.DatabaseError, e: except errors.DatabaseError as e:
self.error("Task lookup failure %s", e) self.error("Task lookup failure %s", e)
return return
@ -783,7 +783,7 @@ class LDAPUpdate:
return return
added = True added = True
self.modified = True self.modified = True
except Exception, e: except Exception as e:
self.error("Add failure %s", e) self.error("Add failure %s", e)
else: else:
# Update LDAP # Update LDAP
@ -802,10 +802,10 @@ class LDAPUpdate:
except errors.EmptyModlist: except errors.EmptyModlist:
self.debug("Entry already up-to-date") self.debug("Entry already up-to-date")
updated = False updated = False
except errors.DatabaseError, e: except errors.DatabaseError as e:
self.error("Update failed: %s", e) self.error("Update failed: %s", e)
updated = False updated = False
except errors.ACIError, e: except errors.ACIError as e:
self.error("Update failed: %s", e) self.error("Update failed: %s", e)
updated = False updated = False
@ -829,10 +829,10 @@ class LDAPUpdate:
self.debug("Deleting entry %s", dn) self.debug("Deleting entry %s", dn)
self.conn.delete_entry(dn) self.conn.delete_entry(dn)
self.modified = True self.modified = True
except errors.NotFound, e: except errors.NotFound as e:
self.debug("%s did not exist:%s", dn, e) self.debug("%s did not exist:%s", dn, e)
self.modified = True self.modified = True
except errors.DatabaseError, e: except errors.DatabaseError as e:
self.error("Delete failed: %s", e) self.error("Delete failed: %s", e)
def get_all_files(self, root, recursive=False): def get_all_files(self, root, recursive=False):
@ -897,7 +897,7 @@ class LDAPUpdate:
try: try:
self.debug("Parsing update file '%s'" % f) self.debug("Parsing update file '%s'" % f)
data = self.read_file(f) data = self.read_file(f)
except Exception, e: except Exception as e:
self.error("error reading update file '%s'", f) self.error("error reading update file '%s'", f)
raise RuntimeError(e) raise RuntimeError(e)

View File

@ -172,7 +172,7 @@ class NTPInstance(service.Service):
try: try:
self.fstore.restore_file(paths.NTP_CONF) self.fstore.restore_file(paths.NTP_CONF)
except ValueError, error: except ValueError as error:
root_logger.debug(error) root_logger.debug(error)
pass pass

View File

@ -119,7 +119,7 @@ class ODSExporterInstance(service.Service):
self.admin_conn.modify_s(dns_group, mod) self.admin_conn.modify_s(dns_group, mod)
except ldap.TYPE_OR_VALUE_EXISTS: except ldap.TYPE_OR_VALUE_EXISTS:
pass pass
except Exception, e: except Exception as e:
root_logger.critical("Could not modify principal's %s entry: %s" root_logger.critical("Could not modify principal's %s entry: %s"
% (dns_exporter_principal_dn, str(e))) % (dns_exporter_principal_dn, str(e)))
raise raise
@ -132,7 +132,7 @@ class ODSExporterInstance(service.Service):
(ldap.MOD_REPLACE, 'nsLookThroughLimit', '-1')] (ldap.MOD_REPLACE, 'nsLookThroughLimit', '-1')]
try: try:
self.admin_conn.modify_s(dns_exporter_principal_dn, mod) self.admin_conn.modify_s(dns_exporter_principal_dn, mod)
except Exception, e: except Exception as e:
root_logger.critical("Could not set principal's %s LDAP limits: %s" root_logger.critical("Could not set principal's %s LDAP limits: %s"
% (dns_exporter_principal_dn, str(e))) % (dns_exporter_principal_dn, str(e)))
raise raise

View File

@ -360,7 +360,7 @@ class OpenDNSSECInstance(service.Service):
paths.OPENDNSSEC_KASP_DB, paths.SYSCONFIG_ODS]: paths.OPENDNSSEC_KASP_DB, paths.SYSCONFIG_ODS]:
try: try:
self.fstore.restore_file(f) self.fstore.restore_file(f)
except ValueError, error: except ValueError as error:
root_logger.debug(error) root_logger.debug(error)
pass pass

View File

@ -264,7 +264,7 @@ class update_master_to_dnsforwardzones(Updater):
del record['dn'] del record['dn']
writer.unparse(dn, record) writer.unparse(dn, record)
except Exception, e: except Exception as e:
self.log.error('Unable to backup zone %s' % self.log.error('Unable to backup zone %s' %
zone['idnsname'][0]) zone['idnsname'][0])
self.log.error(traceback.format_exc()) self.log.error(traceback.format_exc())
@ -274,7 +274,7 @@ class update_master_to_dnsforwardzones(Updater):
try: try:
entry = ldap.get_entry(privilege_dn) entry = ldap.get_entry(privilege_dn)
writer.unparse(str(entry.dn), dict(entry.raw)) writer.unparse(str(entry.dn), dict(entry.raw))
except Exception, e: except Exception as e:
self.log.error('Unable to backup privilege %s' % self.log.error('Unable to backup privilege %s' %
privilege_dn) privilege_dn)
self.log.error(traceback.format_exc()) self.log.error(traceback.format_exc())
@ -291,7 +291,7 @@ class update_master_to_dnsforwardzones(Updater):
# delete master zone # delete master zone
try: try:
self.api.Command['dnszone_del'](zone['idnsname']) self.api.Command['dnszone_del'](zone['idnsname'])
except Exception, e: except Exception as e:
self.log.error('Transform to forwardzone terminated: ' self.log.error('Transform to forwardzone terminated: '
'removing zone %s failed (%s)' % ( 'removing zone %s failed (%s)' % (
zone['idnsname'][0], e) zone['idnsname'][0], e)
@ -306,7 +306,7 @@ class update_master_to_dnsforwardzones(Updater):
'idnsforwardpolicy': zone.get('idnsforwardpolicy', [u'first'])[0] 'idnsforwardpolicy': zone.get('idnsforwardpolicy', [u'first'])[0]
} }
self.api.Command['dnsforwardzone_add'](zone['idnsname'][0], **kw) self.api.Command['dnsforwardzone_add'](zone['idnsname'][0], **kw)
except Exception, e: except Exception as e:
self.log.error('Transform to forwardzone terminated: creating ' self.log.error('Transform to forwardzone terminated: creating '
'forwardzone %s failed' % 'forwardzone %s failed' %
zone['idnsname'][0]) zone['idnsname'][0])
@ -318,7 +318,7 @@ class update_master_to_dnsforwardzones(Updater):
try: try:
perm_name = self.api.Command['dnsforwardzone_add_permission']( perm_name = self.api.Command['dnsforwardzone_add_permission'](
zone['idnsname'][0])['value'] zone['idnsname'][0])['value']
except Exception, e: except Exception as e:
self.log.error('Transform to forwardzone terminated: ' self.log.error('Transform to forwardzone terminated: '
'Adding managed by permission to forward zone' 'Adding managed by permission to forward zone'
' %s failed' % zone['idnsname']) ' %s failed' % zone['idnsname'])
@ -336,7 +336,7 @@ class update_master_to_dnsforwardzones(Updater):
try: try:
self.api.Command['permission_add_member'](perm_name, self.api.Command['permission_add_member'](perm_name,
privilege=privileges) privilege=privileges)
except Exception, e: except Exception as e:
self.log.error('Unable to restore privileges for ' self.log.error('Unable to restore privileges for '
'permission %s, for zone %s' 'permission %s, for zone %s'
% (perm_name, zone['idnsname'])) % (perm_name, zone['idnsname']))

View File

@ -89,7 +89,7 @@ class update_replica_attribute_lists(Updater):
try: try:
repl.conn.update_entry(replica) repl.conn.update_entry(replica)
self.log.debug("Updated") self.log.debug("Updated")
except Exception, e: except Exception as e:
self.log.error("Error caught updating replica: %s", str(e)) self.log.error("Error caught updating replica: %s", str(e))
else: else:
@ -107,7 +107,7 @@ class update_replica_attribute_lists(Updater):
try: try:
repl.conn.update_entry(replica) repl.conn.update_entry(replica)
self.log.debug("Updated %s", attribute) self.log.debug("Updated %s", attribute)
except Exception, e: except Exception as e:
self.log.error("Error caught updating %s: %s", self.log.error("Error caught updating %s: %s",
attribute, str(e)) attribute, str(e))
else: else:

View File

@ -79,7 +79,7 @@ class GenerateUpdateMixin(object):
definitions_managed_entries, truncated = ldap.find_entries( definitions_managed_entries, truncated = ldap.find_entries(
searchfilter, ['*'], old_definition_container, searchfilter, ['*'], old_definition_container,
ldap.SCOPE_ONELEVEL) ldap.SCOPE_ONELEVEL)
except errors.NotFound, e: except errors.NotFound as e:
return (False, update_list) return (False, update_list)
for entry in definitions_managed_entries: for entry in definitions_managed_entries:
@ -89,7 +89,7 @@ class GenerateUpdateMixin(object):
assert isinstance(old_dn, DN) assert isinstance(old_dn, DN)
try: try:
entry = ldap.get_entry(old_dn, ['*']) entry = ldap.get_entry(old_dn, ['*'])
except errors.NotFound, e: except errors.NotFound as e:
pass pass
else: else:
# Compute the new dn by replacing the old container with the new container # Compute the new dn by replacing the old container with the new container

View File

@ -50,7 +50,7 @@ class update_idrange_type(Updater):
"type set found") "type set found")
return False, [] return False, []
except errors.ExecutionError, e: except errors.ExecutionError as e:
root_logger.error("update_idrange_type: cannot retrieve list " root_logger.error("update_idrange_type: cannot retrieve list "
"of ranges with no type set: %s", e) "of ranges with no type set: %s", e)
return False, [] return False, []
@ -89,7 +89,7 @@ class update_idrange_type(Updater):
ldap.update_entry(entry) ldap.update_entry(entry)
except (errors.EmptyModlist, errors.NotFound): except (errors.EmptyModlist, errors.NotFound):
pass pass
except errors.ExecutionError, e: except errors.ExecutionError as e:
root_logger.debug("update_idrange_type: cannot " root_logger.debug("update_idrange_type: cannot "
"update idrange type: %s", e) "update idrange type: %s", e)
error = True error = True
@ -137,7 +137,7 @@ class update_idrange_baserid(Updater):
"range with posix attributes found") "range with posix attributes found")
return False, [] return False, []
except errors.ExecutionError, e: except errors.ExecutionError as e:
root_logger.error("update_idrange_baserid: cannot retrieve " root_logger.error("update_idrange_baserid: cannot retrieve "
"list of affected ranges: %s", e) "list of affected ranges: %s", e)
return False, [] return False, []
@ -157,7 +157,7 @@ class update_idrange_baserid(Updater):
root_logger.info("Done") root_logger.info("Done")
except (errors.EmptyModlist, errors.NotFound): except (errors.EmptyModlist, errors.NotFound):
pass pass
except errors.ExecutionError, e: except errors.ExecutionError as e:
root_logger.debug("update_idrange_type: cannot " root_logger.debug("update_idrange_type: cannot "
"update idrange: %s", e) "update idrange: %s", e)
error = True error = True

View File

@ -50,7 +50,7 @@ class update_service_principalalias(Updater):
root_logger.debug("update_service_principalalias: no service " root_logger.debug("update_service_principalalias: no service "
"to update found") "to update found")
return False, [] return False, []
except errors.ExecutionError, e: except errors.ExecutionError as e:
root_logger.error("update_service_principalalias: cannot " root_logger.error("update_service_principalalias: cannot "
"retrieve list of affected services: %s", e) "retrieve list of affected services: %s", e)
return False, [] return False, []
@ -72,7 +72,7 @@ class update_service_principalalias(Updater):
ldap.update_entry(entry) ldap.update_entry(entry)
except (errors.EmptyModlist, errors.NotFound): except (errors.EmptyModlist, errors.NotFound):
pass pass
except errors.ExecutionError, e: except errors.ExecutionError as e:
root_logger.debug("update_service_principalalias: cannot " root_logger.debug("update_service_principalalias: cannot "
"update service: %s", e) "update service: %s", e)
error = True error = True

View File

@ -59,7 +59,7 @@ class update_upload_cacrt(Updater):
try: try:
certstore.init_ca_entry(entry, cert, nickname, trust, eku) certstore.init_ca_entry(entry, cert, nickname, trust, eku)
except Exception, e: except Exception as e:
self.log.warning("Failed to create entry for %s: %s", self.log.warning("Failed to create entry for %s: %s",
nickname, e) nickname, e)
continue continue

View File

@ -157,7 +157,7 @@ def wait_for_entry(connection, entry, timeout=7200, attr='', quiet=True):
dn, ldap.SCOPE_BASE, filter, attrlist) dn, ldap.SCOPE_BASE, filter, attrlist)
except errors.NotFound: except errors.NotFound:
pass # no entry yet pass # no entry yet
except Exception, e: # badness except Exception as e: # badness
print "\nError reading entry", dn, e print "\nError reading entry", dn, e
break break
if not entry: if not entry:
@ -500,7 +500,7 @@ class ReplicationManager(object):
done = True done = True
except errors.DuplicateEntry: except errors.DuplicateEntry:
benum += 1 benum += 1
except errors.ExecutionError, e: except errors.ExecutionError as e:
print "Could not add backend entry " + dn, e print "Could not add backend entry " + dn, e
raise raise
@ -676,7 +676,7 @@ class ReplicationManager(object):
mod = [(ldap.MOD_ADD, 'nsDS5ReplicatedAttributeListTotal', mod = [(ldap.MOD_ADD, 'nsDS5ReplicatedAttributeListTotal',
'(objectclass=*) $ EXCLUDE %s' % " ".join(TOTAL_EXCLUDES))] '(objectclass=*) $ EXCLUDE %s' % " ".join(TOTAL_EXCLUDES))]
a_conn.modify_s(dn, mod) a_conn.modify_s(dn, mod)
except ldap.LDAPError, e: except ldap.LDAPError as e:
# Apparently there are problems set the total list # Apparently there are problems set the total list
# Probably the master is an old 389-ds server, tell the caller # Probably the master is an old 389-ds server, tell the caller
# that we will have to set the memberof fixup task # that we will have to set the memberof fixup task
@ -842,7 +842,7 @@ class ReplicationManager(object):
try: try:
self.conn.modify_s(dn, mod) self.conn.modify_s(dn, mod)
except Exception, e: except Exception as e:
root_logger.debug("Failed to remove referral value: %s" % str(e)) root_logger.debug("Failed to remove referral value: %s" % str(e))
def check_repl_init(self, conn, agmtdn, start): def check_repl_init(self, conn, agmtdn, start):
@ -1039,7 +1039,7 @@ class ReplicationManager(object):
raise RuntimeError("Failed to lookup AD's Ldap suffix") raise RuntimeError("Failed to lookup AD's Ldap suffix")
ad_conn.unbind_s() ad_conn.unbind_s()
del ad_conn del ad_conn
except Exception, e: except Exception as e:
root_logger.info("Failed to connect to AD server %s" % ad_dc_name) root_logger.info("Failed to connect to AD server %s" % ad_dc_name)
root_logger.info("The error was: %s" % e) root_logger.info("The error was: %s" % e)
raise RuntimeError("Failed to setup winsync replication") raise RuntimeError("Failed to setup winsync replication")
@ -1072,7 +1072,7 @@ class ReplicationManager(object):
try: try:
self.conn.add_entry(entry) self.conn.add_entry(entry)
except Exception, e: except Exception as e:
root_logger.info("Failed to create public entry for winsync replica") root_logger.info("Failed to create public entry for winsync replica")
#Finally start replication #Finally start replication
@ -1203,7 +1203,7 @@ class ReplicationManager(object):
self.conn.delete_entry(entry) self.conn.delete_entry(entry)
except errors.NotFound: except errors.NotFound:
pass pass
except Exception, e: except Exception as e:
if not force: if not force:
raise e raise e
else: else:
@ -1228,7 +1228,7 @@ class ReplicationManager(object):
except (ldap.NO_SUCH_OBJECT, ldap.NO_SUCH_ATTRIBUTE): except (ldap.NO_SUCH_OBJECT, ldap.NO_SUCH_ATTRIBUTE):
root_logger.debug("Replica (%s) memberPrincipal (%s) not found in %s" % \ root_logger.debug("Replica (%s) memberPrincipal (%s) not found in %s" % \
(replica, member_principal, dn)) (replica, member_principal, dn))
except Exception, e: except Exception as e:
if not force: if not force:
raise e raise e
elif not err: elif not err:
@ -1245,7 +1245,7 @@ class ReplicationManager(object):
self.conn.delete_entry(entry) self.conn.delete_entry(entry)
except errors.NotFound: except errors.NotFound:
pass pass
except Exception, e: except Exception as e:
if not force: if not force:
raise e raise e
elif not err: elif not err:
@ -1288,7 +1288,7 @@ class ReplicationManager(object):
pass pass
except errors.NotFound: except errors.NotFound:
pass pass
except Exception, e: except Exception as e:
if not force: if not force:
raise e raise e
elif not err: elif not err:
@ -1326,7 +1326,7 @@ class ReplicationManager(object):
pass pass
except errors.NotFound: except errors.NotFound:
pass pass
except Exception, e: except Exception as e:
if not force: if not force:
raise e raise e
elif not err: elif not err:
@ -1356,7 +1356,7 @@ class ReplicationManager(object):
pass pass
except errors.NotFound: except errors.NotFound:
pass pass
except Exception, e: except Exception as e:
if not force: if not force:
raise e raise e
elif not err: elif not err:
@ -1372,7 +1372,7 @@ class ReplicationManager(object):
self.conn.delete_entry(entry) self.conn.delete_entry(entry)
except errors.NotFound: except errors.NotFound:
pass pass
except Exception, e: except Exception as e:
if not force: if not force:
raise e raise e
elif not err: elif not err:
@ -1394,7 +1394,7 @@ class ReplicationManager(object):
pass pass
except ldap.TYPE_OR_VALUE_EXISTS: except ldap.TYPE_OR_VALUE_EXISTS:
pass pass
except Exception, e: except Exception as e:
if force and err: if force and err:
raise err #pylint: disable=E0702 raise err #pylint: disable=E0702
else: else:
@ -1416,7 +1416,7 @@ class ReplicationManager(object):
mod = [(ldap.MOD_REPLACE, 'nsslapd-readonly', 'on' if readonly else 'off')] mod = [(ldap.MOD_REPLACE, 'nsslapd-readonly', 'on' if readonly else 'off')]
try: try:
self.conn.modify_s(dn, mod) self.conn.modify_s(dn, mod)
except ldap.INSUFFICIENT_ACCESS, e: except ldap.INSUFFICIENT_ACCESS as e:
# We can't modify the read-only status on the remote server. # We can't modify the read-only status on the remote server.
# This usually isn't a show-stopper. # This usually isn't a show-stopper.
if critical: if critical:
@ -1666,7 +1666,7 @@ class CSReplicationManager(ReplicationManager):
entry['nsslapd-referral'].remove('ldap://%s/%s' % entry['nsslapd-referral'].remove('ldap://%s/%s' %
(ipautil.format_netloc(hostname, port), self.suffix)) (ipautil.format_netloc(hostname, port), self.suffix))
self.conn.update_entry(entry) self.conn.update_entry(entry)
except Exception, e: except Exception as e:
root_logger.debug("Failed to remove referral value: %s" % e) root_logger.debug("Failed to remove referral value: %s" % e)
def has_ipaca(self): def has_ipaca(self):

View File

@ -102,7 +102,7 @@ def read_cache(dm_password):
fname = "%s/cache" % top_dir fname = "%s/cache" % top_dir
try: try:
decrypt_file(paths.ROOT_IPA_CACHE, fname, dm_password, top_dir) decrypt_file(paths.ROOT_IPA_CACHE, fname, dm_password, top_dir)
except Exception, e: except Exception as e:
shutil.rmtree(top_dir) shutil.rmtree(top_dir)
raise Exception("Decryption of answer cache in %s failed, please " raise Exception("Decryption of answer cache in %s failed, please "
"check your password." % paths.ROOT_IPA_CACHE) "check your password." % paths.ROOT_IPA_CACHE)
@ -111,10 +111,10 @@ def read_cache(dm_password):
with open(fname, 'rb') as f: with open(fname, 'rb') as f:
try: try:
optdict = pickle.load(f) optdict = pickle.load(f)
except Exception, e: except Exception as e:
raise Exception("Parse error in %s: %s" % raise Exception("Parse error in %s: %s" %
(paths.ROOT_IPA_CACHE, str(e))) (paths.ROOT_IPA_CACHE, str(e)))
except IOError, e: except IOError as e:
raise Exception("Read error in %s: %s" % raise Exception("Read error in %s: %s" %
(paths.ROOT_IPA_CACHE, str(e))) (paths.ROOT_IPA_CACHE, str(e)))
finally: finally:
@ -140,7 +140,7 @@ def write_cache(options):
pickle.dump(options, f) pickle.dump(options, f)
ipautil.encrypt_file(fname, paths.ROOT_IPA_CACHE, ipautil.encrypt_file(fname, paths.ROOT_IPA_CACHE,
options['dm_password'], top_dir) options['dm_password'], top_dir)
except IOError, e: except IOError as e:
raise Exception("Unable to cache command-line options %s" % str(e)) raise Exception("Unable to cache command-line options %s" % str(e))
finally: finally:
shutil.rmtree(top_dir) shutil.rmtree(top_dir)
@ -243,7 +243,7 @@ def set_subject_in_config(realm_name, dm_password, suffix, subject_base):
conn = ldap2(api, ldap_uri=ldapuri) conn = ldap2(api, ldap_uri=ldapuri)
conn.connect(bind_dn=DN(('cn', 'directory manager')), conn.connect(bind_dn=DN(('cn', 'directory manager')),
bind_pw=dm_password) bind_pw=dm_password)
except errors.ExecutionError, e: except errors.ExecutionError as e:
root_logger.critical("Could not connect to the Directory Server " root_logger.critical("Could not connect to the Directory Server "
"on %s" % realm_name) "on %s" % realm_name)
raise e raise e
@ -348,7 +348,7 @@ def install_check(installer):
if cache_vars.get('external_ca', False): if cache_vars.get('external_ca', False):
options.external_ca = False options.external_ca = False
options.interactive = False options.interactive = False
except Exception, e: except Exception as e:
sys.exit("Cannot process the cache file: %s" % str(e)) sys.exit("Cannot process the cache file: %s" % str(e))
# We only set up the CA if the PKCS#12 options are not given. # We only set up the CA if the PKCS#12 options are not given.
@ -400,7 +400,7 @@ def install_check(installer):
if not options.no_ntp: if not options.no_ntp:
try: try:
ipaclient.ntpconf.check_timedate_services() ipaclient.ntpconf.check_timedate_services()
except ipaclient.ntpconf.NTPConflictingService, e: except ipaclient.ntpconf.NTPConflictingService as e:
print("WARNING: conflicting time&date synchronization service '%s'" print("WARNING: conflicting time&date synchronization service '%s'"
" will be disabled" % e.conflicting_service) " will be disabled" % e.conflicting_service)
print "in favor of ntpd" print "in favor of ntpd"
@ -440,7 +440,7 @@ def install_check(installer):
host_name = host_default host_name = host_default
else: else:
host_name = read_host_name(host_default, options.no_host_dns) host_name = read_host_name(host_default, options.no_host_dns)
except BadHostError, e: except BadHostError as e:
sys.exit(str(e) + "\n") sys.exit(str(e) + "\n")
host_name = host_name.lower() host_name = host_name.lower()
@ -462,7 +462,7 @@ def install_check(installer):
root_logger.debug("read domain_name: %s\n" % domain_name) root_logger.debug("read domain_name: %s\n" % domain_name)
try: try:
validate_domain_name(domain_name) validate_domain_name(domain_name)
except ValueError, e: except ValueError as e:
sys.exit("Invalid domain name: %s" % unicode(e)) sys.exit("Invalid domain name: %s" % unicode(e))
else: else:
domain_name = options.domain_name domain_name = options.domain_name
@ -881,7 +881,7 @@ def install(installer):
if options.mkhomedir: if options.mkhomedir:
args.append("--mkhomedir") args.append("--mkhomedir")
run(args) run(args)
except Exception, e: except Exception as e:
sys.exit("Configuration of client side components failed!\n" sys.exit("Configuration of client side components failed!\n"
"ipa-client-install returned: " + str(e)) "ipa-client-install returned: " + str(e))
@ -1034,7 +1034,7 @@ def uninstall(installer):
print "Shutting down all IPA services" print "Shutting down all IPA services"
try: try:
(stdout, stderr, rc) = run([paths.IPACTL, "stop"], raiseonerr=False) (stdout, stderr, rc) = run([paths.IPACTL, "stop"], raiseonerr=False)
except Exception, e: except Exception as e:
pass pass
# Need to get dogtag info before /etc/ipa/default.conf is removed # Need to get dogtag info before /etc/ipa/default.conf is removed
@ -1048,7 +1048,7 @@ def uninstall(installer):
if rc not in [0, 2]: if rc not in [0, 2]:
root_logger.debug("ipa-client-install returned %d" % rc) root_logger.debug("ipa-client-install returned %d" % rc)
raise RuntimeError(stdout) raise RuntimeError(stdout)
except Exception, e: except Exception as e:
rv = 1 rv = 1
print "Uninstall of client side components failed!" print "Uninstall of client side components failed!"
print "ipa-client-install returned: " + str(e) print "ipa-client-install returned: " + str(e)
@ -1262,7 +1262,7 @@ class ServerCA(common.Installable, core.Group, core.Composite):
for rdn in dn: for rdn in dn:
if rdn.attr.lower() not in VALID_SUBJECT_ATTRS: if rdn.attr.lower() not in VALID_SUBJECT_ATTRS:
raise ValueError("invalid attribute: \"%s\"" % rdn.attr) raise ValueError("invalid attribute: \"%s\"" % rdn.attr)
except ValueError, e: except ValueError as e:
raise ValueError("invalid subject base format: %s" % e) raise ValueError("invalid subject base format: %s" % e)
ca_signing_algorithm = Knob( ca_signing_algorithm = Knob(
@ -1325,7 +1325,7 @@ class ServerDNS(common.Installable, core.Group, core.Composite):
encoding = 'utf-8' encoding = 'utf-8'
value = value.decode(encoding) value = value.decode(encoding)
bindinstance.validate_zonemgr_str(value) bindinstance.validate_zonemgr_str(value)
except ValueError, e: except ValueError as e:
# FIXME we can do this in better way # FIXME we can do this in better way
# https://fedorahosted.org/freeipa/ticket/4804 # https://fedorahosted.org/freeipa/ticket/4804
# decode to proper stderr encoding # decode to proper stderr encoding

Some files were not shown because too many files have changed in this diff Show More