diff options
118 files changed, 661 insertions, 661 deletions
diff --git a/contrib/RHEL4/ipa-client-setup b/contrib/RHEL4/ipa-client-setup index 4d1fead98..1096889eb 100644 --- a/contrib/RHEL4/ipa-client-setup +++ b/contrib/RHEL4/ipa-client-setup @@ -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 diff --git a/contrib/RHEL4/ipachangeconf.py b/contrib/RHEL4/ipachangeconf.py index ac7ecf891..de1a215b7 100644 --- a/contrib/RHEL4/ipachangeconf.py +++ b/contrib/RHEL4/ipachangeconf.py @@ -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 diff --git a/daemons/dnssec/ipa-dnskeysyncd b/daemons/dnssec/ipa-dnskeysyncd index f2fce3e4e..93e1cd518 100755 --- a/daemons/dnssec/ipa-dnskeysyncd +++ b/daemons/dnssec/ipa-dnskeysyncd @@ -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 diff --git a/install/certmonger/dogtag-ipa-ca-renew-agent-submit b/install/certmonger/dogtag-ipa-ca-renew-agent-submit index e833a3187..c6fb2deb9 100755 --- a/install/certmonger/dogtag-ipa-ca-renew-agent-submit +++ b/install/certmonger/dogtag-ipa-ca-renew-agent-submit @@ -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) diff --git a/install/certmonger/ipa-server-guard b/install/certmonger/ipa-server-guard index 5e31d89b7..cd6654a09 100755 --- a/install/certmonger/ipa-server-guard +++ b/install/certmonger/ipa-server-guard @@ -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) diff --git a/install/migration/migration.py b/install/migration/migration.py index 8c440175a..e1823e151 100644 --- a/install/migration/migration.py +++ b/install/migration/migration.py @@ -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: diff --git a/install/po/pygettext.py b/install/po/pygettext.py index 4e4212eba..171bd4fc5 100755 --- a/install/po/pygettext.py +++ b/install/po/pygettext.py @@ -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: diff --git a/install/restart_scripts/renew_ca_cert b/install/restart_scripts/renew_ca_cert index 86f5765b7..8ad0473b5 100644 --- a/install/restart_scripts/renew_ca_cert +++ b/install/restart_scripts/renew_ca_cert @@ -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)) diff --git a/install/restart_scripts/renew_ra_cert b/install/restart_scripts/renew_ra_cert index 1f8fcae6f..24b8ba477 100644 --- a/install/restart_scripts/renew_ra_cert +++ b/install/restart_scripts/renew_ra_cert @@ -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") diff --git a/install/restart_scripts/restart_dirsrv b/install/restart_scripts/restart_dirsrv index 723644215..856729b5c 100644 --- a/install/restart_scripts/restart_dirsrv +++ b/install/restart_scripts/restart_dirsrv @@ -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))) diff --git a/install/restart_scripts/restart_httpd b/install/restart_scripts/restart_httpd index f060a3091..50348d4ef 100644 --- a/install/restart_scripts/restart_httpd +++ b/install/restart_scripts/restart_httpd @@ -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)) diff --git a/install/restart_scripts/stop_pkicad b/install/restart_scripts/stop_pkicad index 871e5e761..7a238706d 100644 --- a/install/restart_scripts/stop_pkicad +++ b/install/restart_scripts/stop_pkicad @@ -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: diff --git a/install/share/copy-schema-to-ca.py b/install/share/copy-schema-to-ca.py index fb111ca2a..ac49fcd59 100755 --- a/install/share/copy-schema-to-ca.py +++ b/install/share/copy-schema-to-ca.py @@ -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) diff --git a/install/share/wsgi.py b/install/share/wsgi.py index 9f7d3f487..eab612053 100644 --- a/install/share/wsgi.py +++ b/install/share/wsgi.py @@ -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 ***') diff --git a/install/tools/ipa-adtrust-install b/install/tools/ipa-adtrust-install index 21e58dd9f..a3037440c 100755 --- a/install/tools/ipa-adtrust-install +++ b/install/tools/ipa-adtrust-install @@ -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) diff --git a/install/tools/ipa-compat-manage b/install/tools/ipa-compat-manage index 7d9d20ccc..ee8ac6015 100755 --- a/install/tools/ipa-compat-manage +++ b/install/tools/ipa-compat-manage @@ -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 diff --git a/install/tools/ipa-csreplica-manage b/install/tools/ipa-csreplica-manage index 6f6c6c75a..3a5c78aa4 100755 --- a/install/tools/ipa-csreplica-manage +++ b/install/tools/ipa-csreplica-manage @@ -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) diff --git a/install/tools/ipa-managed-entries b/install/tools/ipa-managed-entries index 8ef82eca7..25404060d 100755 --- a/install/tools/ipa-managed-entries +++ b/install/tools/ipa-managed-entries @@ -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 diff --git a/install/tools/ipa-nis-manage b/install/tools/ipa-nis-manage index 51cd6c323..45b03c26f 100755 --- a/install/tools/ipa-nis-manage +++ b/install/tools/ipa-nis-manage @@ -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 diff --git a/install/tools/ipa-replica-conncheck b/install/tools/ipa-replica-conncheck index 22348fc21..653dee57a 100755 --- a/install/tools/ipa-replica-conncheck +++ b/install/tools/ipa-replica-conncheck @@ -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) diff --git a/install/tools/ipa-replica-manage b/install/tools/ipa-replica-manage index 50a57f70e..1c9c7d32c 100755 --- a/install/tools/ipa-replica-manage +++ b/install/tools/ipa-replica-manage @@ -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) diff --git a/install/tools/ipactl b/install/tools/ipactl index 52dfe67dd..f37c4e02c 100755 --- a/install/tools/ipactl +++ b/install/tools/ipactl @@ -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 diff --git a/install/wsgi/plugins.py b/install/wsgi/plugins.py index 64df08765..3ed8a4544 100644 --- a/install/wsgi/plugins.py +++ b/install/wsgi/plugins.py @@ -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() diff --git a/ipa-client/ipa-install/ipa-client-automount b/ipa-client/ipa-install/ipa-client-automount index eee141812..0739a2e6b 100755 --- a/ipa-client/ipa-install/ipa-client-automount +++ b/ipa-client/ipa-install/ipa-client-automount @@ -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) diff --git a/ipa-client/ipa-install/ipa-client-install b/ipa-client/ipa-install/ipa-client-install index 17cd2b687..0b6305f58 100755 --- a/ipa-client/ipa-install/ipa-client-install +++ b/ipa-client/ipa-install/ipa-client-install @@ -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: diff --git a/ipa-client/ipaclient/ipa_certupdate.py b/ipa-client/ipaclient/ipa_certupdate.py index 26e02ea33..720bd9a87 100644 --- a/ipa-client/ipaclient/ipa_certupdate.py +++ b/ipa-client/ipaclient/ipa_certupdate.py @@ -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) diff --git a/ipa-client/ipaclient/ipachangeconf.py b/ipa-client/ipaclient/ipachangeconf.py index 2c3185716..ed53c9dea 100644 --- a/ipa-client/ipaclient/ipachangeconf.py +++ b/ipa-client/ipaclient/ipachangeconf.py @@ -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 diff --git a/ipa-client/ipaclient/ipadiscovery.py b/ipa-client/ipaclient/ipadiscovery.py index 5e316837d..d21f3fbf5 100644 --- a/ipa-client/ipaclient/ipadiscovery.py +++ b/ipa-client/ipaclient/ipadiscovery.py @@ -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 = [] diff --git a/ipalib/backend.py b/ipalib/backend.py index d510bc733..240fae4b3 100644 --- a/ipalib/backend.py +++ b/ipalib/backend.py @@ -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) ) diff --git a/ipalib/certstore.py b/ipalib/certstore.py index 3a5555c95..533a77f91 100644 --- a/ipalib/certstore.py +++ b/ipalib/certstore.py @@ -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, diff --git a/ipalib/cli.py b/ipalib/cli.py index 4104e6482..52904eada 100644 --- a/ipalib/cli.py +++ b/ipalib/cli.py @@ -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: diff --git a/ipalib/frontend.py b/ipalib/frontend.py index 2ca3aaea8..1fe7ff0f0 100644 --- a/ipalib/frontend.py +++ b/ipalib/frontend.py @@ -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)) diff --git a/ipalib/krb_utils.py b/ipalib/krb_utils.py index 9a557ce5c..19cd0ad79 100644 --- a/ipalib/krb_utils.py +++ b/ipalib/krb_utils.py @@ -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 diff --git a/ipalib/parameters.py b/ipalib/parameters.py index 6cc6f8c92..7b27b70c2 100644 --- a/ipalib/parameters.py +++ b/ipalib/parameters.py @@ -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 diff --git a/ipalib/plugable.py b/ipalib/plugable.py index 45b346376..8b82b60f8 100644 --- a/ipalib/plugable.py +++ b/ipalib/plugable.py @@ -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, diff --git a/ipalib/plugins/aci.py b/ipalib/plugins/aci.py index 158909837..0ff28b84e 100644 --- a/ipalib/plugins/aci.py +++ b/ipalib/plugins/aci.py @@ -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: diff --git a/ipalib/plugins/automount.py b/ipalib/plugins/automount.py index 0a5c121ca..304bed71f 100644 --- a/ipalib/plugins/automount.py +++ b/ipalib/plugins/automount.py @@ -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 diff --git a/ipalib/plugins/baseldap.py b/ipalib/plugins/baseldap.py index 36a5d5f49..0fdc63eee 100644 --- a/ipalib/plugins/baseldap.py +++ b/ipalib/plugins/baseldap.py @@ -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. diff --git a/ipalib/plugins/batch.py b/ipalib/plugins/batch.py index 2002eef88..9b9ab6544 100644 --- a/ipalib/plugins/batch.py +++ b/ipalib/plugins/batch.py @@ -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( diff --git a/ipalib/plugins/cert.py b/ipalib/plugins/cert.py index 610f21493..c0b459d38 100644 --- a/ipalib/plugins/cert.py +++ b/ipalib/plugins/cert.py @@ -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 diff --git a/ipalib/plugins/dns.py b/ipalib/plugins/dns.py index 1de3f16c2..4376d83ce 100644 --- a/ipalib/plugins/dns.py +++ b/ipalib/plugins/dns.py @@ -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)) diff --git a/ipalib/plugins/group.py b/ipalib/plugins/group.py index edecebb06..381693cf1 100644 --- a/ipalib/plugins/group.py +++ b/ipalib/plugins/group.py @@ -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) diff --git a/ipalib/plugins/host.py b/ipalib/plugins/host.py index 3e882aefd..9d7748350 100644 --- a/ipalib/plugins/host.py +++ b/ipalib/plugins/host.py @@ -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: diff --git a/ipalib/plugins/migration.py b/ipalib/plugins/migration.py index 6aeb942ec..3d8d565e0 100644 --- a/ipalib/plugins/migration.py +++ b/ipalib/plugins/migration.py @@ -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! diff --git a/ipalib/plugins/otptoken.py b/ipalib/plugins/otptoken.py index a1e9a85a5..eb3e3f977 100644 --- a/ipalib/plugins/otptoken.py +++ b/ipalib/plugins/otptoken.py @@ -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) diff --git a/ipalib/plugins/permission.py b/ipalib/plugins/permission.py index 7d2a4dd15..1c636d8c0 100644 --- a/ipalib/plugins/permission.py +++ b/ipalib/plugins/permission.py @@ -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 diff --git a/ipalib/plugins/pwpolicy.py b/ipalib/plugins/pwpolicy.py index 165d54889..cb8ef29ee 100644 --- a/ipalib/plugins/pwpolicy.py +++ b/ipalib/plugins/pwpolicy.py @@ -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: diff --git a/ipalib/plugins/radiusproxy.py b/ipalib/plugins/radiusproxy.py index 5d8f3a727..e30f35f9d 100644 --- a/ipalib/plugins/radiusproxy.py +++ b/ipalib/plugins/radiusproxy.py @@ -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) diff --git a/ipalib/plugins/realmdomains.py b/ipalib/plugins/realmdomains.py index c53340591..871ea79c4 100644 --- a/ipalib/plugins/realmdomains.py +++ b/ipalib/plugins/realmdomains.py @@ -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) diff --git a/ipalib/plugins/service.py b/ipalib/plugins/service.py index a21d004c8..6d0299164 100644 --- a/ipalib/plugins/service.py +++ b/ipalib/plugins/service.py @@ -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')) diff --git a/ipalib/plugins/trust.py b/ipalib/plugins/trust.py index 940e06a5f..866a8fb67 100644 --- a/ipalib/plugins/trust.py +++ b/ipalib/plugins/trust.py @@ -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) diff --git a/ipalib/plugins/user.py b/ipalib/plugins/user.py index 859939205..121e107c1 100644 --- a/ipalib/plugins/user.py +++ b/ipalib/plugins/user.py @@ -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) diff --git a/ipalib/plugins/vault.py b/ipalib/plugins/vault.py index ba7696c7e..1150d5f3b 100644 --- a/ipalib/plugins/vault.py +++ b/ipalib/plugins/vault.py @@ -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 diff --git a/ipalib/rpc.py b/ipalib/rpc.py index 4176bbd28..04b8d01d9 100644 --- a/ipalib/rpc.py +++ b/ipalib/rpc.py @@ -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: diff --git a/ipalib/session.py b/ipalib/session.py index ec6c2081c..a124fe027 100644 --- a/ipalib/session.py +++ b/ipalib/session.py @@ -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) diff --git a/ipalib/util.py b/ipalib/util.py index 5a670146e..7baec85d6 100644 --- a/ipalib/util.py +++ b/ipalib/util.py @@ -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 diff --git a/ipalib/x509.py b/ipalib/x509.py index 092d451c6..21c287feb 100644 --- a/ipalib/x509.py +++ b/ipalib/x509.py @@ -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): diff --git a/ipaplatform/redhat/tasks.py b/ipaplatform/redhat/tasks.py index b26604aa7..5f8832432 100644 --- a/ipaplatform/redhat/tasks.py +++ b/ipaplatform/redhat/tasks.py @@ -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 diff --git a/ipapython/certdb.py b/ipapython/certdb.py index e3238c846..d6de01100 100644 --- a/ipapython/certdb.py +++ b/ipapython/certdb.py @@ -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 diff --git a/ipapython/certmonger.py b/ipapython/certmonger.py index 3a2907d83..1371c215d 100644 --- a/ipapython/certmonger.py +++ b/ipapython/certmonger.py @@ -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: diff --git a/ipapython/config.py b/ipapython/config.py index 60f556dc9..8b6b5ac93 100644 --- a/ipapython/config.py +++ b/ipapython/config.py @@ -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): diff --git a/ipapython/cookie.py b/ipapython/cookie.py index aed312a3a..c12e0a127 100644 --- a/ipapython/cookie.py +++ b/ipapython/cookie.py @@ -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: diff --git a/ipapython/dnsutil.py b/ipapython/dnsutil.py index f08cddad9..228cb6629 100644 --- a/ipapython/dnsutil.py +++ b/ipapython/dnsutil.py @@ -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) diff --git a/ipapython/dogtag.py b/ipapython/dogtag.py index 0782d360c..99bdf066d 100644 --- a/ipapython/dogtag.py +++ b/ipapython/dogtag.py @@ -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) diff --git a/ipapython/ipaldap.py b/ipapython/ipaldap.py index ef7c41a37..3d38d6050 100644 --- a/ipapython/ipaldap.py +++ b/ipapython/ipaldap.py @@ -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 diff --git a/ipapython/ipautil.py b/ipapython/ipautil.py index 05a7eebf0..280858ce7 100644 --- a/ipapython/ipautil.py +++ b/ipapython/ipautil.py @@ -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)) diff --git a/ipapython/log_manager.py b/ipapython/log_manager.py index 9625bdfb7..cf3611e0f 100644 --- a/ipapython/log_manager.py +++ b/ipapython/log_manager.py @@ -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: diff --git a/ipapython/nsslib.py b/ipapython/nsslib.py index def6b104e..1fb69cbd1 100644 --- a/ipapython/nsslib.py +++ b/ipapython/nsslib.py @@ -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 diff --git a/ipapython/sysrestore.py b/ipapython/sysrestore.py index 935e4c6ce..a542b28c9 100644 --- a/ipapython/sysrestore.py +++ b/ipapython/sysrestore.py @@ -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] diff --git a/ipaserver/dcerpc.py b/ipaserver/dcerpc.py index 5428d0e38..639f89ff5 100644 --- a/ipaserver/dcerpc.py +++ b/ipaserver/dcerpc.py @@ -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) diff --git a/ipaserver/install/adtrustinstance.py b/ipaserver/install/adtrustinstance.py index ff0e8cc3e..701a605be 100644 --- a/ipaserver/install/adtrustinstance.py +++ b/ipaserver/install/adtrustinstance.py @@ -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): diff --git a/ipaserver/install/bindinstance.py b/ipaserver/install/bindinstance.py index 6d3470373..4a09d3685 100644 --- a/ipaserver/install/bindinstance.py +++ b/ipaserver/install/bindinstance.py @@ -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 diff --git a/ipaserver/install/ca.py b/ipaserver/install/ca.py index 39f4435e2..557efedf7 100644 --- a/ipaserver/install/ca.py +++ b/ipaserver/install/ca.py @@ -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) diff --git a/ipaserver/install/cainstance.py b/ipaserver/install/cainstance.py index c1fa1fc27..60c41b6d2 100644 --- a/ipaserver/install/cainstance.py +++ b/ipaserver/install/cainstance.py @@ -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: diff --git a/ipaserver/install/certs.py b/ipaserver/install/certs.py index e8084950e..3e07ee398 100644 --- a/ipaserver/install/certs.py +++ b/ipaserver/install/certs.py @@ -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): diff --git a/ipaserver/install/dnskeysyncinstance.py b/ipaserver/install/dnskeysyncinstance.py index f593b7134..2036a56be 100644 --- a/ipaserver/install/dnskeysyncinstance.py +++ b/ipaserver/install/dnskeysyncinstance.py @@ -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 diff --git a/ipaserver/install/dogtaginstance.py b/ipaserver/install/dogtaginstance.py index 33f39f793..c377bfe2b 100644 --- a/ipaserver/install/dogtaginstance.py +++ b/ipaserver/install/dogtaginstance.py @@ -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) diff --git a/ipaserver/install/dsinstance.py b/ipaserver/install/dsinstance.py index 45a523e9b..2657e2f99 100644 --- a/ipaserver/install/dsinstance.py +++ b/ipaserver/install/dsinstance.py @@ -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: diff --git a/ipaserver/install/httpinstance.py b/ipaserver/install/httpinstance.py index 7dcdda03d..a176acb97 100644 --- a/ipaserver/install/httpinstance.py +++ b/ipaserver/install/httpinstance.py @@ -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 diff --git a/ipaserver/install/installutils.py b/ipaserver/install/installutils.py index 02e852631..61bb552de 100644 --- a/ipaserver/install/installutils.py +++ b/ipaserver/install/installutils.py @@ -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)) diff --git a/ipaserver/install/ipa_backup.py b/ipaserver/install/ipa_backup.py index 685c618d8..36f666044 100644 --- a/ipaserver/install/ipa_backup.py +++ b/ipaserver/install/ipa_backup.py @@ -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: diff --git a/ipaserver/install/ipa_cacert_manage.py b/ipaserver/install/ipa_cacert_manage.py index 01ec805fc..34a931d1a 100644 --- a/ipaserver/install/ipa_cacert_manage.py +++ b/ipaserver/install/ipa_cacert_manage.py @@ -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) diff --git a/ipaserver/install/ipa_ldap_updater.py b/ipaserver/install/ipa_ldap_updater.py index f07eecf23..2c4f28af4 100644 --- a/ipaserver/install/ipa_ldap_updater.py +++ b/ipaserver/install/ipa_ldap_updater.py @@ -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) diff --git a/ipaserver/install/ipa_replica_prepare.py b/ipaserver/install/ipa_replica_prepare.py index 55cdb8ad2..b33bff631 100644 --- a/ipaserver/install/ipa_replica_prepare.py +++ b/ipaserver/install/ipa_replica_prepare.py @@ -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): diff --git a/ipaserver/install/ipa_restore.py b/ipaserver/install/ipa_restore.py index 62b31c580..65cb49355 100644 --- a/ipaserver/install/ipa_restore.py +++ b/ipaserver/install/ipa_restore.py @@ -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)) diff --git a/ipaserver/install/ipa_server_certinstall.py b/ipaserver/install/ipa_server_certinstall.py index d1c3bfd9d..e90b2abd6 100644 --- a/ipaserver/install/ipa_server_certinstall.py +++ b/ipaserver/install/ipa_server_certinstall.py @@ -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 diff --git a/ipaserver/install/ipa_winsync_migrate.py b/ipaserver/install/ipa_winsync_migrate.py index cbe068458..73f79249a 100644 --- a/ipaserver/install/ipa_winsync_migrate.py +++ b/ipaserver/install/ipa_winsync_migrate.py @@ -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) diff --git a/ipaserver/install/krbinstance.py b/ipaserver/install/krbinstance.py index b34d00601..874914826 100644 --- a/ipaserver/install/krbinstance.py +++ b/ipaserver/install/krbinstance.py @@ -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 diff --git a/ipaserver/install/ldapupdate.py b/ipaserver/install/ldapupdate.py index 6f796dfdc..1f3aca542 100644 --- a/ipaserver/install/ldapupdate.py +++ b/ipaserver/install/ldapupdate.py @@ -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) diff --git a/ipaserver/install/ntpinstance.py b/ipaserver/install/ntpinstance.py index cdab0ae26..4904defb8 100644 --- a/ipaserver/install/ntpinstance.py +++ b/ipaserver/install/ntpinstance.py @@ -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 diff --git a/ipaserver/install/odsexporterinstance.py b/ipaserver/install/odsexporterinstance.py index 51b0f3efc..ddf2ebf36 100644 --- a/ipaserver/install/odsexporterinstance.py +++ b/ipaserver/install/odsexporterinstance.py @@ -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 diff --git a/ipaserver/install/opendnssecinstance.py b/ipaserver/install/opendnssecinstance.py index a62fa667c..e8192cdc2 100644 --- a/ipaserver/install/opendnssecinstance.py +++ b/ipaserver/install/opendnssecinstance.py @@ -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 diff --git a/ipaserver/install/plugins/dns.py b/ipaserver/install/plugins/dns.py index 3d40e0e3a..6d7c81c98 100644 --- a/ipaserver/install/plugins/dns.py +++ b/ipaserver/install/plugins/dns.py @@ -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'])) diff --git a/ipaserver/install/plugins/fix_replica_agreements.py b/ipaserver/install/plugins/fix_replica_agreements.py index 1381c7cce..106f66a45 100644 --- a/ipaserver/install/plugins/fix_replica_agreements.py +++ b/ipaserver/install/plugins/fix_replica_agreements.py @@ -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: diff --git a/ipaserver/install/plugins/rename_managed.py b/ipaserver/install/plugins/rename_managed.py index 16477cf9d..9cff18b76 100644 --- a/ipaserver/install/plugins/rename_managed.py +++ b/ipaserver/install/plugins/rename_managed.py @@ -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 diff --git a/ipaserver/install/plugins/update_idranges.py b/ipaserver/install/plugins/update_idranges.py index badde9453..9a005b8a4 100644 --- a/ipaserver/install/plugins/update_idranges.py +++ b/ipaserver/install/plugins/update_idranges.py @@ -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 diff --git a/ipaserver/install/plugins/update_services.py b/ipaserver/install/plugins/update_services.py index 975480d7b..c52d3c45c 100644 --- a/ipaserver/install/plugins/update_services.py +++ b/ipaserver/install/plugins/update_services.py @@ -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 diff --git a/ipaserver/install/plugins/upload_cacrt.py b/ipaserver/install/plugins/upload_cacrt.py index db34e1cb7..ddca4baba 100644 --- a/ipaserver/install/plugins/upload_cacrt.py +++ b/ipaserver/install/plugins/upload_cacrt.py @@ -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 diff --git a/ipaserver/install/replication.py b/ipaserver/install/replication.py index 2b36a5eb9..78b75503d 100644 --- a/ipaserver/install/replication.py +++ b/ipaserver/install/replication.py @@ -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): diff --git a/ipaserver/install/server/install.py b/ipaserver/install/server/install.py index 2ef187667..967538334 100644 --- a/ipaserver/install/server/install.py +++ b/ipaserver/install/server/install.py @@ -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 diff --git a/ipaserver/install/server/replicainstall.py b/ipaserver/install/server/replicainstall.py index ea3b902b8..ac0f6a32c 100644 --- a/ipaserver/install/server/replicainstall.py +++ b/ipaserver/install/server/replicainstall.py @@ -106,7 +106,7 @@ def install_ca_cert(ldap, base_dn, realm, cafile): x509.write_certificate_list(certs, constants.CACERT) os.chmod(constants.CACERT, 0o444) - except Exception, e: + except Exception as e: print "error copying files: " + str(e) sys.exit(1) @@ -137,7 +137,7 @@ def install_http(config, auto_redirect): if ipautil.file_exists(config.dir + "/configure.jar"): shutil.copy(config.dir + "/configure.jar", paths.CONFIGURE_JAR) - except Exception, e: + except Exception as e: print "error copying files: " + str(e) sys.exit(1) @@ -167,12 +167,12 @@ def install_dns_records(config, options, remote_api): reverse_zone, not options.no_ntp, options.setup_ca) - except errors.NotFound, e: + except errors.NotFound as e: root_logger.debug('Replica DNS records could not be added ' 'on master: %s', str(e)) # we should not fail here no matter what - except Exception, e: + except Exception as e: root_logger.info('Replica DNS records could not be added ' 'on master: %s', str(e)) @@ -247,7 +247,7 @@ def check_dns_resolution(host_name, dns_servers): address, host_name) revname = dnsreversename.from_address(address) rrset = resolver.query(revname, 'PTR').rrset - except Exception, e: + except Exception as e: root_logger.debug('Check failed: %s %s', type(e).__name__, e) root_logger.error( 'Reverse DNS resolution of address %s (%s) failed. ' @@ -333,7 +333,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" % e.conflicting_service) print "be disabled in favor of ntpd" @@ -627,7 +627,7 @@ def install(installer): if options.mkhomedir: args.append("--mkhomedir") ipautil.run(args) - except Exception, e: + except Exception as e: print "Configuration of client side components failed!" print "ipa-client-install returned: " + str(e) raise RuntimeError("Failed to configure the client") diff --git a/ipaserver/install/server/upgrade.py b/ipaserver/install/server/upgrade.py index f9f2d75f9..d7480d7cd 100644 --- a/ipaserver/install/server/upgrade.py +++ b/ipaserver/install/server/upgrade.py @@ -321,7 +321,7 @@ def ca_enable_ldap_profile_subsystem(ca): if value == 'com.netscape.cmscore.profile.ProfileSubsystem': needs_update = True break - except OSError, e: + except OSError as e: root_logger.error('Cannot read CA configuration file "%s": %s', caconfig.CS_CFG_PATH, e) return False @@ -447,7 +447,7 @@ def named_set_minimum_connections(): bindinstance.named_conf_set_directive('connections', minimum_connections) root_logger.debug('Connections set to %d', minimum_connections) - except IOError, e: + except IOError as e: root_logger.error('Cannot update connections in %s: %s', bindinstance.NAMED_CONF, e) else: @@ -492,7 +492,7 @@ def named_enable_serial_autoincrement(): try: bindinstance.named_conf_set_directive('serial_autoincrement', 'yes') - except IOError, e: + except IOError as e: root_logger.error('Cannot enable serial_autoincrement in %s: %s', bindinstance.NAMED_CONF, e) return changed @@ -530,7 +530,7 @@ def named_update_gssapi_configuration(): try: gssapi_keytab = bindinstance.named_conf_get_directive('tkey-gssapi-keytab', bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot retrieve tkey-gssapi-keytab option from %s: %s', bindinstance.NAMED_CONF, e) return False @@ -545,7 +545,7 @@ def named_update_gssapi_configuration(): bindinstance.NAMED_SECTION_OPTIONS) tkey_domain = bindinstance.named_conf_get_directive('tkey-domain', bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot retrieve tkey-gssapi-credential option from %s: %s', bindinstance.NAMED_CONF, e) return False @@ -565,7 +565,7 @@ def named_update_gssapi_configuration(): bindinstance.named_conf_set_directive( 'tkey-gssapi-keytab', paths.NAMED_KEYTAB, bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot update GSSAPI configuration in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -594,7 +594,7 @@ def named_update_pid_file(): try: pid_file = bindinstance.named_conf_get_directive('pid-file', bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot retrieve pid-file option from %s: %s', bindinstance.NAMED_CONF, e) return False @@ -607,7 +607,7 @@ def named_update_pid_file(): try: bindinstance.named_conf_set_directive('pid-file', paths.NAMED_PID, bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot update pid-file configuration in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -632,7 +632,7 @@ def named_enable_dnssec(): bindinstance.named_conf_set_directive('dnssec-enable', 'yes', bindinstance.NAMED_SECTION_OPTIONS, str_val=False) - except IOError, e: + except IOError as e: root_logger.error('Cannot update dnssec-enable configuration in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -664,7 +664,7 @@ def named_validate_dnssec(): bindinstance.named_conf_set_directive('dnssec-validation', 'no', bindinstance.NAMED_SECTION_OPTIONS, str_val=False) - except IOError, e: + except IOError as e: root_logger.error('Cannot update dnssec-validate configuration in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -690,7 +690,7 @@ def named_bindkey_file_option(): try: bindkey_file = bindinstance.named_conf_get_directive('bindkey-file', bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot retrieve bindkey-file option from %s: %s', bindinstance.NAMED_CONF, e) return False @@ -705,7 +705,7 @@ def named_bindkey_file_option(): bindinstance.named_conf_set_directive('bindkeys-file', paths.NAMED_BINDKEYS_FILE, bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot update bindkeys-file configuration in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -730,7 +730,7 @@ def named_managed_keys_dir_option(): try: managed_keys = bindinstance.named_conf_get_directive('managed-keys-directory', bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot retrieve managed-keys-directory option from %s: %s', bindinstance.NAMED_CONF, e) return False @@ -745,7 +745,7 @@ def named_managed_keys_dir_option(): bindinstance.named_conf_set_directive('managed-keys-directory', paths.NAMED_MANAGED_KEYS_DIR, bindinstance.NAMED_SECTION_OPTIONS) - except IOError, e: + except IOError as e: root_logger.error('Cannot update managed-keys-directory configuration in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -769,7 +769,7 @@ def named_root_key_include(): try: root_key = bindinstance.named_conf_include_exists(paths.NAMED_ROOT_KEY) - except IOError, e: + except IOError as e: root_logger.error('Cannot check root key include in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -782,7 +782,7 @@ def named_root_key_include(): root_logger.info('[Including named root key in named.conf]') try: bindinstance.named_conf_add_include(paths.NAMED_ROOT_KEY) - except IOError, e: + except IOError as e: root_logger.error('Cannot update named root key include in %s: %s', bindinstance.NAMED_CONF, e) return False @@ -959,7 +959,7 @@ def migrate_crl_publish_dir(ca): old_publish_dir = installutils.get_directive(caconfig.CS_CFG_PATH, 'ca.publish.publisher.instance.FileBaseCRLPublisher.directory', separator='=') - except OSError, e: + except OSError as e: root_logger.error('Cannot read CA configuration file "%s": %s', caconfig.CS_CFG_PATH, e) return False @@ -978,7 +978,7 @@ def migrate_crl_publish_dir(ca): root_logger.info('Copy all CRLs to new publish directory') try: crl_files_unsorted = cainstance.get_crl_files(old_publish_dir) - except OSError, e: + except OSError as e: root_logger.error('Cannot move CRL files to new directory: %s', e) else: # Move CRL files at the end of the list to make sure that the actual @@ -1031,7 +1031,7 @@ def add_ca_dns_records(): if not api.Backend.ldap2.isconnected(): try: api.Backend.ldap2.connect(autobind=True) - except ipalib.errors.PublicError, e: + except ipalib.errors.PublicError as e: root_logger.error( "Cannot connect to LDAP to add DNS records: %s", e) return @@ -1227,7 +1227,7 @@ def fix_trust_flags(): if not api.Backend.ldap2.isconnected(): try: api.Backend.ldap2.connect(autobind=True) - except ipalib.errors.PublicError, e: + except ipalib.errors.PublicError as e: root_logger.error("Cannot connect to LDAP: %s", e) return diff --git a/ipaserver/install/service.py b/ipaserver/install/service.py index 2f5f565b1..ac65f7b09 100644 --- a/ipaserver/install/service.py +++ b/ipaserver/install/service.py @@ -145,7 +145,7 @@ class Service(object): conn = ipaldap.IPAdmin(self.fqdn, port=389) conn.do_bind(self.dm_password, autobind=self.autobind) - except Exception, e: + except Exception as e: root_logger.debug("Could not connect to the Directory Server on %s: %s" % (self.fqdn, str(e))) raise @@ -198,7 +198,7 @@ class Service(object): try: try: ipautil.run(args, nolog=nologlist) - except ipautil.CalledProcessError, e: + except ipautil.CalledProcessError as e: root_logger.critical("Failed to load %s: %s" % (ldif, str(e))) finally: if pw_name: @@ -282,7 +282,7 @@ class Service(object): entry.setdefault('userCertificate', []).append(self.dercert) try: self.admin_conn.update_entry(entry) - except Exception, e: + except Exception as e: root_logger.critical("Could not add certificate to service %s entry: %s" % (self.principal, str(e))) def import_ca_certs(self, db, ca_is_configured, conn=None): @@ -476,7 +476,7 @@ class Service(object): try: self.admin_conn.add_entry(entry) - except (errors.DuplicateEntry), e: + except (errors.DuplicateEntry) as e: root_logger.debug("failed to add service %s startup entry", name) raise e diff --git a/ipaserver/install/sysupgrade.py b/ipaserver/install/sysupgrade.py index 19e017d90..7d1b929a2 100644 --- a/ipaserver/install/sysupgrade.py +++ b/ipaserver/install/sysupgrade.py @@ -51,5 +51,5 @@ def remove_upgrade_state(module, state): def remove_upgrade_file(): try: os.remove(os.path.join(paths.STATEFILE_DIR, STATEFILE_FILE)) - except Exception, e: + except Exception as e: root_logger.debug('Cannot remove sysupgrade state file: %s', e) diff --git a/ipaserver/rpcserver.py b/ipaserver/rpcserver.py index ead830def..70d6c070c 100644 --- a/ipaserver/rpcserver.py +++ b/ipaserver/rpcserver.py @@ -345,11 +345,11 @@ class WSGIExecutioner(Executioner): raise CommandError(name=name) else: result = self.Command[name](*args, **options) - except PublicError, e: + except PublicError as e: if self.api.env.debug: self.debug('WSGI wsgi_execute PublicError: %s', traceback.format_exc()) error = e - except StandardError, e: + except StandardError as e: self.exception( 'non-public: %s: %s', e.__class__.__name__, str(e) ) @@ -361,7 +361,7 @@ class WSGIExecutioner(Executioner): if name and name in self.Command: try: params = self.Command[name].args_options_2_params(*args, **options) - except Exception, e: + except Exception as e: self.info( 'exception %s caught when converting options: %s', e.__class__.__name__, str(e) ) @@ -402,7 +402,7 @@ class WSGIExecutioner(Executioner): status = HTTP_STATUS_SUCCESS response = self.wsgi_execute(environ) headers = [('Content-Type', self.content_type + '; charset=utf-8')] - except StandardError, e: + except StandardError as e: self.exception('WSGI %s.__call__():', self.name) status = HTTP_STATUS_SERVER_ERROR response = status @@ -470,7 +470,7 @@ class jsonserver(WSGIExecutioner, HTTP_Status): def unmarshal(self, data): try: d = json.loads(data) - except ValueError, e: + except ValueError as e: raise JSONError(error=e) if not isinstance(d, dict): raise JSONError(error=_('Request must be a dict')) @@ -548,7 +548,7 @@ class KerberosSession(object): seconds = parse_time_duration(self.api.env.session_auth_duration) self.session_auth_duration = int(seconds) self.debug("session_auth_duration: %s", datetime.timedelta(seconds=self.session_auth_duration)) - except Exception, e: + except Exception as e: self.session_auth_duration = default_max_session_duration self.error('unable to parse session_auth_duration, defaulting to %d: %s', self.session_auth_duration, e) @@ -645,7 +645,7 @@ class KerberosWSGIExecutioner(WSGIExecutioner, HTTP_Status, KerberosSession): if (session_data is None and self.env.context != 'lite'): self.finalize_kerberos_acquisition( 'xmlserver', user_ccache, environ, start_response, headers) - except PublicError, e: + except PublicError as e: status = HTTP_STATUS_SUCCESS response = status start_response(status, headers) @@ -806,7 +806,7 @@ class jsonserver_session(jsonserver, KerberosSession): # This may fail if a ticket from wrong realm was handled via browser try: self.create_context(ccache=ipa_ccache_name) - except ACIError, e: + except ACIError as e: return self.unauthorized(environ, start_response, str(e), 'denied') try: @@ -888,7 +888,7 @@ class login_password(Backend, KerberosSession, HTTP_Status): try: query_dict = urlparse.parse_qs(query_string) - except Exception, e: + except Exception as e: return self.bad_request(environ, start_response, "cannot parse query data") user = query_dict.get('user', None) @@ -1009,7 +1009,7 @@ class change_password(Backend, HTTP_Status): try: query_dict = urlparse.parse_qs(query_string) - except Exception, e: + except Exception as e: return self.bad_request(environ, start_response, "cannot parse query data") data = {} @@ -1044,18 +1044,18 @@ class change_password(Backend, HTTP_Status): except (NotFound, ACIError): result = 'invalid-password' message = 'The old password or username is not correct.' - except Exception, e: + except Exception as e: message = "Could not connect to LDAP server." self.error("change_password: cannot authenticate '%s' to LDAP server: %s", data['user'], str(e)) else: try: conn.modify_password(bind_dn, data['new_password'], data['old_password'], skip_bind=True) - except ExecutionError, e: + except ExecutionError as e: result = 'policy-error' policy_error = escape(str(e)) message = "Password change was rejected: %s" % escape(str(e)) - except Exception, e: + except Exception as e: message = "Could not change the password" self.error("change_password: cannot change password of '%s': %s", data['user'], str(e)) @@ -1111,7 +1111,7 @@ class sync_token(Backend, HTTP_Status): # Parse the query string to a dictionary. try: query_dict = urlparse.parse_qs(query_string) - except Exception, e: + except Exception as e: return self.bad_request(environ, start_response, "cannot parse query data") data = {} for field in ('user', 'password', 'first_code', 'second_code', 'token'): @@ -1160,7 +1160,7 @@ class sync_token(Backend, HTTP_Status): except (NotFound, ACIError): result = 'invalid-credentials' message = 'The username, password or token codes are not correct.' - except Exception, e: + except Exception as e: result = 'error' message = "Could not connect to LDAP server." self.error("token_sync: cannot authenticate '%s' to LDAP server: %s", diff --git a/ipatests/i18n.py b/ipatests/i18n.py index 7d31e4d87..369871658 100755 --- a/ipatests/i18n.py +++ b/ipatests/i18n.py @@ -415,7 +415,7 @@ def validate_file(file_path, validation_mode, reference_pot=None): try: po = polib.pofile(file_path) - except Exception, e: + except Exception as e: error_lines.append(entry_seperator) error_lines.append('Unable to parse file "%s": %s' % (file_path, e)) n_errors += 1 @@ -528,7 +528,7 @@ def create_po(pot_file, po_file, mo_file): return 1 try: po = polib.pofile(pot_file) - except Exception, e: + except Exception as e: print >>sys.stderr, 'Unable to parse file "%s": %s' % (pot_file, e) return 1 @@ -619,7 +619,7 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural): return 1 try: po = polib.pofile(po_file) - except Exception, e: + except Exception as e: print >>sys.stderr, 'Unable to parse file "%s": %s' % (po_file, e) return 1 @@ -638,7 +638,7 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural): n_translations += 1 validate_unicode_edit(msgid, msgstr) n_valid += 1 - except Exception, e: + except Exception as e: n_fail += 1 if print_traceback: traceback.print_exc() @@ -648,7 +648,7 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural): n_translations += 1 validate_unicode_edit(msgid_plural, msgstr_plural) n_valid += 1 - except Exception, e: + except Exception as e: n_fail += 1 if print_traceback: traceback.print_exc() @@ -663,7 +663,7 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural): n_translations += 1 validate_unicode_edit(msgid, msgstr) n_valid += 1 - except Exception, e: + except Exception as e: n_fail += 1 if print_traceback: traceback.print_exc() @@ -671,7 +671,7 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural): n_entries += 1 - except Exception, e: + except Exception as e: if print_traceback: traceback.print_exc() print >> sys.stderr, "ERROR: %s" % e diff --git a/ipatests/ipa-test-task b/ipatests/ipa-test-task index 8c9ab082f..192814c48 100755 --- a/ipatests/ipa-test-task +++ b/ipatests/ipa-test-task @@ -287,7 +287,7 @@ class TaskRunner(object): try: return args.func(args) - except Exception, e: + except Exception as e: if args.with_beakerlib: beakerlib_process.log_exception() beakerlib_process.run_beakerlib_command( diff --git a/ipatests/test_cmdline/cmdline.py b/ipatests/test_cmdline/cmdline.py index a7ed67793..0ae8cc079 100644 --- a/ipatests/test_cmdline/cmdline.py +++ b/ipatests/test_cmdline/cmdline.py @@ -42,7 +42,7 @@ try: server_available = True except errors.DatabaseError: server_available = False -except Exception, e: +except Exception as e: server_available = False class cmdline_test(XMLRPC_test): diff --git a/ipatests/test_cmdline/test_ipagetkeytab.py b/ipatests/test_cmdline/test_ipagetkeytab.py index bc948bf09..2b99c268e 100644 --- a/ipatests/test_cmdline/test_ipagetkeytab.py +++ b/ipatests/test_cmdline/test_ipagetkeytab.py @@ -48,7 +48,7 @@ def use_keytab(principal, keytab): conn = ldap2(api) conn.connect(ccache=ccache) conn.disconnect() - except krbV.Krb5Error, e: + except krbV.Krb5Error as e: raise StandardError('Unable to bind to LDAP. Error initializing principal %s in %s: %s' % (principal.name, keytab, str(e))) finally: del os.environ['KRB5CCNAME'] @@ -111,7 +111,7 @@ class test_ipagetkeytab(cmdline_test): expected = 'Keytab successfully retrieved and stored in: %s\n' % ( self.keytabname) assert expected in err, 'Success message not in output:\n%s' % err - except ipautil.CalledProcessError, e: + except ipautil.CalledProcessError as e: assert (False) def test_3_use(self): @@ -141,7 +141,7 @@ class test_ipagetkeytab(cmdline_test): """ try: use_keytab(self.service_princ, self.keytabname) - except StandardError, errmsg: + except StandardError as errmsg: assert('Unable to bind to LDAP. Error initializing principal' in str(errmsg)) def test_9_cleanup(self): diff --git a/ipatests/test_ipalib/test_rpc.py b/ipatests/test_ipalib/test_rpc.py index b61337474..dd24d055c 100644 --- a/ipatests/test_ipalib/test_rpc.py +++ b/ipatests/test_ipalib/test_rpc.py @@ -274,7 +274,7 @@ class test_xml_introspection(object): def test_list_methods_many_params(self): try: result = api.Backend.xmlclient.conn.system.listMethods('foo') - except Fault, f: + except Fault as f: print f assert f.faultCode == 3003 assert f.faultString == ( @@ -294,7 +294,7 @@ class test_xml_introspection(object): def test_signature_no_params(self): try: result = api.Backend.xmlclient.conn.system.methodSignature() - except Fault, f: + except Fault as f: print f assert f.faultCode == 3007 assert f.faultString == "'method name' is required" @@ -304,7 +304,7 @@ class test_xml_introspection(object): def test_signature_many_params(self): try: result = api.Backend.xmlclient.conn.system.methodSignature('a', 'b') - except Fault, f: + except Fault as f: print f assert f.faultCode == 3004 assert f.faultString == ( @@ -315,7 +315,7 @@ class test_xml_introspection(object): def test_help_no_params(self): try: result = api.Backend.xmlclient.conn.system.methodHelp() - except Fault, f: + except Fault as f: print f assert f.faultCode == 3007 assert f.faultString == "'method name' is required" @@ -325,7 +325,7 @@ class test_xml_introspection(object): def test_help_many_params(self): try: result = api.Backend.xmlclient.conn.system.methodHelp('a', 'b') - except Fault, f: + except Fault as f: print f assert f.faultCode == 3004 assert f.faultString == ( diff --git a/ipatests/test_ipapython/test_keyring.py b/ipatests/test_ipapython/test_keyring.py index e92b1b465..bd876ea77 100644 --- a/ipatests/test_ipapython/test_keyring.py +++ b/ipatests/test_ipapython/test_keyring.py @@ -59,7 +59,7 @@ class test_keyring(object): # Make sure it is gone try: result = kernel_keyring.read_key(TEST_KEY) - except ValueError, e: + except ValueError as e: assert e.message == 'key %s not found' % TEST_KEY def test_02(self): diff --git a/ipatests/test_ipapython/test_ssh.py b/ipatests/test_ipapython/test_ssh.py index db136a898..913ff8e6b 100644 --- a/ipatests/test_ipapython/test_ssh.py +++ b/ipatests/test_ipapython/test_ssh.py @@ -30,7 +30,7 @@ def make_public_key_checker(pk, out): try: parsed = ssh.SSHPublicKey(pk) assert parsed.openssh() == out - except Exception, e: + except Exception as e: assert type(e) is out check_public_key.description = "Test SSH public key parsing (%s)" % repr(pk) return check_public_key diff --git a/ipatests/test_ipaserver/test_changepw.py b/ipatests/test_ipaserver/test_changepw.py index 30d7b1dff..1a2f57e8a 100644 --- a/ipatests/test_ipaserver/test_changepw.py +++ b/ipatests/test_ipaserver/test_changepw.py @@ -37,7 +37,7 @@ class test_changepw(XMLRPC_test, Unauthorized_HTTP_test): try: api.Command['user_add'](uid=testuser, givenname=u'Test', sn=u'User') api.Command['passwd'](testuser, password=u'old_password') - except errors.ExecutionError, e: + except errors.ExecutionError as e: raise nose.SkipTest( 'Cannot set up test user: %s' % e ) diff --git a/ipatests/test_pkcs10/test_pkcs10.py b/ipatests/test_pkcs10/test_pkcs10.py index c5a1c56b1..86314dfe5 100644 --- a/ipatests/test_pkcs10/test_pkcs10.py +++ b/ipatests/test_pkcs10/test_pkcs10.py @@ -111,7 +111,7 @@ class test_update(object): try: request = pkcs10.load_certificate_request(csr) - except NSPRError, nsprerr: + except NSPRError as nsprerr: # (SEC_ERROR_BAD_DER) security library: improperly formatted DER-encoded message. assert(nsprerr. errno== -8183) @@ -122,5 +122,5 @@ class test_update(object): csr = self.read_file("test4.csr") try: request = pkcs10.load_certificate_request(csr) - except TypeError, typeerr: + except TypeError as typeerr: assert(str(typeerr) == 'Incorrect padding') diff --git a/ipatests/test_webui/ui_driver.py b/ipatests/test_webui/ui_driver.py index 4b382d8fb..16af5ff16 100644 --- a/ipatests/test_webui/ui_driver.py +++ b/ipatests/test_webui/ui_driver.py @@ -144,9 +144,9 @@ class UI_driver(object): try: with open(path, 'r') as conf: self.config = yaml.load(conf) - except yaml.YAMLError, e: + except yaml.YAMLError as e: raise nose.SkipTest("Invalid Web UI config.\n%s" % e) - except IOError, e: + except IOError as e: raise nose.SkipTest("Can't load Web UI test config: %s" % e) else: self.config = {} @@ -198,9 +198,9 @@ class UI_driver(object): driver = webdriver.Remote( command_executor='http://%s:%d/wd/hub' % (host, port), desired_capabilities=capabilities) - except URLError, e: + except URLError as e: raise nose.SkipTest('Error connecting to selenium server: %s' % e) - except RuntimeError, e: + except RuntimeError as e: raise nose.SkipTest('Error while establishing webdriver: %s' % e) else: try: @@ -213,9 +213,9 @@ class UI_driver(object): if "ff_profile" in self.config: fp = webdriver.FirefoxProfile(self.config["ff_profile"]) driver = webdriver.Firefox(fp) - except URLError, e: + except URLError as e: raise nose.SkipTest('Error connecting to selenium server: %s' % e) - except RuntimeError, e: + except RuntimeError as e: raise nose.SkipTest('Error while establishing webdriver: %s' % e) return driver diff --git a/ipatests/test_xmlrpc/test_sudorule_plugin.py b/ipatests/test_xmlrpc/test_sudorule_plugin.py index 052578666..f654a94b5 100644 --- a/ipatests/test_xmlrpc/test_sudorule_plugin.py +++ b/ipatests/test_xmlrpc/test_sudorule_plugin.py @@ -494,7 +494,7 @@ class test_sudorule(XMLRPC_test): self.rule_name, addattr='externalhost=%s' % self.test_invalid_host ) - except errors.ValidationError, e: + except errors.ValidationError as e: assert unicode(e) == ("invalid 'externalhost': only letters, " + "numbers, '_', '-' are allowed. " + "DNS label may not start or end with '-'") diff --git a/ipatests/test_xmlrpc/xmlrpc_test.py b/ipatests/test_xmlrpc/xmlrpc_test.py index 808abae19..0db211118 100644 --- a/ipatests/test_xmlrpc/xmlrpc_test.py +++ b/ipatests/test_xmlrpc/xmlrpc_test.py @@ -311,7 +311,7 @@ class Declarative(XMLRPC_test): name = klass.__name__ try: output = api.Command[cmd](*args, **options) - except StandardError, e: + except StandardError as e: pass else: raise AssertionError( @@ -334,7 +334,7 @@ class Declarative(XMLRPC_test): e = None try: output = api.Command[cmd](*args, **options) - except StandardError, e: + except StandardError as e: pass if not expected(e, output): raise AssertionError( diff --git a/ipatests/util.py b/ipatests/util.py index a8899cc6f..9b6eed7ad 100644 --- a/ipatests/util.py +++ b/ipatests/util.py @@ -361,7 +361,7 @@ def raises(exception, callback, *args, **kw): raised = False try: callback(*args, **kw) - except exception, e: + except exception as e: raised = True if not raised: raise ExceptionNotRaised(exception) |