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()
return True
except LDAPError, err:
except LDAPError as err:
#no good
root_logger.error("Ldap Error: "+str(err))
return False
@ -289,7 +289,7 @@ def main():
{'name':'empty', 'type':'empty'}]
try:
ldapconf.newConf("/etc/ldap.conf", opts)
except Exception, e:
except Exception as e:
print "Configuration failed: " + str(e)
return 1

View File

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

View File

@ -90,10 +90,10 @@ while watcher_running:
try:
log.info('LDAP bind...')
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)
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)
time.sleep(5)
continue

View File

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

View File

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

View File

@ -52,12 +52,12 @@ def bind(ldap_uri, base_dn, username, password):
try:
conn = IPAdmin(ldap_uri=ldap_uri)
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(
'migration invalid credentials for %s: %s' % (bind_dn, e))
raise IOError(
errno.EPERM, 'Invalid LDAP credentials for user %s' % username)
except Exception, e:
except Exception as e:
root_logger.error('migration bind failed: %s' % e)
raise IOError(errno.EIO, 'Bind error')
finally:

View File

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

View File

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

View File

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

View File

@ -40,7 +40,7 @@ def _main():
try:
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)))

View File

@ -30,7 +30,7 @@ def _main():
try:
services.knownservices.httpd.restart()
except Exception, e:
except Exception as 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)
try:
dogtag_service.stop(dogtag_instance)
except Exception, e:
except Exception as e:
syslog.syslog(
syslog.LOG_ERR, "Cannot stop %s: %s" % (dogtag_service.service_name, e))
else:

View File

@ -82,7 +82,7 @@ def add_ca_schema():
continue
try:
shutil.copyfile(source_fname, target_fname)
except IOError, e:
except IOError as e:
root_logger.warning('Could not install %s: %s', target_fname, e)
else:
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)
try:
api.finalize()
except StandardError, e:
except StandardError as e:
api.log.error('Failed to start IPA: %s' % e)
else:
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):
try:
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."
return False
return True
@ -305,14 +305,14 @@ def main():
ctx = krbV.default_context()
ccache = ctx.default_ccache()
principal = ccache.principal()
except krbV.Krb5Error, e:
except krbV.Krb5Error as e:
sys.exit("Must have Kerberos credentials to setup AD trusts on server")
try:
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")
except errors.DatabaseError, e:
except errors.DatabaseError as e:
sys.exit("Cannot connect to the LDAP database. Please check if IPA is running")
try:
@ -321,9 +321,9 @@ def main():
if not (user['uid'][0] in group['member_user'] and
group['cn'][0] in user['memberof_group']):
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")
except Exception, e:
except Exception as e:
sys.exit("Unrecognized error during check of admin rights: %s" % (str(e)))
(netbios_name, reset_netbios_name) = \
@ -344,7 +344,7 @@ def main():
except errors.NotFound:
# All objects have SIDs assigned
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 unicode(e)
else:
@ -400,7 +400,7 @@ def main():
base_dn=masters_dn, attrs_list=['cn'], scope=ldap.SCOPE_ONELEVEL)
except errors.NotFound:
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 unicode(e)
@ -409,7 +409,7 @@ def main():
base_dn=agents_dn, attrs_list=['member'], scope=ldap.SCOPE_BASE)
except errors.NotFound:
pass
except (errors.DatabaseError, errors.NetworkError), e:
except (errors.DatabaseError, errors.NetworkError) as e:
print "Could not retrieve a list of adtrust agents:"
print unicode(e)

View File

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

View File

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

View File

@ -102,7 +102,7 @@ def main():
conn.do_simple_bind(bindpw=dirman_password)
except errors.ACIError:
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" %
str(lde))
@ -112,7 +112,7 @@ def main():
try:
entries = conn.get_entries(
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))
sys.exit("Unable to find managed entries at %s" % managed_entry_definitions_dn)
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)
except errors.NotFound:
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 lde
@ -166,7 +166,7 @@ def main():
retval = 0
except errors.NotFound:
print "Enabling Plugin"
except errors.ExecutionError, lde:
except errors.ExecutionError as lde:
print "An error occurred while talking to the server."
print lde
retval = 1
@ -190,11 +190,11 @@ def main():
except errors.NotFound:
print "Plugin is already disabled"
retval = 2
except errors.DatabaseError, dbe:
except errors.DatabaseError as dbe:
print "An error occurred while talking to the server."
print dbe
retval = 1
except errors.ExecutionError, lde:
except errors.ExecutionError as lde:
print "An error occurred while talking to the server."
print lde
retval = 1

View File

@ -124,7 +124,7 @@ def main():
conn.connect(
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))
except errors.AuthorizationError:
sys.exit("Incorrect password")
@ -136,7 +136,7 @@ def main():
entry = None
try:
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 lde
retval = 1
@ -146,13 +146,13 @@ def main():
portmap = services.knownservices.portmap
portmap.enable()
servicemsg = portmap.service_name
except ipautil.CalledProcessError, cpe:
except ipautil.CalledProcessError as cpe:
if cpe.returncode == 1:
try:
rpcbind = services.knownservices.rpcbind
rpcbind.enable()
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)
retval = 3
@ -180,7 +180,7 @@ def main():
except (errors.NotFound, errors.EmptyModlist):
print "Plugin is already disabled"
retval = 2
except errors.LDAPError, lde:
except errors.LDAPError as lde:
print "An error occurred while talking to the server."
print lde
retval = 1

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -127,14 +127,14 @@ class Executioner(Backend):
if _name not in self.Command:
raise CommandError(name=_name)
result = self.Command[_name](*args, **options)
except PublicError, e:
except PublicError as e:
error = e
except StandardError, e:
except StandardError as e:
self.exception(
'non-public: %s: %s', e.__class__.__name__, str(e)
)
error = InternalError()
except Exception, e:
except Exception as e:
self.exception(
'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)
serial_number = x509.get_serial_number(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)
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:
try:
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)
if cert_eku is not None:
cert_eku -= {x509.EKU_SERVER_AUTH, x509.EKU_CLIENT_AUTH,

View File

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

View File

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

View File

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

View File

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

View File

@ -429,7 +429,7 @@ class API(ReadOnly):
filename=self.env.log,
level=level,
format=LOGGING_FORMAT_FILE)])
except IOError, e:
except IOError as e:
log.error('Cannot open log file %r: %s', self.env.log, e)
return
@ -541,7 +541,7 @@ class API(ReadOnly):
subpackage = module[:-2]
try:
plugins = importlib.import_module(subpackage)
except ImportError, e:
except ImportError as e:
self.log.error("cannot import plugins sub-package %s: %s",
subpackage, e)
raise
@ -565,9 +565,9 @@ class API(ReadOnly):
self.log.debug("importing plugin module %s", name)
try:
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)
except StandardError, e:
except StandardError as e:
if self.env.startup_traceback:
import traceback
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
try:
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'):
raise e
else:
@ -304,7 +304,7 @@ def _make_aci(ldap, current, aciname, kw):
if not target.startswith('ldap:///'):
target = 'ldap:///%s' % 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)))
return a
@ -370,7 +370,7 @@ def _aci_to_kw(ldap, a, test=False, pkey_only=False):
entry = ldap.make_entry(dn)
try:
entry = ldap.get_entry(groupdn, ['cn'])
except errors.NotFound, e:
except errors.NotFound as e:
# FIXME, use real name here
if test:
dn = DN(('cn', 'test'), api.env.container_permission,
@ -389,7 +389,7 @@ def _convert_strings_to_acis(acistrs):
for a in acistrs:
try:
acis.append(ACI(a))
except SyntaxError, e:
except SyntaxError as e:
root_logger.warning("Failed to parse: %s" % a)
return acis
@ -651,7 +651,7 @@ class aci_mod(crud.Update):
try:
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
# report the ADD error back to user
try:

View File

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

View File

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

View File

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

View File

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

View File

@ -520,7 +520,7 @@ class group_add_member(LDAPAddMember):
else:
try:
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))
else:
sids.append(actual_sid)
@ -577,7 +577,7 @@ class group_remove_member(LDAPRemoveMember):
else:
try:
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)))
else:
sids.append(actual_sid)

View File

@ -256,7 +256,7 @@ def validate_ipaddr(ugettext, ipaddr):
"""
try:
CheckedIPAddress(ipaddr, match_local=False)
except Exception, e:
except Exception as e:
return unicode(e)
return None
@ -272,7 +272,7 @@ def normalize_hostname(hostname):
def _hostname_validator(ugettext, value):
try:
validate_hostname(value)
except ValueError, e:
except ValueError as e:
return _('invalid domain-name: %s') % unicode(e)
return None
@ -674,7 +674,7 @@ class host_add(LDAPCreate):
del options['ip_address']
update_sshfp_record(domain, unicode(parts[0]), entry_attrs)
except Exception, e:
except Exception as e:
exc = e
if options.get('random', False):
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']:
try:
from ipaserver.plugins.ldap2 import ldap2
except StandardError, e:
except StandardError as e:
raise e
from ipalib import _
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.' \
% (entry_attrs['gidnumber'][0], pkey))
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
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))
except errors.LimitsExceeded, e:
except errors.LimitsExceeded as e:
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
@ -240,7 +240,7 @@ def _pre_migrate_user(ldap, pkey, dn, entry_attrs, failed, config, ctx, **kwargs
', convert it', pkey, value, type(value), attr)
try:
value = DN(value)
except ValueError, e:
except ValueError as e:
api.log.warn('%s: skipping normalization of value %s of type %s '
'in attribute %s which could not be converted to DN: %s',
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]:
try:
m = DN(m)
except ValueError, e:
except ValueError as e:
# This should be impossible unless the remote server
# doesn't enforce syntax checking.
api.log.error('Malformed DN %s: %s' % (m, e))
@ -826,19 +826,19 @@ can use their Kerberos accounts.''')
)
if not entry_attrs.dn:
continue
except errors.NotFound, e:
except errors.NotFound as e:
failed[ldap_obj_name][pkey] = unicode(e.reason)
continue
try:
ldap.add_entry(entry_attrs)
except errors.ExecutionError, e:
except errors.ExecutionError as e:
callback = self.migrate_objects[ldap_obj_name]['exc_callback']
if callable(callback):
try:
callback(
ldap, entry_attrs.dn, entry_attrs, e, options)
except errors.ExecutionError, e:
except errors.ExecutionError as e:
failed[ldap_obj_name][pkey] = unicode(e)
continue
else:
@ -916,7 +916,7 @@ can use their Kerberos accounts.''')
try:
ds_base_dn = DN(entries[0]['namingcontexts'][0])
assert isinstance(ds_base_dn, DN)
except (IndexError, KeyError), e:
except (IndexError, KeyError) as e:
raise StandardError(str(e))
# migrate!

View File

@ -90,7 +90,7 @@ class OTPTokenKey(Bytes):
if isinstance(value, unicode):
try:
value = base64.b32decode(value, True)
except TypeError, e:
except TypeError as e:
raise ConversionError(name=self.name, index=index, error=str(e))
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):
try:
self.obj.add_aci(entry)
except Exception, e:
except Exception as e:
# Adding the ACI failed.
# 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.)
@ -1185,7 +1185,7 @@ class permission_mod(baseldap.LDAPUpdate):
context.permision_moving_aci = True
try:
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)
# 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(
keys[-1], cospriority=options['cospriority']
)
except errors.EmptyModlist, e:
except errors.EmptyModlist as e:
if len(entry_attrs) == 1: # cospriority only was passed
raise e
else:

View File

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

View File

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

View File

@ -307,7 +307,7 @@ def check_required_principal(ldap, hostname, service):
"""
try:
host_is_master(ldap, hostname)
except errors.ValidationError, e:
except errors.ValidationError as e:
service_types = ['HTTP', 'ldap', 'DNS', 'dogtagldap']
if service in service_types:
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:
import pysss_murmur #pylint: disable=F0401
_murmur_installed = True
except Exception, e:
except Exception as e:
_murmur_installed = False
try:
import pysss_nss_idmap #pylint: disable=F0401
_nss_idmap_installed = True
except Exception, e:
except Exception as e:
_nss_idmap_installed = False
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)
fetch_domains_method = intf.get_dbus_method('fetch_domains', dbus_interface=DBUS_IFACE_TRUST)
(_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.'
'DBus exception is %(exc)s.' % dict(iface=DBUS_IFACE_TRUST, exc=str(e)))
if _ret != 0:
@ -1173,7 +1173,7 @@ class trust_resolve(Command):
entry['name'] = [unicode(xlate[sid][pysss_nss_idmap.NAME_KEY])]
entry['type'] = [idmap_type_string(xlate[sid][pysss_nss_idmap.TYPE_KEY])]
result.append(entry)
except ValueError, e:
except ValueError as e:
pass
return dict(result=result)

View File

@ -974,7 +974,7 @@ class user_status(LDAPQuery):
other_ldap = ldap2(self.api, ldap_uri='ldap://%s' % host)
try:
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)))
newresult = {'dn': dn}
newresult['server'] = _("%(host)s failed: %(error)s") % dict(host=host, error=str(e))
@ -994,7 +994,7 @@ class user_status(LDAPQuery):
continue
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))
except Exception, e:
except Exception as e:
self.debug("time conversion failed with %s" % str(e))
pass
newresult['server'] = host
@ -1011,7 +1011,7 @@ class user_status(LDAPQuery):
count += 1
except errors.NotFound:
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)))
newresult = {'dn': dn}
newresult['server'] = _("%(host)s failed") % dict(host=host)

View File

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

View File

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

View File

@ -706,7 +706,7 @@ class SessionAuthManager(object):
for auth_mgr in self.auth_managers.values():
try:
auth_mgr.logout(session_data)
except Exception, e:
except Exception as e:
self.error('%s auth_mgr logout failed: %s', auth_mgr.name, e)
#-------------------------------------------------------------------------------
@ -963,7 +963,7 @@ class MemcacheSessionManager(SessionManager):
try:
session_cookie = Cookie.get_named_cookie_from_string(cookie_header, self.session_cookie_name)
except Exception, e:
except Exception as e:
session_cookie = None
if session_cookie:
session_id = session_cookie.value
@ -1272,7 +1272,7 @@ def release_ipa_ccache(ccache_name):
if os.path.exists(name):
try:
os.unlink(name)
except Exception, e:
except Exception as e:
root_logger.error('unable to delete session ccache file "%s", %s', name, e)
else:
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,
' '.join(str(answer) for answer in answers))
)
except DNSException, e:
except DNSException as e:
log.debug(
'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,
' '.join(str(answer) for answer in answers))
)
except DNSException, e:
except DNSException as e:
log.debug(
'IPA: DNS AAAA record lookup failed for %s' % fqdn
)
@ -186,7 +186,7 @@ def check_writable_file(filename):
else:
fp = open(filename, 'w')
fp.close()
except (IOError, OSError), e:
except (IOError, OSError) as e:
raise errors.FileError(reason=str(e))
def normalize_zonemgr(zonemgr):
@ -287,13 +287,13 @@ def normalize_sshpubkey(value):
def validate_sshpubkey(ugettext, value):
try:
SSHPublicKey(value)
except ValueError, UnicodeDecodeError:
except ValueError as UnicodeDecodeError:
return _('invalid SSH public key')
def validate_sshpubkey_no_options(ugettext, value):
try:
pubkey = SSHPublicKey(value)
except ValueError, UnicodeDecodeError:
except ValueError as UnicodeDecodeError:
return _('invalid SSH public key')
if pubkey.has_options():
@ -313,7 +313,7 @@ def convert_sshpubkey_post(ldap, dn, entry_attrs):
for pubkey in pubkeys:
try:
pubkey = SSHPublicKey(pubkey)
except ValueError, UnicodeDecodeError:
except ValueError as UnicodeDecodeError:
continue
fp = pubkey.fingerprint_hex_md5()
@ -525,7 +525,7 @@ def get_reverse_zone_default(ip_address):
def validate_rdn_param(ugettext, value):
try:
rdn = RDN(value)
except Exception, e:
except Exception as e:
return str(e)
return None

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -185,7 +185,7 @@ class Cookie(object):
try:
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))
return dt
@ -594,7 +594,7 @@ class Cookie(object):
from ipalib.util import validate_domain_name
try:
validate_domain_name(url_domain)
except Exception, e:
except Exception as e:
return False
if cookie_domain is None:

View File

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

View File

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

View File

@ -168,7 +168,7 @@ class SchemaCache(object):
except ldap.SERVER_DOWN:
raise errors.NetworkError(uri=url,
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()
info = e.args[0].get('info', '').strip()
raise errors.DatabaseError(desc = u'uri=%s' % url,
@ -865,7 +865,7 @@ class LDAPClient(object):
return datetime.datetime.strptime(val, LDAP_GENERALIZED_TIME_FORMAT)
else:
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)
self.log.error(msg)
raise ValueError(msg)
@ -927,7 +927,7 @@ class LDAPClient(object):
yield
except ldap.TIMEOUT:
raise errors.DatabaseTimeout()
except ldap.LDAPError, e:
except ldap.LDAPError as e:
desc = e.args[0]['desc'].strip()
info = e.args[0].get('info', '').strip()
if arg_desc is not None:
@ -984,7 +984,7 @@ class LDAPClient(object):
raise errors.DatabaseError(desc=desc, info=info)
except ldap.AUTH_UNKNOWN:
raise errors.ACIError(info='%s (%s)' % (info,desc))
except ldap.LDAPError, e:
except ldap.LDAPError as e:
if 'NOT_ALLOWED_TO_DELEGATE' in info:
raise errors.ACIError(
info="KDC returned NOT_ALLOWED_TO_DELEGATE")
@ -1354,7 +1354,7 @@ class LDAPClient(object):
break
else:
cookie = ''
except ldap.LDAPError, e:
except ldap.LDAPError as e:
# If paged search is in progress, try to cancel it
if paged_search and cookie:
sctrls = [SimplePagedResultsControl(0, 0, cookie)]
@ -1363,7 +1363,7 @@ class LDAPClient(object):
str(base_dn), scope, filter, attrs_list,
serverctrls=sctrls, timeout=time_limit,
sizelimit=size_limit)
except ldap.LDAPError, e:
except ldap.LDAPError as e:
self.log.warning(
"Error cancelling paged search: %s", e)
cookie = ''
@ -1630,7 +1630,7 @@ class IPAdmin(LDAPClient):
pw_name = pwd.getpwuid(os.geteuid()).pw_name
self.do_external_bind(pw_name, timeout=timeout)
return
except errors.NotFound, e:
except errors.NotFound as e:
if autobind == AUTOBIND_ENABLED:
# autobind was required and failed, raise
# 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)
return True
except socket.error, e:
except socket.error as e:
pass
finally:
if s:
@ -824,14 +824,14 @@ def bind_port_responder(port, socket_type=socket.SOCK_STREAM, socket_timeout=Non
try:
addr_infos = socket.getaddrinfo(host, port, family, socket_type, 0,
socket.AI_PASSIVE)
except socket.error, e:
except socket.error as e:
last_socket_error = e
continue
for res in addr_infos:
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error, e:
except socket.error as e:
last_socket_error = e
s = None
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
# the exception back to him
raise
except socket.error, e:
except socket.error as e:
last_socket_error = e
s.close()
s = None
@ -1177,7 +1177,7 @@ def wait_for_open_socket(socket_name, timeout=0):
s.connect(socket_name)
s.close()
break
except socket.error, e:
except socket.error as e:
if e.errno in (2,111): # 111: Connection refused, 2: File not found
if timeout and time.time() > op_timeout: # timeout exceeded
raise e
@ -1298,7 +1298,7 @@ def restore_hostname(statestore):
if old_hostname is not None and old_hostname != system_hostname:
try:
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))

View File

@ -936,7 +936,7 @@ class LogManager(object):
if value is not None:
try:
level = parse_log_level(value)
except Exception, e:
except Exception as e:
raise ValueError("could not set %s (%s)" % (attr, e))
setattr(self, attr, level)
@ -1239,7 +1239,7 @@ class LogManager(object):
if level is not None:
try:
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)
level = 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
# and the strerror attribute will contain a string describing the reason.
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)
cert_is_valid = False
return cert_is_valid
@ -88,7 +88,7 @@ def auth_certificate_callback(sock, check_sig, is_server, certdb):
try:
# If the cert fails validation it will raise an exception
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)',
hostname, cert.subject, e.strerror)
cert_is_valid = False
@ -159,7 +159,7 @@ class NSSAddressFamilyFallback(object):
self._create_socket()
self.sock.connect(net_addr)
return
except Exception, e:
except Exception as e:
root_logger.debug("Could not connect socket to %s, error: %s",
net_addr, str(e))
root_logger.debug("Try to continue with next family...")
@ -199,7 +199,7 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
ssl.clear_session_cache()
try:
nss.nss_shutdown()
except NSPRError, e:
except NSPRError as e:
if e.errno != error.SEC_ERROR_NOT_INITIALIZED:
raise e
@ -236,7 +236,7 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
self.sock.set_ssl_option(ssl.SSL_HANDSHAKE_AS_CLIENT, True)
try:
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))
raise
self.sock.set_ssl_option(ssl_require_safe_negotiation, False)
@ -289,7 +289,7 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
httplib.HTTPConnection.endheaders(self)
else:
httplib.HTTPConnection.endheaders(self, message)
except NSPRError, e:
except NSPRError as e:
self.close()
raise e

View File

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

View File

@ -179,7 +179,7 @@ class DomainValidator(object):
self.sid = entry_attrs[self.ATTR_SID][0]
self.dn = entry_attrs.dn
self.domain = self.api.env.domain
except errors.NotFound, e:
except errors.NotFound as e:
return False
return True
@ -211,7 +211,7 @@ class DomainValidator(object):
trust_partner = entry[self.ATTR_TRUST_PARTNER][0]
flatname_normalized = entry[self.ATTR_FLATNAME][0].lower()
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
# Skip the domain, but leave log entry for investigation
api.log.warn("Trusted domain '%s' entry misses an "
@ -221,7 +221,7 @@ class DomainValidator(object):
result[trust_partner] = (flatname_normalized,
security.dom_sid(trusted_sid))
return result
except errors.NotFound, e:
except errors.NotFound as e:
return []
def set_trusted_domains(self):
@ -381,7 +381,7 @@ class DomainValidator(object):
try:
test_sid = security.dom_sid(sid)
return unicode(test_sid)
except TypeError, e:
except TypeError as e:
raise errors.ValidationError(name=_('trusted domain 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'])
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}"\
.format(host=host, port=str(port), err=str(e))
if quiet:
@ -742,11 +742,11 @@ class DomainValidator(object):
result = None
try:
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:
# 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)
except RuntimeError, e:
except RuntimeError as e:
finddc_error = e
if not self._domains:
@ -767,7 +767,7 @@ class DomainValidator(object):
try:
answers = resolver.query(gc_name, rdatatype.SRV)
except DNSException, e:
except DNSException as e:
answers = []
for answer in answers:
@ -838,9 +838,9 @@ class TrustDomainInstance(object):
self._pipe = self.__gen_lsa_connection(binding)
if self._pipe and self._pipe.session_key:
break
except errors.ACIError, e:
except errors.ACIError as e:
attempts = attempts + 1
except RuntimeError, e:
except RuntimeError as e:
# When session key is not available, we just skip this binding
session_attempts = session_attempts + 1
@ -880,7 +880,7 @@ class TrustDomainInstance(object):
result = netrc.finddc(domain=remote_host, flags=flags)
else:
result = netrc.finddc(address=remote_host, flags=flags)
except RuntimeError, e:
except RuntimeError as e:
raise assess_dcerpc_exception(message=str(e))
if not result:
@ -902,11 +902,11 @@ class TrustDomainInstance(object):
(objtype, res) = conn.search_s('', _ldap.SCOPE_BASE)[0]
search_result = res['defaultNamingContext'][0]
self.info['dns_hostname'] = res['dnsHostName'][0]
except _ldap.LDAPError, e:
except _ldap.LDAPError as e:
root_logger.error(
"LDAP error when connecting to %(host)s: %(error)s" %
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} "
"returned malformed. Your DNS might be "
"misconfigured."
@ -1035,7 +1035,7 @@ class TrustDomainInstance(object):
ftinfo, 0)
if 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
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_AES256_CTS_HMAC_SHA1_96
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
# improved security but the trust will work with default values as
# 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.trust_attributes |= lsa.LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE
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)))
pass
if self.info['is_pdc']:
@ -1213,7 +1213,7 @@ def fetch_domains(api, mydomain, trustdomain, creds=None, server=None):
else:
result = netrc.finddc(domain=trustdomain,
flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS)
except RuntimeError, e:
except RuntimeError as e:
raise assess_dcerpc_exception(message=str(e))
td.info['dc'] = unicode(result.pdc_dns_name)

View File

@ -71,7 +71,7 @@ def check_inst():
def ipa_smb_conf_exists():
try:
conf_fd = open(paths.SMB_CONF, 'r')
except IOError, err:
except IOError as err:
if err.errno == errno.ENOENT:
return False
@ -247,7 +247,7 @@ class ADTRUSTInstance(service.Service):
except errors.NotFound:
try:
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.")
raise e
else:
@ -291,7 +291,7 @@ class ADTRUSTInstance(service.Service):
except errors.NotFound:
try:
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.")
raise e
@ -358,7 +358,7 @@ class ADTRUSTInstance(service.Service):
str(self.rid_base)),
(ldap.MOD_ADD, "ipaSecondaryBaseRID",
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 "
"object:\n %s" % e[0]['info'])
raise RuntimeError("Constraint violation.\n")
@ -401,7 +401,7 @@ class ADTRUSTInstance(service.Service):
except errors.NotFound:
try:
name = new_dn[1].attr
except Exception, e:
except Exception as e:
self.print_msg('Cannot extract RDN attribute value from "%s": %s' % \
(new_dn, e))
return
@ -518,7 +518,7 @@ class ADTRUSTInstance(service.Service):
# adtrustinstance is managed
# That's fine, we we'll re-extract the key again.
pass
except Exception, e:
except Exception as e:
self.print_msg("Cannot add CIFS service: %s" % e)
self.clean_samba_keytab()
@ -536,7 +536,7 @@ class ADTRUSTInstance(service.Service):
try:
ipautil.run(["ipa-rmkeytab", "--principal", self.cifs_principal,
"-k", self.samba_keytab])
except ipautil.CalledProcessError, e:
except ipautil.CalledProcessError as e:
if e.returncode != 5:
root_logger.critical("Failed to remove old key for %s"
% self.cifs_principal)
@ -653,7 +653,7 @@ class ADTRUSTInstance(service.Service):
try:
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))
return
@ -689,7 +689,7 @@ class ADTRUSTInstance(service.Service):
# SRV records for _msdcs
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)
def __enable_compat_tree(self):
@ -703,7 +703,7 @@ class ADTRUSTInstance(service.Service):
if not(config[1] in lookup_nsswitch):
current[lookup_nsswitch_name] = [config[1]]
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)
def __enable_and_start_oddjobd(self):
@ -740,13 +740,13 @@ class ADTRUSTInstance(service.Service):
try:
self.ldap_enable('ADTRUST', self.fqdn, self.dm_password, \
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.")
try:
self.ldap_enable('EXTID', self.fqdn, self.dm_password, \
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.")
def __setup_sub_dict(self):

View File

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

View File

@ -248,7 +248,7 @@ def install_step_1(standalone, replica_config, options):
str(dogtag_constants.DOGTAG_VERSION))
with open(paths.IPA_DEFAULT_CONF, 'w') as f:
parser.write(f)
except IOError, e:
except IOError as e:
print "Failed to update /etc/ipa/default.conf"
root_logger.error(str(e))
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
try:
f = open(filename)
except IOError, e:
except IOError as e:
root_logger.error("Cannot open configuration file." + str(e))
raise e
data = f.read()
@ -752,7 +752,7 @@ class CAInstance(DogtagInstance):
nolog = (self.admin_password, self.dm_password,)
ipautil.run(args, env={'PKI_HOSTNAME':self.fqdn}, nolog=nolog)
except ipautil.CalledProcessError, e:
except ipautil.CalledProcessError as e:
self.handle_setup_error(e)
if self.external == 1:
@ -770,7 +770,7 @@ class CAInstance(DogtagInstance):
def backup_config(self):
try:
backup_config(self.dogtag_constants)
except Exception, e:
except Exception as e:
root_logger.warning("Failed to backup CS.cfg: %s", e)
def __disable_nonce(self):
@ -976,7 +976,7 @@ class CAInstance(DogtagInstance):
try:
return dogtag.get_ca_certchain(ca_host=self.fqdn,
dogtag_constants=self.dogtag_constants)
except Exception, e:
except Exception as e:
raise RuntimeError("Unable to retrieve CA chain: %s" % str(e))
def __create_ca_agent_pkcs12(self):
@ -1194,7 +1194,7 @@ class CAInstance(DogtagInstance):
"-pki_instance_name=%s" %
self.dogtag_constants.PKI_INSTANCE_NAME,
"--force"])
except ipautil.CalledProcessError, e:
except ipautil.CalledProcessError as e:
self.log.critical("failed to uninstall CA instance %s", e)
self.restore_state("installed")
@ -1234,7 +1234,7 @@ class CAInstance(DogtagInstance):
for f in get_crl_files():
self.log.debug("Remove %s", f)
installutils.remove_file(f)
except OSError, e:
except OSError as e:
self.log.warning("Error while removing old CRL files: %s", e)
# remove CRL directory
@ -1242,7 +1242,7 @@ class CAInstance(DogtagInstance):
if os.path.exists(self.dogtag_constants.CRL_PUBLISH_PATH):
try:
shutil.rmtree(self.dogtag_constants.CRL_PUBLISH_PATH)
except OSError, e:
except OSError as e:
self.log.warning("Error while removing CRL publish "
"directory: %s", e)
@ -1294,7 +1294,7 @@ class CAInstance(DogtagInstance):
secdir=paths.HTTPD_ALIAS_DIR,
pre_command=None,
post_command='renew_ra_cert')
except RuntimeError, e:
except RuntimeError as e:
self.log.error(
"certmonger failed to start tracking certificate: %s", e)
@ -1305,7 +1305,7 @@ class CAInstance(DogtagInstance):
try:
certmonger.stop_tracking(paths.HTTPD_ALIAS_DIR, nickname='ipaCert')
except RuntimeError, e:
except RuntimeError as e:
root_logger.error(
"certmonger failed to stop tracking certificate: %s", e)
@ -1418,7 +1418,7 @@ class CAInstance(DogtagInstance):
try:
backup_config(dogtag_constants)
except Exception, e:
except Exception as e:
syslog.syslog(syslog.LOG_ERR, "Failed to backup CS.cfg: %s" % e)
DogtagInstance.update_cert_cs_cfg(
@ -1613,7 +1613,7 @@ def update_people_entry(dercert):
conn.update_entry(entry)
except errors.EmptyModlist:
pass
except Exception, e:
except Exception as e:
syslog.syslog(
syslog.LOG_ERR,
'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)
time.sleep(30)
attempts += 1
except Exception, e:
except Exception as e:
syslog.syslog(syslog.LOG_ERR, 'Caught unhandled exception: %s' % e)
break
finally:

View File

@ -95,7 +95,7 @@ class CertDB(object):
self.subject_base = subject_base
try:
self.cwd = os.getcwd()
except OSError, e:
except OSError as e:
raise RuntimeError("Unable to determine the current directory: %s" % str(e))
if not subject_base:
@ -300,7 +300,7 @@ class CertDB(object):
command = paths.CERTMONGER_COMMAND_TEMPLATE % (libpath, command)
try:
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))
return
@ -316,7 +316,7 @@ class CertDB(object):
"""
try:
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))
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)
except ldap.TYPE_OR_VALUE_EXISTS:
pass
except Exception, e:
except Exception as e:
self.logger.critical("Could not modify principal's %s entry: %s"
% (dnssynckey_principal_dn, str(e)))
raise
@ -456,7 +456,7 @@ class DNSKeySyncInstance(service.Service):
(ldap.MOD_REPLACE, 'nsLookThroughLimit', '-1')]
try:
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"
% (dnssynckey_principal_dn, str(e)))
raise
@ -485,7 +485,7 @@ class DNSKeySyncInstance(service.Service):
for f in [paths.SYSCONFIG_NAMED]:
try:
self.fstore.restore_file(f)
except ValueError, error:
except ValueError as error:
self.logger.debug(error)
pass

View File

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

View File

@ -442,7 +442,7 @@ class DsInstance(service.Service):
try:
ipautil.run(args)
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)
# check for open port 389 from now on
@ -452,7 +452,7 @@ class DsInstance(service.Service):
try:
self.__restart_instance()
root_logger.debug("done restarting ds instance")
except ipautil.CalledProcessError, e:
except ipautil.CalledProcessError as e:
print "failed to restart ds instance", e
root_logger.debug("failed to restart ds instance %s" % e)
inf_fd.close()
@ -484,9 +484,9 @@ class DsInstance(service.Service):
if not is_ds_running(instance):
root_logger.critical("Failed to restart the directory server. See the installation log for details.")
sys.exit(1)
except SystemExit, e:
except SystemExit as e:
raise e
except Exception, e:
except Exception as e:
# TODO: roll back here?
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 }
ipautil.run(args, env=env)
root_logger.debug("ldappasswd done")
except ipautil.CalledProcessError, e:
except ipautil.CalledProcessError as e:
print "Unable to set admin password", e
root_logger.debug("Unable to set admin password %s" % e)
@ -793,7 +793,7 @@ class DsInstance(service.Service):
try:
self.fstore.restore_file(paths.LIMITS_CONF)
self.fstore.restore_file(paths.SYSCONFIG_DIRSRV)
except ValueError, error:
except ValueError as error:
root_logger.debug(error)
pass
@ -829,7 +829,7 @@ class DsInstance(service.Service):
for ds_instance in get_ds_instances():
try:
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)
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" %
cacert_fname)
return False
except OSError, e:
except OSError as e:
root_logger.critical("The given CA cert file named [%s] could not be read: %s" %
(cacert_fname, str(e)))
return False
@ -876,7 +876,7 @@ class DsInstance(service.Service):
status = True
try:
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" %
(cacert_fname, str(e)))
status = False
@ -1025,7 +1025,7 @@ class DsInstance(service.Service):
ret['result']['ipacertificatesubjectbase'][0])
root_logger.debug(
'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 '
'subject base: %s', e)
finally:

View File

@ -60,7 +60,7 @@ def httpd_443_configured():
"""
try:
(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("httpd returned error when checking: %s" % e)
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]:
try:
self.fstore.restore_file(f)
except ValueError, error:
except ValueError as error:
root_logger.debug(error)
pass

View File

@ -144,7 +144,7 @@ def verify_fqdn(host_name, no_host_dns=False, local_hostname=True):
try:
# make sure that the host name meets the requirements in ipalib
validate_hostname(host_name)
except ValueError, e:
except ValueError as e:
raise BadHostError("Invalid hostname '%s', %s" % (host_name, unicode(e)))
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]))
except socket.gaierror:
pass
except socket.error, e:
except socket.error as e:
root_logger.debug('socket.gethostbyaddr() error: %d: %s' % (e.errno, e.strerror))
if no_host_dns:
@ -167,7 +167,7 @@ def verify_fqdn(host_name, no_host_dns=False, local_hostname=True):
try:
root_logger.debug('Search DNS for %s', host_name)
hostaddr = socket.getaddrinfo(host_name, None)
except Exception, e:
except Exception as e:
root_logger.debug('Search failed: %s', e)
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:
root_logger.debug('Check reverse address of %s', address)
revname = socket.gethostbyaddr(address)[0]
except Exception, e:
except Exception as e:
root_logger.debug('Check failed: %s', e)
raise HostReverseLookupError(
"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)
try:
ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True)
except Exception, e:
except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e)
continue
else:
@ -273,7 +273,7 @@ def read_ip_addresses(host_name, fstore):
break
try:
ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True)
except Exception, e:
except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e)
continue
ips.append(ip_parsed)
@ -291,7 +291,7 @@ def read_dns_forwarders():
break
try:
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 "DNS forwarder %s not added." % ip
continue
@ -333,7 +333,7 @@ def read_password(user, confirm=True, validate=True, retry=True, validator=_read
if validate:
try:
validator(pwd)
except ValueError, e:
except ValueError as e:
print str(e)
pwd = None
continue
@ -490,7 +490,7 @@ def get_server_ip_address(host_name, fstore, unattended, setup_dns, ip_addresses
for ha in hostaddr:
try:
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))
if not ips and not ip_addresses:
@ -583,7 +583,7 @@ def read_replica_info_dogtag_port(config_dir):
with open(portfile) as fd:
try:
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('Default to %d', default_port)
dogtag_master_ds_port = default_port
@ -595,7 +595,7 @@ def create_replica_config(dirman_password, filename, options):
top_dir = None
try:
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.")
print "ERROR: Failed to decrypt or open the replica file."
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
try:
host = get_host_name(options.no_host_dns)
except BadHostError, e:
except BadHostError as e:
root_logger.error(str(e))
sys.exit(1)
if config.host_name != host:
@ -659,7 +659,7 @@ def remove_file(filename):
try:
if os.path.lexists(filename):
os.unlink(filename)
except Exception, e:
except Exception as e:
root_logger.error('Error removing %s: %s' % (filename, str(e)))
@ -670,7 +670,7 @@ def rmtree(path):
try:
if os.path.exists(path):
shutil.rmtree(path)
except Exception, e:
except Exception as 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:
return_value = main_function()
except BaseException, e:
except BaseException as e:
if isinstance(e, SystemExit) and (e.code is None or e.code == 0):
# Not an error after all
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)
sys.exit(return_value)
except BaseException, error:
except BaseException as error:
message, exitcode = handle_error(error, log_file_name)
if 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:]:
try:
nssdb.verify_ca_cert_validity(nickname)
except ValueError, e:
except ValueError as e:
raise ScriptError(
"CA certificate %s in %s is not valid: %s" %
(subject, ", ".join(cert_files), e))
@ -1020,7 +1020,7 @@ def load_external_cert(files, subject_base):
for nickname in trust_chain:
try:
nssdb.verify_ca_cert_validity(nickname)
except ValueError, e:
except ValueError as e:
raise ScriptError(
"CA certificate %s in %s is not valid: %s" %
(subject, ", ".join(files), e))

View File

@ -314,7 +314,7 @@ class Backup(admintool.AdminTool):
finally:
try:
os.chdir(cwd)
except Exception, e:
except Exception as e:
self.log.error('Cannot change directory to %s: %s' % (cwd, e))
shutil.rmtree(self.top_dir)
@ -368,7 +368,7 @@ class Backup(admintool.AdminTool):
try:
pw_name = pwd.getpwuid(os.geteuid()).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._conn.host, e))
@ -411,7 +411,7 @@ class Backup(admintool.AdminTool):
try:
conn.add_entry(ent)
except Exception, e:
except Exception as e:
raise admintool.ScriptError('Unable to add LDIF task: %s'
% e)
@ -459,7 +459,7 @@ class Backup(admintool.AdminTool):
try:
conn.add_entry(ent)
except Exception, e:
except Exception as e:
raise admintool.ScriptError('Unable to to add backup task: %s'
% e)
@ -523,7 +523,7 @@ class Backup(admintool.AdminTool):
except errors.NetworkError:
self.log.critical(
"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" %
(conn.host, e))
else:

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -319,11 +319,11 @@ class WinsyncMigrate(admintool.AdminTool):
ccache = ctx.default_ccache()
api.Backend.ldap2.connect(ccache)
cls.ldap = api.Backend.ldap2
except krbV.Krb5Error, e:
except krbV.Krb5Error as e:
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.")
except errors.DatabaseError, e:
except errors.DatabaseError as e:
sys.exit("Cannot connect to the LDAP database. Please check if IPA is running.")
super(WinsyncMigrate, cls).main(argv)

View File

@ -277,11 +277,11 @@ class KrbInstance(service.Service):
for r in res:
try:
self.admin_conn.delete_entry(r)
except Exception, e:
except Exception as e:
root_logger.critical(
"Error during SASL mapping removal: %s", e)
raise
except Exception, e:
except Exception as e:
root_logger.critical("Error while enumerating SASL mappings %s", e)
raise
@ -343,7 +343,7 @@ class KrbInstance(service.Service):
)
try:
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"
def __configure_instance(self):
@ -452,7 +452,7 @@ class KrbInstance(service.Service):
for f in [paths.KRB5KDC_KDC_CONF, paths.KRB5_CONF]:
try:
self.fstore.restore_file(f)
except ValueError, error:
except ValueError as error:
root_logger.debug(error)
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:
raise RuntimeError(
"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())
return conn
@ -335,7 +335,7 @@ class LDAPUpdate:
def _template_str(self, s):
try:
return ipautil.template_str(s, self.sub_dict)
except KeyError, e:
except KeyError as e:
raise BadSyntax("Unknown template keyword %s" % e)
def read_file(self, filename):
@ -565,10 +565,10 @@ class LDAPUpdate:
while True:
try:
entry = self.conn.get_entry(dn, attrlist)
except errors.NotFound, e:
except errors.NotFound as e:
self.error("Task not found: %s", dn)
return
except errors.DatabaseError, e:
except errors.DatabaseError as e:
self.error("Task lookup failure %s", e)
return
@ -783,7 +783,7 @@ class LDAPUpdate:
return
added = True
self.modified = True
except Exception, e:
except Exception as e:
self.error("Add failure %s", e)
else:
# Update LDAP
@ -802,10 +802,10 @@ class LDAPUpdate:
except errors.EmptyModlist:
self.debug("Entry already up-to-date")
updated = False
except errors.DatabaseError, e:
except errors.DatabaseError as e:
self.error("Update failed: %s", e)
updated = False
except errors.ACIError, e:
except errors.ACIError as e:
self.error("Update failed: %s", e)
updated = False
@ -829,10 +829,10 @@ class LDAPUpdate:
self.debug("Deleting entry %s", dn)
self.conn.delete_entry(dn)
self.modified = True
except errors.NotFound, e:
except errors.NotFound as e:
self.debug("%s did not exist:%s", dn, e)
self.modified = True
except errors.DatabaseError, e:
except errors.DatabaseError as e:
self.error("Delete failed: %s", e)
def get_all_files(self, root, recursive=False):
@ -897,7 +897,7 @@ class LDAPUpdate:
try:
self.debug("Parsing update file '%s'" % f)
data = self.read_file(f)
except Exception, e:
except Exception as e:
self.error("error reading update file '%s'", f)
raise RuntimeError(e)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -79,7 +79,7 @@ class GenerateUpdateMixin(object):
definitions_managed_entries, truncated = ldap.find_entries(
searchfilter, ['*'], old_definition_container,
ldap.SCOPE_ONELEVEL)
except errors.NotFound, e:
except errors.NotFound as e:
return (False, update_list)
for entry in definitions_managed_entries:
@ -89,7 +89,7 @@ class GenerateUpdateMixin(object):
assert isinstance(old_dn, DN)
try:
entry = ldap.get_entry(old_dn, ['*'])
except errors.NotFound, e:
except errors.NotFound as e:
pass
else:
# 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")
return False, []
except errors.ExecutionError, e:
except errors.ExecutionError as e:
root_logger.error("update_idrange_type: cannot retrieve list "
"of ranges with no type set: %s", e)
return False, []
@ -89,7 +89,7 @@ class update_idrange_type(Updater):
ldap.update_entry(entry)
except (errors.EmptyModlist, errors.NotFound):
pass
except errors.ExecutionError, e:
except errors.ExecutionError as e:
root_logger.debug("update_idrange_type: cannot "
"update idrange type: %s", e)
error = True
@ -137,7 +137,7 @@ class update_idrange_baserid(Updater):
"range with posix attributes found")
return False, []
except errors.ExecutionError, e:
except errors.ExecutionError as e:
root_logger.error("update_idrange_baserid: cannot retrieve "
"list of affected ranges: %s", e)
return False, []
@ -157,7 +157,7 @@ class update_idrange_baserid(Updater):
root_logger.info("Done")
except (errors.EmptyModlist, errors.NotFound):
pass
except errors.ExecutionError, e:
except errors.ExecutionError as e:
root_logger.debug("update_idrange_type: cannot "
"update idrange: %s", e)
error = True

View File

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

View File

@ -59,7 +59,7 @@ class update_upload_cacrt(Updater):
try:
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",
nickname, e)
continue

View File

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

View File

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

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