From c0f5bf53ec760f72c50b4ad96fa7b82b1329a76e Mon Sep 17 00:00:00 2001 From: akun <6awkun@gmail.com> Date: Thu, 1 Feb 2018 22:08:09 +0800 Subject: [PATCH] Refactoring for Python 3 `except` * 2to3 `ls | grep -v thirdparty` -f except --- extra/cloak/cloak.py | 2 +- extra/dbgtool/dbgtool.py | 2 +- extra/safe2bin/safe2bin.py | 2 +- extra/shutils/regressiontest.py | 4 ++-- extra/sqlharvest/sqlharvest.py | 4 ++-- lib/controller/action.py | 6 +++--- lib/controller/checks.py | 8 +++---- lib/controller/controller.py | 2 +- lib/core/bigarray.py | 6 +++--- lib/core/common.py | 30 +++++++++++++-------------- lib/core/dump.py | 10 ++++----- lib/core/option.py | 26 +++++++++++------------ lib/core/profiling.py | 2 +- lib/core/replication.py | 6 +++--- lib/core/shell.py | 4 ++-- lib/core/subprocessng.py | 10 ++++----- lib/core/target.py | 20 +++++++++--------- lib/core/testing.py | 6 +++--- lib/core/threads.py | 8 +++---- lib/core/update.py | 2 +- lib/core/wordlist.py | 4 ++-- lib/parse/cmdline.py | 6 +++--- lib/parse/configfile.py | 4 ++-- lib/parse/payloads.py | 4 ++-- lib/request/basic.py | 2 +- lib/request/connect.py | 10 ++++----- lib/request/dns.py | 2 +- lib/request/httpshandler.py | 4 ++-- lib/request/redirecthandler.py | 4 ++-- lib/utils/api.py | 10 ++++----- lib/utils/crawler.py | 6 +++--- lib/utils/hash.py | 6 +++--- lib/utils/hashdb.py | 8 +++---- lib/utils/pivotdumptable.py | 2 +- lib/utils/purge.py | 2 +- lib/utils/search.py | 10 ++++----- lib/utils/sqlalchemy.py | 8 +++---- lib/utils/timeout.py | 2 +- plugins/dbms/access/connector.py | 8 +++---- plugins/dbms/db2/connector.py | 8 +++---- plugins/dbms/firebird/connector.py | 8 +++---- plugins/dbms/hsqldb/connector.py | 8 +++---- plugins/dbms/informix/connector.py | 8 +++---- plugins/dbms/mssqlserver/connector.py | 8 +++---- plugins/dbms/mysql/connector.py | 10 ++++----- plugins/dbms/oracle/connector.py | 8 +++---- plugins/dbms/postgresql/connector.py | 8 +++---- plugins/dbms/sqlite/connector.py | 10 ++++----- plugins/dbms/sybase/connector.py | 8 +++---- plugins/generic/connector.py | 2 +- plugins/generic/custom.py | 2 +- plugins/generic/entries.py | 4 ++-- 52 files changed, 177 insertions(+), 177 deletions(-) diff --git a/extra/cloak/cloak.py b/extra/cloak/cloak.py index d98f6d09d..7dd34ea25 100644 --- a/extra/cloak/cloak.py +++ b/extra/cloak/cloak.py @@ -60,7 +60,7 @@ def main(): if not args.inputFile: parser.error('Missing the input file, -h for help') - except (OptionError, TypeError), e: + except (OptionError, TypeError) as e: parser.error(e) if not os.path.isfile(args.inputFile): diff --git a/extra/dbgtool/dbgtool.py b/extra/dbgtool/dbgtool.py index 3dc07a836..de6a38710 100644 --- a/extra/dbgtool/dbgtool.py +++ b/extra/dbgtool/dbgtool.py @@ -87,7 +87,7 @@ if __name__ == "__main__": if not args.inputFile: parser.error("Missing the input file, -h for help") - except (OptionError, TypeError), e: + except (OptionError, TypeError) as e: parser.error(e) inputFile = args.inputFile diff --git a/extra/safe2bin/safe2bin.py b/extra/safe2bin/safe2bin.py index c4f9ac13f..0287323ec 100644 --- a/extra/safe2bin/safe2bin.py +++ b/extra/safe2bin/safe2bin.py @@ -109,7 +109,7 @@ def main(): if not args.inputFile: parser.error('Missing the input file, -h for help') - except (OptionError, TypeError), e: + except (OptionError, TypeError) as e: parser.error(e) if not os.path.isfile(args.inputFile): diff --git a/extra/shutils/regressiontest.py b/extra/shutils/regressiontest.py index 9a3217b3c..b034007b5 100755 --- a/extra/shutils/regressiontest.py +++ b/extra/shutils/regressiontest.py @@ -57,7 +57,7 @@ def send_email(msg): s.sendmail(FROM, TO, msg.as_string()) s.quit() # Catch all for SMTP exceptions - except smtplib.SMTPException, e: + except smtplib.SMTPException as e: print("Failure to send email: %s" % str(e)) def failure_email(msg): @@ -158,7 +158,7 @@ if __name__ == "__main__": try: main() - except Exception, e: + except Exception as e: log_fd.write("An exception has occurred:\n%s" % str(traceback.format_exc())) log_fd.write("Regression test finished at %s\n\n" % time.strftime("%H:%M:%S %d-%m-%Y", time.gmtime())) diff --git a/extra/sqlharvest/sqlharvest.py b/extra/sqlharvest/sqlharvest.py index e7c34df96..6c4579985 100644 --- a/extra/sqlharvest/sqlharvest.py +++ b/extra/sqlharvest/sqlharvest.py @@ -76,7 +76,7 @@ def main(): except KeyboardInterrupt: raise - except Exception, msg: + except Exception as msg: print(msg) if abort: @@ -119,7 +119,7 @@ def main(): except KeyboardInterrupt: raise - except Exception, msg: + except Exception as msg: print(msg) else: diff --git a/lib/controller/action.py b/lib/controller/action.py index a05e8f7f4..5870937e0 100644 --- a/lib/controller/action.py +++ b/lib/controller/action.py @@ -75,7 +75,7 @@ def action(): if conf.getPasswordHashes: try: conf.dumper.userSettings("database management system users password hashes", conf.dbmsHandler.getPasswordHashes(), "password hash", CONTENT_TYPE.PASSWORDS) - except SqlmapNoneDataException, ex: + except SqlmapNoneDataException as ex: logger.critical(ex) except: raise @@ -83,7 +83,7 @@ def action(): if conf.getPrivileges: try: conf.dumper.userSettings("database management system users privileges", conf.dbmsHandler.getPrivileges(), "privilege", CONTENT_TYPE.PRIVILEGES) - except SqlmapNoneDataException, ex: + except SqlmapNoneDataException as ex: logger.critical(ex) except: raise @@ -91,7 +91,7 @@ def action(): if conf.getRoles: try: conf.dumper.userSettings("database management system users roles", conf.dbmsHandler.getRoles(), "role", CONTENT_TYPE.ROLES) - except SqlmapNoneDataException, ex: + except SqlmapNoneDataException as ex: logger.critical(ex) except: raise diff --git a/lib/controller/checks.py b/lib/controller/checks.py index ff238e978..717ffacba 100644 --- a/lib/controller/checks.py +++ b/lib/controller/checks.py @@ -602,7 +602,7 @@ def checkSqlInjection(place, parameter, value): injectable = True - except SqlmapConnectionException, msg: + except SqlmapConnectionException as msg: debugMsg = "problem occurred most likely because the " debugMsg += "server hasn't recovered as expected from the " debugMsg += "error-based payload used ('%s')" % msg @@ -1405,7 +1405,7 @@ def identifyWaf(): try: logger.debug("checking for WAF/IPS/IDS product '%s'" % product) found = function(_) - except Exception, ex: + except Exception as ex: errMsg = "exception occurred while running " errMsg += "WAF script for '%s' ('%s')" % (product, getSafeExString(ex)) logger.critical(errMsg) @@ -1506,7 +1506,7 @@ def checkConnection(suppressOutput=False): except socket.gaierror: errMsg = "host '%s' does not exist" % conf.hostname raise SqlmapConnectionException(errMsg) - except socket.error, ex: + except socket.error as ex: errMsg = "problem occurred while " errMsg += "resolving a host name '%s' ('%s')" % (conf.hostname, getSafeExString(ex)) raise SqlmapConnectionException(errMsg) @@ -1537,7 +1537,7 @@ def checkConnection(suppressOutput=False): else: kb.errorIsNone = True - except SqlmapConnectionException, ex: + except SqlmapConnectionException as ex: if conf.ipv6: warnMsg = "check connection to a provided " warnMsg += "IPv6 address with a tool like ping6 " diff --git a/lib/controller/controller.py b/lib/controller/controller.py index 27708c867..bb97b235e 100644 --- a/lib/controller/controller.py +++ b/lib/controller/controller.py @@ -674,7 +674,7 @@ def start(): except SqlmapSilentQuitException: raise - except SqlmapBaseException, ex: + except SqlmapBaseException as ex: errMsg = getSafeExString(ex) if conf.multipleTargets: diff --git a/lib/core/bigarray.py b/lib/core/bigarray.py index f733b81cb..005be9d35 100644 --- a/lib/core/bigarray.py +++ b/lib/core/bigarray.py @@ -87,7 +87,7 @@ class BigArray(list): try: with open(self.chunks[-1], "rb") as f: self.chunks[-1] = pickle.loads(bz2.decompress(f.read())) - except IOError, ex: + except IOError as ex: errMsg = "exception occurred while retrieving data " errMsg += "from a temporary file ('%s')" % ex.message raise SqlmapSystemException, errMsg @@ -109,7 +109,7 @@ class BigArray(list): with open(filename, "w+b") as f: f.write(bz2.compress(pickle.dumps(chunk, pickle.HIGHEST_PROTOCOL), BIGARRAY_COMPRESS_LEVEL)) return filename - except (OSError, IOError), ex: + except (OSError, IOError) as ex: errMsg = "exception occurred while storing data " errMsg += "to a temporary file ('%s'). Please " % ex.message errMsg += "make sure that there is enough disk space left. If problem persists, " @@ -126,7 +126,7 @@ class BigArray(list): try: with open(self.chunks[index], "rb") as f: self.cache = Cache(index, pickle.loads(bz2.decompress(f.read())), False) - except IOError, ex: + except IOError as ex: errMsg = "exception occurred while retrieving data " errMsg += "from a temporary file ('%s')" % ex.message raise SqlmapSystemException, errMsg diff --git a/lib/core/common.py b/lib/core/common.py index 6b36d1ec0..fc4766bc6 100644 --- a/lib/core/common.py +++ b/lib/core/common.py @@ -943,7 +943,7 @@ def dataToTrafficFile(data): try: conf.trafficFP.write(data) conf.trafficFP.flush() - except IOError, ex: + except IOError as ex: errMsg = "something went wrong while trying " errMsg += "to write to the traffic file '%s' ('%s')" % (conf.trafficFile, getSafeExString(ex)) raise SqlmapSystemException(errMsg) @@ -952,7 +952,7 @@ def dataToDumpFile(dumpFile, data): try: dumpFile.write(data) dumpFile.flush() - except IOError, ex: + except IOError as ex: if "No space left" in getUnicode(ex): errMsg = "no space left on output device" logger.error(errMsg) @@ -972,7 +972,7 @@ def dataToOutFile(filename, data): try: with open(retVal, "w+b") as f: # has to stay as non-codecs because data is raw ASCII encoded data f.write(unicodeencode(data)) - except UnicodeEncodeError, ex: + except UnicodeEncodeError as ex: _ = normalizeUnicode(filename) if filename != _: filename = _ @@ -980,7 +980,7 @@ def dataToOutFile(filename, data): errMsg = "couldn't write to the " errMsg += "output file ('%s')" % getSafeExString(ex) raise SqlmapGenericException(errMsg) - except IOError, ex: + except IOError as ex: errMsg = "something went wrong while trying to write " errMsg += "to the output file ('%s')" % getSafeExString(ex) raise SqlmapGenericException(errMsg) @@ -1429,7 +1429,7 @@ def parseTargetUrl(): try: urlSplit = urlparse.urlsplit(conf.url) - except ValueError, ex: + except ValueError as ex: errMsg = "invalid URL '%s' has been given ('%s'). " % (conf.url, getSafeExString(ex)) errMsg += "Please be sure that you don't have any leftover characters (e.g. '[' or ']') " errMsg += "in the hostname part" @@ -2001,7 +2001,7 @@ def parseXmlFile(xmlFile, handler): try: with contextlib.closing(StringIO(readCachedFileContent(xmlFile))) as stream: parse(stream, handler) - except (SAXParseException, UnicodeError), ex: + except (SAXParseException, UnicodeError) as ex: errMsg = "something appears to be wrong with " errMsg += "the file '%s' ('%s'). Please make " % (xmlFile, getSafeExString(ex)) errMsg += "sure that you haven't made any changes to it" @@ -2061,7 +2061,7 @@ def readCachedFileContent(filename, mode='rb'): try: with openFile(filename, mode) as f: kb.cache.content[filename] = f.read() - except (IOError, OSError, MemoryError), ex: + except (IOError, OSError, MemoryError) as ex: errMsg = "something went wrong while trying " errMsg += "to read the content of file '%s' ('%s')" % (filename, getSafeExString(ex)) raise SqlmapSystemException(errMsg) @@ -2175,7 +2175,7 @@ def getFileItems(filename, commentPrefix='#', unicode_=True, lowercase=False, un retVal[line] = True else: retVal.append(line) - except (IOError, OSError, MemoryError), ex: + except (IOError, OSError, MemoryError) as ex: errMsg = "something went wrong while trying " errMsg += "to read the content of file '%s' ('%s')" % (filename, getSafeExString(ex)) raise SqlmapSystemException(errMsg) @@ -2308,7 +2308,7 @@ def getUnicode(value, encoding=None, noneToNull=False): while True: try: return unicode(value, encoding or (kb.get("pageEncoding") if kb.get("originalPage") else None) or UNICODE_ENCODING) - except UnicodeDecodeError, ex: + except UnicodeDecodeError as ex: try: return unicode(value, UNICODE_ENCODING) except: @@ -2364,7 +2364,7 @@ def pushValue(value): getCurrentThreadData().valueStack.append(copy.deepcopy(value)) success = True break - except Exception, ex: + except Exception as ex: _ = ex if not success: @@ -3052,7 +3052,7 @@ def saveConfig(conf, filename): with openFile(filename, "wb") as f: try: config.write(f) - except IOError, ex: + except IOError as ex: errMsg = "something went wrong while trying " errMsg += "to write to the configuration file '%s' ('%s')" % (filename, getSafeExString(ex)) raise SqlmapSystemException(errMsg) @@ -3380,7 +3380,7 @@ def createGithubIssue(errMsg, excMsg): try: content = urllib2.urlopen(req).read() - except Exception, ex: + except Exception as ex: content = None issueUrl = re.search(r"https://github.com/sqlmapproject/sqlmap/issues/\d+", content or "") @@ -3990,7 +3990,7 @@ def findPageForms(content, url, raise_=False, addToTargets=False): continue request = form.click() - except (ValueError, TypeError), ex: + except (ValueError, TypeError) as ex: errMsg = "there has been a problem while " errMsg += "processing page forms ('%s')" % getSafeExString(ex) if raise_: @@ -4111,7 +4111,7 @@ def evaluateCode(code, variables=None): exec(code, variables) except KeyboardInterrupt: raise - except Exception, ex: + except Exception as ex: errMsg = "an error occurred while evaluating provided code ('%s') " % getSafeExString(ex) raise SqlmapGenericException(errMsg) @@ -4318,7 +4318,7 @@ def resetCookieJar(cookieJar): errMsg = "no valid cookies found" raise SqlmapGenericException(errMsg) - except cookielib.LoadError, msg: + except cookielib.LoadError as msg: errMsg = "there was a problem loading " errMsg += "cookies file ('%s')" % re.sub(r"(cookies) file '[^']+'", "\g<1>", str(msg)) raise SqlmapGenericException(errMsg) diff --git a/lib/core/dump.py b/lib/core/dump.py index 33f68e63d..803cbf1d2 100644 --- a/lib/core/dump.py +++ b/lib/core/dump.py @@ -78,7 +78,7 @@ class Dump(object): try: self._outputFP.write(text) - except IOError, ex: + except IOError as ex: errMsg = "error occurred while writing to log file ('%s')" % getSafeExString(ex) raise SqlmapGenericException(errMsg) @@ -98,7 +98,7 @@ class Dump(object): self._outputFile = os.path.join(conf.outputPath, "log") try: self._outputFP = openFile(self._outputFile, "ab" if not conf.flushSession else "wb") - except IOError, ex: + except IOError as ex: errMsg = "error occurred while opening log file ('%s')" % getSafeExString(ex) raise SqlmapGenericException(errMsg) @@ -425,10 +425,10 @@ class Dump(object): if not os.path.isdir(dumpDbPath): try: os.makedirs(dumpDbPath, 0755) - except Exception, ex: + except Exception as ex: try: tempDir = tempfile.mkdtemp(prefix="sqlmapdb") - except IOError, _: + except IOError as _: errMsg = "unable to write to the temporary directory ('%s'). " % _ errMsg += "Please make sure that your disk is not full and " errMsg += "that you have sufficient write permissions to " @@ -622,7 +622,7 @@ class Dump(object): with open(filepath, "wb") as f: _ = safechardecode(value, True) f.write(_) - except magic.MagicException, err: + except magic.MagicException as err: logger.debug(str(err)) if conf.dumpFormat == DUMP_FORMAT.CSV: diff --git a/lib/core/option.py b/lib/core/option.py index 0cfc3caa1..c4e8e5051 100644 --- a/lib/core/option.py +++ b/lib/core/option.py @@ -353,7 +353,7 @@ def _feedTargetsDict(reqFile, addedTargetUrls): try: with openFile(reqFile, "rb") as f: content = f.read() - except (IOError, OSError, MemoryError), ex: + except (IOError, OSError, MemoryError) as ex: errMsg = "something went wrong while trying " errMsg += "to read the content of file '%s' ('%s')" % (reqFile, getSafeExString(ex)) raise SqlmapSystemException(errMsg) @@ -398,7 +398,7 @@ def _loadQueries(): tree = ElementTree() try: tree.parse(paths.QUERIES_XML) - except Exception, ex: + except Exception as ex: errMsg = "something appears to be wrong with " errMsg += "the file '%s' ('%s'). Please make " % (paths.QUERIES_XML, getSafeExString(ex)) errMsg += "sure that you haven't made any changes to it" @@ -514,7 +514,7 @@ def _setCrawler(): if conf.verbose in (1, 2): status = "%d/%d links visited (%d%%)" % (i + 1, len(targets), round(100.0 * (i + 1) / len(targets))) dataToStdout("\r[%s] [INFO] %s" % (time.strftime("%X"), status), True) - except Exception, ex: + except Exception as ex: errMsg = "problem occurred while crawling at '%s' ('%s')" % (target, getSafeExString(ex)) logger.error(errMsg) @@ -650,7 +650,7 @@ def _findPageForms(): dataToStdout("\r[%s] [INFO] %s" % (time.strftime("%X"), status), True) except KeyboardInterrupt: break - except Exception, ex: + except Exception as ex: errMsg = "problem occurred while searching for forms at '%s' ('%s')" % (target, getSafeExString(ex)) logger.error(errMsg) @@ -931,7 +931,7 @@ def _setTamperingFunctions(): try: module = __import__(filename[:-3].encode(sys.getfilesystemencoding() or UNICODE_ENCODING)) - except Exception, ex: + except (ImportError, SyntaxError) as ex: raise SqlmapSyntaxException("cannot import tamper script '%s' (%s)" % (filename[:-3], getSafeExString(ex))) priority = PRIORITY.NORMAL if not hasattr(module, "__priority__") else module.__priority__ @@ -1004,7 +1004,7 @@ def _setWafFunctions(): if filename[:-3] in sys.modules: del sys.modules[filename[:-3]] module = __import__(filename[:-3].encode(sys.getfilesystemencoding() or UNICODE_ENCODING)) - except ImportError, msg: + except ImportError as msg: raise SqlmapSyntaxException("cannot import WAF script '%s' (%s)" % (filename[:-3], msg)) _ = dict(inspect.getmembers(module)) @@ -1126,7 +1126,7 @@ def _setHTTPHandlers(): try: _ = urlparse.urlsplit(conf.proxy) - except Exception, ex: + except Exception as ex: errMsg = "invalid proxy address '%s' ('%s')" % (conf.proxy, getSafeExString(ex)) raise SqlmapSyntaxException, errMsg @@ -1577,7 +1577,7 @@ def _createTemporaryDirectory(): warnMsg = "using '%s' as the temporary directory" % conf.tmpDir logger.warn(warnMsg) - except (OSError, IOError), ex: + except (OSError, IOError) as ex: errMsg = "there has been a problem while accessing " errMsg += "temporary directory location(s) ('%s')" % getSafeExString(ex) raise SqlmapSystemException, errMsg @@ -1585,7 +1585,7 @@ def _createTemporaryDirectory(): try: if not os.path.isdir(tempfile.gettempdir()): os.makedirs(tempfile.gettempdir()) - except (OSError, IOError, WindowsError), ex: + except (OSError, IOError, WindowsError) as ex: warnMsg = "there has been a problem while accessing " warnMsg += "system's temporary directory location(s) ('%s'). Please " % getSafeExString(ex) warnMsg += "make sure that there is enough disk space left. If problem persists, " @@ -1604,7 +1604,7 @@ def _createTemporaryDirectory(): if not os.path.isdir(tempfile.tempdir): try: os.makedirs(tempfile.tempdir) - except (OSError, IOError, WindowsError), ex: + except (OSError, IOError, WindowsError) as ex: errMsg = "there has been a problem while setting " errMsg += "temporary directory location ('%s')" % getSafeExString(ex) raise SqlmapSystemException, errMsg @@ -2275,7 +2275,7 @@ def _setDNSServer(): try: conf.dnsServer = DNSServer() conf.dnsServer.run() - except socket.error, msg: + except socket.error as msg: errMsg = "there was an error while setting up " errMsg += "DNS server instance ('%s')" % msg raise SqlmapGenericException(errMsg) @@ -2462,14 +2462,14 @@ def _basicOptionValidation(): if conf.regexp: try: re.compile(conf.regexp) - except Exception, ex: + except Exception as ex: errMsg = "invalid regular expression '%s' ('%s')" % (conf.regexp, getSafeExString(ex)) raise SqlmapSyntaxException(errMsg) if conf.crawlExclude: try: re.compile(conf.crawlExclude) - except Exception, ex: + except Exception as ex: errMsg = "invalid regular expression '%s' ('%s')" % (conf.crawlExclude, getSafeExString(ex)) raise SqlmapSyntaxException(errMsg) diff --git a/lib/core/profiling.py b/lib/core/profiling.py index c8ede5a2d..7a0329615 100644 --- a/lib/core/profiling.py +++ b/lib/core/profiling.py @@ -25,7 +25,7 @@ def profile(profileOutputFile=None, dotOutputFile=None, imageOutputFile=None): import gobject import gtk import pydot - except ImportError, e: + except ImportError as e: errMsg = "profiling requires third-party libraries ('%s') " % getUnicode(e, UNICODE_ENCODING) errMsg += "(Hint: 'sudo apt-get install python-pydot python-pyparsing python-profiler graphviz')" logger.error(errMsg) diff --git a/lib/core/replication.py b/lib/core/replication.py index 764f7664e..bc4b6eff1 100644 --- a/lib/core/replication.py +++ b/lib/core/replication.py @@ -27,7 +27,7 @@ class Replication(object): self.connection = sqlite3.connect(dbpath) self.connection.isolation_level = None self.cursor = self.connection.cursor() - except sqlite3.OperationalError, ex: + except sqlite3.OperationalError as ex: errMsg = "error occurred while opening a replication " errMsg += "file '%s' ('%s')" % (self.filepath, getSafeExString(ex)) raise SqlmapConnectionException(errMsg) @@ -63,7 +63,7 @@ class Replication(object): self.execute('CREATE TABLE "%s" (%s)' % (self.name, ','.join('"%s" %s' % (unsafeSQLIdentificatorNaming(colname), coltype) for colname, coltype in self.columns))) else: self.execute('CREATE TABLE "%s" (%s)' % (self.name, ','.join('"%s"' % unsafeSQLIdentificatorNaming(colname) for colname in self.columns))) - except Exception, ex: + except Exception as ex: errMsg = "problem occurred ('%s') while initializing the sqlite database " % getSafeExString(ex, UNICODE_ENCODING) errMsg += "located at '%s'" % self.parent.dbpath raise SqlmapGenericException(errMsg) @@ -82,7 +82,7 @@ class Replication(object): def execute(self, sql, parameters=[]): try: self.parent.cursor.execute(sql, parameters) - except sqlite3.OperationalError, ex: + except sqlite3.OperationalError as ex: errMsg = "problem occurred ('%s') while accessing sqlite database " % getSafeExString(ex, UNICODE_ENCODING) errMsg += "located at '%s'. Please make sure that " % self.parent.dbpath errMsg += "it's not used by some other program" diff --git a/lib/core/shell.py b/lib/core/shell.py index b6c200755..28a111737 100644 --- a/lib/core/shell.py +++ b/lib/core/shell.py @@ -72,7 +72,7 @@ def saveHistory(completion=None): readline.set_history_length(MAX_HISTORY_LENGTH) try: readline.write_history_file(historyPath) - except IOError, msg: + except IOError as msg: warnMsg = "there was a problem writing the history file '%s' (%s)" % (historyPath, msg) logger.warn(warnMsg) @@ -92,7 +92,7 @@ def loadHistory(completion=None): if os.path.exists(historyPath): try: readline.read_history_file(historyPath) - except IOError, msg: + except IOError as msg: warnMsg = "there was a problem loading the history file '%s' (%s)" % (historyPath, msg) logger.warn(warnMsg) diff --git a/lib/core/subprocessng.py b/lib/core/subprocessng.py index e82f172cd..079aca8d9 100644 --- a/lib/core/subprocessng.py +++ b/lib/core/subprocessng.py @@ -37,7 +37,7 @@ def blockingReadFromFD(fd): while True: try: output += os.read(fd, 8192) - except (OSError, IOError), ioe: + except (OSError, IOError) as ioe: if ioe.args[0] in (errno.EAGAIN, errno.EINTR): # Uncomment the following line if the process seems to # take a huge amount of cpu time @@ -58,7 +58,7 @@ def blockingWriteToFD(fd, data): try: data_length = len(data) wrote_data = os.write(fd, data) - except (OSError, IOError), io: + except (OSError, IOError) as io: if io.errno in (errno.EAGAIN, errno.EINTR): continue else: @@ -101,7 +101,7 @@ class Popen(subprocess.Popen): (errCode, written) = WriteFile(x, input) except ValueError: return self._close('stdin') - except (subprocess.pywintypes.error, Exception), why: + except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise @@ -122,7 +122,7 @@ class Popen(subprocess.Popen): (errCode, read) = ReadFile(x, nAvail, None) except (ValueError, NameError): return self._close(which) - except (subprocess.pywintypes.error, Exception), why: + except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close(which) raise @@ -140,7 +140,7 @@ class Popen(subprocess.Popen): try: written = os.write(self.stdin.fileno(), input) - except OSError, why: + except OSError as why: if why[0] == errno.EPIPE: # broken pipe return self._close('stdin') raise diff --git a/lib/core/target.py b/lib/core/target.py index 146f3de47..370f1b19f 100644 --- a/lib/core/target.py +++ b/lib/core/target.py @@ -422,7 +422,7 @@ def _setHashDB(): try: os.remove(conf.hashDBFile) logger.info("flushing session file") - except OSError, msg: + except OSError as msg: errMsg = "unable to flush the session file (%s)" % msg raise SqlmapFilePathException(errMsg) @@ -550,7 +550,7 @@ def _setResultsFile(): conf.resultsFilename = os.path.join(paths.SQLMAP_OUTPUT_PATH, time.strftime(RESULTS_FILE_FORMAT).lower()) try: conf.resultsFP = openFile(conf.resultsFilename, "a", UNICODE_ENCODING, buffering=0) - except (OSError, IOError), ex: + except (OSError, IOError) as ex: try: warnMsg = "unable to create results file '%s' ('%s'). " % (conf.resultsFilename, getUnicode(ex)) handle, conf.resultsFilename = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.RESULTS, suffix=".csv") @@ -558,7 +558,7 @@ def _setResultsFile(): conf.resultsFP = openFile(conf.resultsFilename, "w+", UNICODE_ENCODING, buffering=0) warnMsg += "Using temporary file '%s' instead" % conf.resultsFilename logger.warn(warnMsg) - except IOError, _: + except IOError as _: errMsg = "unable to write to the temporary directory ('%s'). " % _ errMsg += "Please make sure that your disk is not full and " errMsg += "that you have sufficient write permissions to " @@ -582,7 +582,7 @@ def _createFilesDir(): if not os.path.isdir(conf.filePath): try: os.makedirs(conf.filePath, 0755) - except OSError, ex: + except OSError as ex: tempDir = tempfile.mkdtemp(prefix="sqlmapfiles") warnMsg = "unable to create files directory " warnMsg += "'%s' (%s). " % (conf.filePath, getUnicode(ex)) @@ -604,7 +604,7 @@ def _createDumpDir(): if not os.path.isdir(conf.dumpPath): try: os.makedirs(conf.dumpPath, 0755) - except OSError, ex: + except OSError as ex: tempDir = tempfile.mkdtemp(prefix="sqlmapdump") warnMsg = "unable to create dump directory " warnMsg += "'%s' (%s). " % (conf.dumpPath, getUnicode(ex)) @@ -633,10 +633,10 @@ def _createTargetDirs(): if conf.outputDir: warnMsg = "using '%s' as the output directory" % paths.SQLMAP_OUTPUT_PATH logger.warn(warnMsg) - except (OSError, IOError), ex: + except (OSError, IOError) as ex: try: tempDir = tempfile.mkdtemp(prefix="sqlmapoutput") - except Exception, _: + except Exception as _: errMsg = "unable to write to the temporary directory ('%s'). " % _ errMsg += "Please make sure that your disk is not full and " errMsg += "that you have sufficient write permissions to " @@ -655,10 +655,10 @@ def _createTargetDirs(): try: if not os.path.isdir(conf.outputPath): os.makedirs(conf.outputPath, 0755) - except (OSError, IOError, TypeError), ex: + except (OSError, IOError, TypeError) as ex: try: tempDir = tempfile.mkdtemp(prefix="sqlmapoutput") - except Exception, _: + except Exception as _: errMsg = "unable to write to the temporary directory ('%s'). " % _ errMsg += "Please make sure that your disk is not full and " errMsg += "that you have sufficient write permissions to " @@ -679,7 +679,7 @@ def _createTargetDirs(): f.write(" # %s" % getUnicode(subprocess.list2cmdline(sys.argv), encoding=sys.stdin.encoding)) if conf.data: f.write("\n\n%s" % getUnicode(conf.data)) - except IOError, ex: + except IOError as ex: if "denied" in getUnicode(ex): errMsg = "you don't have enough permissions " else: diff --git a/lib/core/testing.py b/lib/core/testing.py index ec53aa1de..c7024832c 100644 --- a/lib/core/testing.py +++ b/lib/core/testing.py @@ -71,7 +71,7 @@ def smokeTest(): try: __import__(path) module = sys.modules[path] - except Exception, msg: + except Exception as msg: retVal = False dataToStdout("\r") errMsg = "smoke test failed at importing module '%s' (%s):\n%s" % (path, os.path.join(root, filename), msg) @@ -271,9 +271,9 @@ def runCase(parse): result = start() except KeyboardInterrupt: pass - except SqlmapBaseException, e: + except SqlmapBaseException as e: handled_exception = e - except Exception, e: + except Exception as e: unhandled_exception = e finally: sys.stdout.seek(0) diff --git a/lib/core/threads.py b/lib/core/threads.py index 97184fcdf..e1c4bb097 100644 --- a/lib/core/threads.py +++ b/lib/core/threads.py @@ -92,7 +92,7 @@ def exceptionHandledFunction(threadFunction, silent=False): kb.threadContinue = False kb.threadException = True raise - except Exception, ex: + except Exception as ex: if not silent: logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message)) @@ -151,7 +151,7 @@ def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardExceptio try: thread.start() - except Exception, ex: + except Exception as ex: errMsg = "error occurred while starting new thread ('%s')" % ex.message logger.critical(errMsg) break @@ -167,7 +167,7 @@ def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardExceptio alive = True time.sleep(0.1) - except (KeyboardInterrupt, SqlmapUserQuitException), ex: + except (KeyboardInterrupt, SqlmapUserQuitException) as ex: print() kb.threadContinue = False kb.threadException = True @@ -184,7 +184,7 @@ def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardExceptio if forwardException: raise - except (SqlmapConnectionException, SqlmapValueException), ex: + except (SqlmapConnectionException, SqlmapValueException) as ex: print() kb.threadException = True logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message)) diff --git a/lib/core/update.py b/lib/core/update.py index a41159400..210f747af 100644 --- a/lib/core/update.py +++ b/lib/core/update.py @@ -47,7 +47,7 @@ def update(): pollProcess(process, True) stdout, stderr = process.communicate() success = not process.returncode - except (IOError, OSError), ex: + except (IOError, OSError) as ex: success = False stderr = getSafeExString(ex) diff --git a/lib/core/wordlist.py b/lib/core/wordlist.py index 90d26d483..2f2d81b69 100644 --- a/lib/core/wordlist.py +++ b/lib/core/wordlist.py @@ -43,7 +43,7 @@ class Wordlist(object): if os.path.splitext(self.current)[1].lower() == ".zip": try: _ = zipfile.ZipFile(self.current, 'r') - except zipfile.error, ex: + except zipfile.error as ex: errMsg = "something appears to be wrong with " errMsg += "the file '%s' ('%s'). Please make " % (self.current, getSafeExString(ex)) errMsg += "sure that you haven't made any changes to it" @@ -69,7 +69,7 @@ class Wordlist(object): self.counter += 1 try: retVal = self.iter.next().rstrip() - except zipfile.error, ex: + except zipfile.error as ex: errMsg = "something appears to be wrong with " errMsg += "the file '%s' ('%s'). Please make " % (self.current, getSafeExString(ex)) errMsg += "sure that you haven't made any changes to it" diff --git a/lib/parse/cmdline.py b/lib/parse/cmdline.py index 644c4cfa2..ec8465f6b 100644 --- a/lib/parse/cmdline.py +++ b/lib/parse/cmdline.py @@ -909,7 +909,7 @@ def cmdLineParser(argv=None): try: for arg in shlex.split(command): argv.append(getUnicode(arg, encoding=sys.stdin.encoding)) - except ValueError, ex: + except ValueError as ex: raise SqlmapSyntaxException, "something went wrong during command line parsing ('%s')" % ex.message for i in xrange(len(argv)): @@ -955,7 +955,7 @@ def cmdLineParser(argv=None): try: (args, _) = parser.parse_args(argv) - except UnicodeEncodeError, ex: + except UnicodeEncodeError as ex: dataToStdout("\n[!] %s\n" % ex.object.encode("unicode-escape")) raise SystemExit except SystemExit: @@ -986,7 +986,7 @@ def cmdLineParser(argv=None): return args - except (OptionError, TypeError), e: + except (OptionError, TypeError) as e: parser.error(e) except SystemExit: diff --git a/lib/parse/configfile.py b/lib/parse/configfile.py index d8ae541d6..8290611fa 100644 --- a/lib/parse/configfile.py +++ b/lib/parse/configfile.py @@ -39,7 +39,7 @@ def configFileProxy(section, option, datatype): value = config.getfloat(section, option) if config.get(section, option) else 0.0 else: value = config.get(section, option) - except ValueError, ex: + except ValueError as ex: errMsg = "error occurred while processing the option " errMsg += "'%s' in provided configuration file ('%s')" % (option, getUnicode(ex)) raise SqlmapSyntaxException(errMsg) @@ -71,7 +71,7 @@ def configFileParser(configFile): try: config = UnicodeRawConfigParser() config.readfp(configFP) - except Exception, ex: + except Exception as ex: errMsg = "you have provided an invalid and/or unreadable configuration file ('%s')" % getSafeExString(ex) raise SqlmapSyntaxException(errMsg) diff --git a/lib/parse/payloads.py b/lib/parse/payloads.py index 9f8d5a41b..89d280532 100644 --- a/lib/parse/payloads.py +++ b/lib/parse/payloads.py @@ -74,7 +74,7 @@ def parseXmlNode(node): def loadBoundaries(): try: doc = et.parse(paths.BOUNDARIES_XML) - except Exception, ex: + except Exception as ex: errMsg = "something appears to be wrong with " errMsg += "the file '%s' ('%s'). Please make " % (paths.BOUNDARIES_XML, getSafeExString(ex)) errMsg += "sure that you haven't made any changes to it" @@ -89,7 +89,7 @@ def loadPayloads(): try: doc = et.parse(payloadFilePath) - except Exception, ex: + except Exception as ex: errMsg = "something appears to be wrong with " errMsg += "the file '%s' ('%s'). Please make " % (payloadFilePath, getSafeExString(ex)) errMsg += "sure that you haven't made any changes to it" diff --git a/lib/request/basic.py b/lib/request/basic.py index d0d6d0bbb..4326acead 100644 --- a/lib/request/basic.py +++ b/lib/request/basic.py @@ -283,7 +283,7 @@ def decodePage(page, contentEncoding, contentType): raise Exception("size too large") page = data.read() - except Exception, msg: + except Exception as msg: if ")", msg) @@ -52,7 +52,7 @@ class Connector(GenericConnector): try: self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password) - except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg: + except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError) as msg: raise SqlmapConnectionException(msg) self.initCursor() @@ -61,7 +61,7 @@ class Connector(GenericConnector): def fetchall(self): try: return self.cursor.fetchall() - except cx_Oracle.InterfaceError, msg: + except cx_Oracle.InterfaceError as msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg) return None @@ -71,7 +71,7 @@ class Connector(GenericConnector): try: self.cursor.execute(utf8encode(query)) retVal = True - except cx_Oracle.DatabaseError, msg: + except cx_Oracle.DatabaseError as msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg) self.connector.commit() diff --git a/plugins/dbms/postgresql/connector.py b/plugins/dbms/postgresql/connector.py index e480d17dc..b3df0bd44 100644 --- a/plugins/dbms/postgresql/connector.py +++ b/plugins/dbms/postgresql/connector.py @@ -36,7 +36,7 @@ class Connector(GenericConnector): try: self.connector = psycopg2.connect(host=self.hostname, user=self.user, password=self.password, database=self.db, port=self.port) - except psycopg2.OperationalError, msg: + except psycopg2.OperationalError as msg: raise SqlmapConnectionException(msg) self.connector.set_client_encoding('UNICODE') @@ -47,7 +47,7 @@ class Connector(GenericConnector): def fetchall(self): try: return self.cursor.fetchall() - except psycopg2.ProgrammingError, msg: + except psycopg2.ProgrammingError as msg: logger.warn(msg) return None @@ -57,9 +57,9 @@ class Connector(GenericConnector): try: self.cursor.execute(query) retVal = True - except (psycopg2.OperationalError, psycopg2.ProgrammingError), msg: + except (psycopg2.OperationalError, psycopg2.ProgrammingError) as msg: logger.warn(("(remote) %s" % msg).strip()) - except psycopg2.InternalError, msg: + except psycopg2.InternalError as msg: raise SqlmapConnectionException(msg) self.connector.commit() diff --git a/plugins/dbms/sqlite/connector.py b/plugins/dbms/sqlite/connector.py index ae2722a9a..5ece8c86e 100644 --- a/plugins/dbms/sqlite/connector.py +++ b/plugins/dbms/sqlite/connector.py @@ -46,7 +46,7 @@ class Connector(GenericConnector): cursor.execute("SELECT * FROM sqlite_master") cursor.close() - except (self.__sqlite.DatabaseError, self.__sqlite.OperationalError), msg: + except (self.__sqlite.DatabaseError, self.__sqlite.OperationalError) as msg: warnMsg = "unable to connect using SQLite 3 library, trying with SQLite 2" logger.warn(warnMsg) @@ -60,7 +60,7 @@ class Connector(GenericConnector): self.__sqlite = sqlite self.connector = self.__sqlite.connect(database=self.db, check_same_thread=False, timeout=conf.timeout) - except (self.__sqlite.DatabaseError, self.__sqlite.OperationalError), msg: + except (self.__sqlite.DatabaseError, self.__sqlite.OperationalError) as msg: raise SqlmapConnectionException(msg[0]) self.initCursor() @@ -69,16 +69,16 @@ class Connector(GenericConnector): def fetchall(self): try: return self.cursor.fetchall() - except self.__sqlite.OperationalError, msg: + except self.__sqlite.OperationalError as msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[0]) return None def execute(self, query): try: self.cursor.execute(utf8encode(query)) - except self.__sqlite.OperationalError, msg: + except self.__sqlite.OperationalError as msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[0]) - except self.__sqlite.DatabaseError, msg: + except self.__sqlite.DatabaseError as msg: raise SqlmapConnectionException(msg[0]) self.connector.commit() diff --git a/plugins/dbms/sybase/connector.py b/plugins/dbms/sybase/connector.py index fe1cec52f..29c6f4c91 100644 --- a/plugins/dbms/sybase/connector.py +++ b/plugins/dbms/sybase/connector.py @@ -41,7 +41,7 @@ class Connector(GenericConnector): try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) - except (pymssql.Error, _mssql.MssqlDatabaseException), msg: + except (pymssql.Error, _mssql.MssqlDatabaseException) as msg: raise SqlmapConnectionException(msg) self.initCursor() @@ -50,7 +50,7 @@ class Connector(GenericConnector): def fetchall(self): try: return self.cursor.fetchall() - except (pymssql.Error, _mssql.MssqlDatabaseException), msg: + except (pymssql.Error, _mssql.MssqlDatabaseException) as msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) return None @@ -60,9 +60,9 @@ class Connector(GenericConnector): try: self.cursor.execute(utf8encode(query)) retVal = True - except (pymssql.OperationalError, pymssql.ProgrammingError), msg: + except (pymssql.OperationalError, pymssql.ProgrammingError) as msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) - except pymssql.InternalError, msg: + except pymssql.InternalError as msg: raise SqlmapConnectionException(msg) return retVal diff --git a/plugins/generic/connector.py b/plugins/generic/connector.py index 3676f5707..c7be7e358 100644 --- a/plugins/generic/connector.py +++ b/plugins/generic/connector.py @@ -50,7 +50,7 @@ class Connector: self.cursor.close() if self.connector: self.connector.close() - except Exception, msg: + except Exception as msg: logger.debug(msg) finally: self.closed() diff --git a/plugins/generic/custom.py b/plugins/generic/custom.py index e56576dea..d1694a026 100644 --- a/plugins/generic/custom.py +++ b/plugins/generic/custom.py @@ -71,7 +71,7 @@ class Custom: output = NULL - except SqlmapNoneDataException, ex: + except SqlmapNoneDataException as ex: logger.warn(ex) return output diff --git a/plugins/generic/entries.py b/plugins/generic/entries.py index 0fab15af1..2febe95c0 100644 --- a/plugins/generic/entries.py +++ b/plugins/generic/entries.py @@ -435,13 +435,13 @@ class Entries: "db": safeSQLIdentificatorNaming(conf.db)} try: attackDumpedTable() - except (IOError, OSError), ex: + except (IOError, OSError) as ex: errMsg = "an error occurred while attacking " errMsg += "table dump ('%s')" % getSafeExString(ex) logger.critical(errMsg) conf.dumper.dbTableValues(kb.data.dumpedTable) - except SqlmapConnectionException, ex: + except SqlmapConnectionException as ex: errMsg = "connection exception detected in dumping phase " errMsg += "('%s')" % getSafeExString(ex) logger.critical(errMsg)