Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sqlmapproject
GitHub Repository: sqlmapproject/sqlmap
Path: blob/master/sqlmap.py
3554 views
1
#!/usr/bin/env python
2
3
"""
4
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
5
See the file 'LICENSE' for copying permission
6
"""
7
8
from __future__ import print_function
9
10
try:
11
import sys
12
13
sys.dont_write_bytecode = True
14
15
try:
16
__import__("lib.utils.versioncheck") # this has to be the first non-standard import
17
except ImportError:
18
sys.exit("[!] wrong installation detected (missing modules). Visit 'https://github.com/sqlmapproject/sqlmap/#installation' for further details")
19
20
import bdb
21
import glob
22
import inspect
23
import json
24
import logging
25
import os
26
import re
27
import shutil
28
import sys
29
import tempfile
30
import threading
31
import time
32
import traceback
33
import warnings
34
35
if "--deprecations" not in sys.argv:
36
warnings.filterwarnings(action="ignore", category=DeprecationWarning)
37
else:
38
warnings.resetwarnings()
39
warnings.filterwarnings(action="ignore", message="'crypt'", category=DeprecationWarning)
40
warnings.simplefilter("ignore", category=ImportWarning)
41
if sys.version_info >= (3, 0):
42
warnings.simplefilter("ignore", category=ResourceWarning)
43
44
warnings.filterwarnings(action="ignore", message="Python 2 is no longer supported")
45
warnings.filterwarnings(action="ignore", message=".*was already imported", category=UserWarning)
46
warnings.filterwarnings(action="ignore", message=".*using a very old release", category=UserWarning)
47
warnings.filterwarnings(action="ignore", message=".*default buffer size will be used", category=RuntimeWarning)
48
warnings.filterwarnings(action="ignore", category=UserWarning, module="psycopg2")
49
50
from lib.core.data import logger
51
52
from lib.core.common import banner
53
from lib.core.common import checkPipedInput
54
from lib.core.common import checkSums
55
from lib.core.common import createGithubIssue
56
from lib.core.common import dataToStdout
57
from lib.core.common import extractRegexResult
58
from lib.core.common import filterNone
59
from lib.core.common import getDaysFromLastUpdate
60
from lib.core.common import getFileItems
61
from lib.core.common import getSafeExString
62
from lib.core.common import maskSensitiveData
63
from lib.core.common import openFile
64
from lib.core.common import setPaths
65
from lib.core.common import weAreFrozen
66
from lib.core.convert import getUnicode
67
from lib.core.common import setColor
68
from lib.core.common import unhandledExceptionMessage
69
from lib.core.compat import LooseVersion
70
from lib.core.compat import xrange
71
from lib.core.data import cmdLineOptions
72
from lib.core.data import conf
73
from lib.core.data import kb
74
from lib.core.datatype import OrderedSet
75
from lib.core.enums import MKSTEMP_PREFIX
76
from lib.core.exception import SqlmapBaseException
77
from lib.core.exception import SqlmapShellQuitException
78
from lib.core.exception import SqlmapSilentQuitException
79
from lib.core.exception import SqlmapUserQuitException
80
from lib.core.option import init
81
from lib.core.option import initOptions
82
from lib.core.patch import dirtyPatches
83
from lib.core.patch import resolveCrossReferences
84
from lib.core.settings import GIT_PAGE
85
from lib.core.settings import IS_WIN
86
from lib.core.settings import LAST_UPDATE_NAGGING_DAYS
87
from lib.core.settings import LEGAL_DISCLAIMER
88
from lib.core.settings import THREAD_FINALIZATION_TIMEOUT
89
from lib.core.settings import UNICODE_ENCODING
90
from lib.core.settings import VERSION
91
from lib.parse.cmdline import cmdLineParser
92
from lib.utils.crawler import crawl
93
except KeyboardInterrupt:
94
errMsg = "user aborted"
95
96
if "logger" in globals():
97
logger.critical(errMsg)
98
raise SystemExit
99
else:
100
import time
101
sys.exit("\r[%s] [CRITICAL] %s" % (time.strftime("%X"), errMsg))
102
103
def modulePath():
104
"""
105
This will get us the program's directory, even if we are frozen
106
using py2exe
107
"""
108
109
try:
110
_ = sys.executable if weAreFrozen() else __file__
111
except NameError:
112
_ = inspect.getsourcefile(modulePath)
113
114
return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystemencoding() or UNICODE_ENCODING)
115
116
def checkEnvironment():
117
try:
118
os.path.isdir(modulePath())
119
except UnicodeEncodeError:
120
errMsg = "your system does not properly handle non-ASCII paths. "
121
errMsg += "Please move the sqlmap's directory to the other location"
122
logger.critical(errMsg)
123
raise SystemExit
124
125
if LooseVersion(VERSION) < LooseVersion("1.0"):
126
errMsg = "your runtime environment (e.g. PYTHONPATH) is "
127
errMsg += "broken. Please make sure that you are not running "
128
errMsg += "newer versions of sqlmap with runtime scripts for older "
129
errMsg += "versions"
130
logger.critical(errMsg)
131
raise SystemExit
132
133
# Patch for pip (import) environment
134
if "sqlmap.sqlmap" in sys.modules:
135
for _ in ("cmdLineOptions", "conf", "kb"):
136
globals()[_] = getattr(sys.modules["lib.core.data"], _)
137
138
for _ in ("SqlmapBaseException", "SqlmapShellQuitException", "SqlmapSilentQuitException", "SqlmapUserQuitException"):
139
globals()[_] = getattr(sys.modules["lib.core.exception"], _)
140
141
def main():
142
"""
143
Main function of sqlmap when running from command line.
144
"""
145
146
try:
147
dirtyPatches()
148
resolveCrossReferences()
149
checkEnvironment()
150
setPaths(modulePath())
151
banner()
152
153
# Store original command line options for possible later restoration
154
args = cmdLineParser()
155
cmdLineOptions.update(args.__dict__ if hasattr(args, "__dict__") else args)
156
initOptions(cmdLineOptions)
157
158
if checkPipedInput():
159
conf.batch = True
160
161
if conf.get("api"):
162
# heavy imports
163
from lib.utils.api import StdDbOut
164
from lib.utils.api import setRestAPILog
165
166
# Overwrite system standard output and standard error to write
167
# to an IPC database
168
sys.stdout = StdDbOut(conf.taskid, messagetype="stdout")
169
sys.stderr = StdDbOut(conf.taskid, messagetype="stderr")
170
171
setRestAPILog()
172
173
conf.showTime = True
174
dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER, forceOutput=True)
175
dataToStdout("[*] starting @ %s\n\n" % time.strftime("%X /%Y-%m-%d/"), forceOutput=True)
176
177
init()
178
179
if not conf.updateAll:
180
# Postponed imports (faster start)
181
if conf.smokeTest:
182
from lib.core.testing import smokeTest
183
os._exitcode = 1 - (smokeTest() or 0)
184
elif conf.vulnTest:
185
from lib.core.testing import vulnTest
186
os._exitcode = 1 - (vulnTest() or 0)
187
else:
188
from lib.controller.controller import start
189
if conf.profile:
190
from lib.core.profiling import profile
191
globals()["start"] = start
192
profile()
193
else:
194
try:
195
if conf.crawlDepth and conf.bulkFile:
196
targets = getFileItems(conf.bulkFile)
197
198
for i in xrange(len(targets)):
199
target = None
200
201
try:
202
kb.targets = OrderedSet()
203
target = targets[i]
204
205
if not re.search(r"(?i)\Ahttp[s]*://", target):
206
target = "https://%s" % target
207
208
infoMsg = "starting crawler for target URL '%s' (%d/%d)" % (target, i + 1, len(targets))
209
logger.info(infoMsg)
210
211
crawl(target)
212
except Exception as ex:
213
if target and not isinstance(ex, SqlmapUserQuitException):
214
errMsg = "problem occurred while crawling '%s' ('%s')" % (target, getSafeExString(ex))
215
logger.error(errMsg)
216
else:
217
raise
218
else:
219
if kb.targets:
220
start()
221
else:
222
start()
223
except Exception as ex:
224
os._exitcode = 1
225
226
if "can't start new thread" in getSafeExString(ex):
227
errMsg = "unable to start new threads. Please check OS (u)limits"
228
logger.critical(errMsg)
229
raise SystemExit
230
else:
231
raise
232
233
except SqlmapUserQuitException:
234
if not conf.batch:
235
errMsg = "user quit"
236
logger.error(errMsg)
237
238
except (SqlmapSilentQuitException, bdb.BdbQuit):
239
pass
240
241
except SqlmapShellQuitException:
242
cmdLineOptions.sqlmapShell = False
243
244
except SqlmapBaseException as ex:
245
errMsg = getSafeExString(ex)
246
logger.critical(errMsg)
247
248
os._exitcode = 1
249
250
raise SystemExit
251
252
except KeyboardInterrupt:
253
try:
254
print()
255
except IOError:
256
pass
257
258
except EOFError:
259
print()
260
261
errMsg = "exit"
262
logger.error(errMsg)
263
264
except SystemExit as ex:
265
os._exitcode = ex.code or 0
266
267
except:
268
print()
269
errMsg = unhandledExceptionMessage()
270
excMsg = traceback.format_exc()
271
valid = checkSums()
272
273
os._exitcode = 255
274
275
if any(_ in excMsg for _ in ("MemoryError", "Cannot allocate memory")):
276
errMsg = "memory exhaustion detected"
277
logger.critical(errMsg)
278
raise SystemExit
279
280
elif any(_ in excMsg for _ in ("No space left", "Disk quota exceeded", "Disk full while accessing")):
281
errMsg = "no space left on output device"
282
logger.critical(errMsg)
283
raise SystemExit
284
285
elif any(_ in excMsg for _ in ("The paging file is too small",)):
286
errMsg = "no space left for paging file"
287
logger.critical(errMsg)
288
raise SystemExit
289
290
elif all(_ in excMsg for _ in ("Access is denied", "subprocess", "metasploit")):
291
errMsg = "permission error occurred while running Metasploit"
292
logger.critical(errMsg)
293
raise SystemExit
294
295
elif all(_ in excMsg for _ in ("Permission denied", "metasploit")):
296
errMsg = "permission error occurred while using Metasploit"
297
logger.critical(errMsg)
298
raise SystemExit
299
300
elif "Read-only file system" in excMsg:
301
errMsg = "output device is mounted as read-only"
302
logger.critical(errMsg)
303
raise SystemExit
304
305
elif "Insufficient system resources" in excMsg:
306
errMsg = "resource exhaustion detected"
307
logger.critical(errMsg)
308
raise SystemExit
309
310
elif "OperationalError: disk I/O error" in excMsg:
311
errMsg = "I/O error on output device"
312
logger.critical(errMsg)
313
raise SystemExit
314
315
elif "Violation of BIDI" in excMsg:
316
errMsg = "invalid URL (violation of Bidi IDNA rule - RFC 5893)"
317
logger.critical(errMsg)
318
raise SystemExit
319
320
elif "Invalid IPv6 URL" in excMsg:
321
errMsg = "invalid URL ('%s')" % excMsg.strip().split('\n')[-1]
322
logger.critical(errMsg)
323
raise SystemExit
324
325
elif "_mkstemp_inner" in excMsg:
326
errMsg = "there has been a problem while accessing temporary files"
327
logger.critical(errMsg)
328
raise SystemExit
329
330
elif any(_ in excMsg for _ in ("tempfile.mkdtemp", "tempfile.mkstemp", "tempfile.py")):
331
errMsg = "unable to write to the temporary directory '%s'. " % tempfile.gettempdir()
332
errMsg += "Please make sure that your disk is not full and "
333
errMsg += "that you have sufficient write permissions to "
334
errMsg += "create temporary files and/or directories"
335
logger.critical(errMsg)
336
raise SystemExit
337
338
elif "Permission denied: '" in excMsg:
339
match = re.search(r"Permission denied: '([^']*)", excMsg)
340
errMsg = "permission error occurred while accessing file '%s'" % match.group(1)
341
logger.critical(errMsg)
342
raise SystemExit
343
344
elif all(_ in excMsg for _ in ("twophase", "sqlalchemy")):
345
errMsg = "please update the 'sqlalchemy' package (>= 1.1.11) "
346
errMsg += "(Reference: 'https://qiita.com/tkprof/items/7d7b2d00df9c5f16fffe')"
347
logger.critical(errMsg)
348
raise SystemExit
349
350
elif all(_ in excMsg for _ in ("httpcore", "typing.", "AttributeError")):
351
errMsg = "please update the 'httpcore' package (>= 1.0.8) "
352
errMsg += "(Reference: 'https://github.com/encode/httpcore/discussions/995')"
353
logger.critical(errMsg)
354
raise SystemExit
355
356
elif "invalid maximum character passed to PyUnicode_New" in excMsg and re.search(r"\A3\.[34]", sys.version) is not None:
357
errMsg = "please upgrade the Python version (>= 3.5) "
358
errMsg += "(Reference: 'https://bugs.python.org/issue18183')"
359
logger.critical(errMsg)
360
raise SystemExit
361
362
elif all(_ in excMsg for _ in ("scramble_caching_sha2", "TypeError")):
363
errMsg = "please downgrade the 'PyMySQL' package (=< 0.8.1) "
364
errMsg += "(Reference: 'https://github.com/PyMySQL/PyMySQL/issues/700')"
365
logger.critical(errMsg)
366
raise SystemExit
367
368
elif "must be pinned buffer, not bytearray" in excMsg:
369
errMsg = "error occurred at Python interpreter which "
370
errMsg += "is fixed in 2.7. Please update accordingly "
371
errMsg += "(Reference: 'https://bugs.python.org/issue8104')"
372
logger.critical(errMsg)
373
raise SystemExit
374
375
elif all(_ in excMsg for _ in ("OSError: [Errno 22] Invalid argument: '", "importlib")):
376
errMsg = "unable to read file '%s'" % extractRegexResult(r"OSError: \[Errno 22\] Invalid argument: '(?P<result>[^']+)", excMsg)
377
logger.critical(errMsg)
378
raise SystemExit
379
380
elif "hash_randomization" in excMsg:
381
errMsg = "error occurred at Python interpreter which "
382
errMsg += "is fixed in 2.7.3. Please update accordingly "
383
errMsg += "(Reference: 'https://docs.python.org/2/library/sys.html')"
384
logger.critical(errMsg)
385
raise SystemExit
386
387
elif "AttributeError:" in excMsg and re.search(r"3\.11\.\d+a", sys.version):
388
errMsg = "there is a known issue when sqlmap is run with ALPHA versions of Python 3.11. "
389
errMsg += "Please download a stable Python version"
390
logger.critical(errMsg)
391
raise SystemExit
392
393
elif all(_ in excMsg for _ in ("Resource temporarily unavailable", "os.fork()", "dictionaryAttack")):
394
errMsg = "there has been a problem while running the multiprocessing hash cracking. "
395
errMsg += "Please rerun with option '--threads=1'"
396
logger.critical(errMsg)
397
raise SystemExit
398
399
elif "can't start new thread" in excMsg:
400
errMsg = "there has been a problem while creating new thread instance. "
401
errMsg += "Please make sure that you are not running too many processes"
402
if not IS_WIN:
403
errMsg += " (or increase the 'ulimit -u' value)"
404
logger.critical(errMsg)
405
raise SystemExit
406
407
elif "can't allocate read lock" in excMsg:
408
errMsg = "there has been a problem in regular socket operation "
409
errMsg += "('%s')" % excMsg.strip().split('\n')[-1]
410
logger.critical(errMsg)
411
raise SystemExit
412
413
elif all(_ in excMsg for _ in ("pymysql", "configparser")):
414
errMsg = "wrong initialization of 'pymsql' detected (using Python3 dependencies)"
415
logger.critical(errMsg)
416
raise SystemExit
417
418
elif all(_ in excMsg for _ in ("ntlm", "socket.error, err", "SyntaxError")):
419
errMsg = "wrong initialization of 'python-ntlm' detected (using Python2 syntax)"
420
logger.critical(errMsg)
421
raise SystemExit
422
423
elif all(_ in excMsg for _ in ("drda", "to_bytes")):
424
errMsg = "wrong initialization of 'drda' detected (using Python3 syntax)"
425
logger.critical(errMsg)
426
raise SystemExit
427
428
elif "'WebSocket' object has no attribute 'status'" in excMsg:
429
errMsg = "wrong websocket library detected"
430
errMsg += " (Reference: 'https://github.com/sqlmapproject/sqlmap/issues/4572#issuecomment-775041086')"
431
logger.critical(errMsg)
432
raise SystemExit
433
434
elif all(_ in excMsg for _ in ("window = tkinter.Tk()",)):
435
errMsg = "there has been a problem in initialization of GUI interface "
436
errMsg += "('%s')" % excMsg.strip().split('\n')[-1]
437
logger.critical(errMsg)
438
raise SystemExit
439
440
elif any(_ in excMsg for _ in ("unable to access item 'liveTest'",)):
441
errMsg = "detected usage of files from different versions of sqlmap"
442
logger.critical(errMsg)
443
raise SystemExit
444
445
elif any(_ in errMsg for _ in (": 9.9.9#",)):
446
errMsg = "LOL xD"
447
logger.critical(errMsg)
448
raise SystemExit
449
450
elif kb.get("dumpKeyboardInterrupt"):
451
raise SystemExit
452
453
elif any(_ in excMsg for _ in ("Broken pipe", "KeyboardInterrupt")):
454
raise SystemExit
455
456
elif valid is False:
457
errMsg = "code checksum failed (turning off automatic issue creation). "
458
errMsg += "You should retrieve the latest development version from official GitHub "
459
errMsg += "repository at '%s'" % GIT_PAGE
460
logger.critical(errMsg)
461
print()
462
dataToStdout(excMsg)
463
raise SystemExit
464
465
elif any(_ in "%s\n%s" % (errMsg, excMsg) for _ in ("tamper/", "waf/", "--engagement-dojo")):
466
logger.critical(errMsg)
467
print()
468
dataToStdout(excMsg)
469
raise SystemExit
470
471
elif any(_ in excMsg for _ in ("ImportError", "ModuleNotFoundError", "<frozen", "Can't find file for module", "SAXReaderNotAvailable", "<built-in function compile> returned NULL without setting an exception", "source code string cannot contain null bytes", "No module named", "tp_name field", "module 'sqlite3' has no attribute 'OperationalError'")):
472
errMsg = "invalid runtime environment ('%s')" % excMsg.split("Error: ")[-1].strip()
473
logger.critical(errMsg)
474
raise SystemExit
475
476
elif all(_ in excMsg for _ in ("SyntaxError: Non-ASCII character", ".py on line", "but no encoding declared")):
477
errMsg = "invalid runtime environment ('%s')" % excMsg.split("Error: ")[-1].strip()
478
logger.critical(errMsg)
479
raise SystemExit
480
481
elif all(_ in excMsg for _ in ("FileNotFoundError: [Errno 2] No such file or directory", "cwd = os.getcwd()")):
482
errMsg = "invalid runtime environment ('%s')" % excMsg.split("Error: ")[-1].strip()
483
logger.critical(errMsg)
484
raise SystemExit
485
486
elif all(_ in excMsg for _ in ("PermissionError: [WinError 5]", "multiprocessing")):
487
errMsg = "there is a permission problem in running multiprocessing on this system. "
488
errMsg += "Please rerun with '--disable-multi'"
489
logger.critical(errMsg)
490
raise SystemExit
491
492
elif all(_ in excMsg for _ in ("No such file", "_'")):
493
errMsg = "corrupted installation detected ('%s'). " % excMsg.strip().split('\n')[-1]
494
errMsg += "You should retrieve the latest development version from official GitHub "
495
errMsg += "repository at '%s'" % GIT_PAGE
496
logger.critical(errMsg)
497
raise SystemExit
498
499
elif all(_ in excMsg for _ in ("No such file", "sqlmap.conf", "Test")):
500
errMsg = "you are trying to run (hidden) development tests inside the production environment"
501
logger.critical(errMsg)
502
raise SystemExit
503
504
elif all(_ in excMsg for _ in ("HTTPNtlmAuthHandler", "'str' object has no attribute 'decode'")):
505
errMsg = "package 'python-ntlm' has a known compatibility issue with the "
506
errMsg += "Python 3 (Reference: 'https://github.com/mullender/python-ntlm/pull/61')"
507
logger.critical(errMsg)
508
raise SystemExit
509
510
elif "'DictObject' object has no attribute '" in excMsg and all(_ in errMsg for _ in ("(fingerprinted)", "(identified)")):
511
errMsg = "there has been a problem in enumeration. "
512
errMsg += "Because of a considerable chance of false-positive case "
513
errMsg += "you are advised to rerun with switch '--flush-session'"
514
logger.critical(errMsg)
515
raise SystemExit
516
517
elif "database disk image is malformed" in excMsg:
518
errMsg = "local session file seems to be malformed. Please rerun with '--flush-session'"
519
logger.critical(errMsg)
520
raise SystemExit
521
522
elif "'cryptography' package is required" in excMsg:
523
errMsg = "third-party library 'cryptography' is required"
524
logger.critical(errMsg)
525
raise SystemExit
526
527
elif "AttributeError: 'module' object has no attribute 'F_GETFD'" in excMsg:
528
errMsg = "invalid runtime (\"%s\") " % excMsg.split("Error: ")[-1].strip()
529
errMsg += "(Reference: 'https://stackoverflow.com/a/38841364' & 'https://bugs.python.org/issue24944#msg249231')"
530
logger.critical(errMsg)
531
raise SystemExit
532
533
elif "bad marshal data (unknown type code)" in excMsg:
534
match = re.search(r"\s*(.+)\s+ValueError", excMsg)
535
errMsg = "one of your .pyc files are corrupted%s" % (" ('%s')" % match.group(1) if match else "")
536
errMsg += ". Please delete .pyc files on your system to fix the problem"
537
logger.critical(errMsg)
538
raise SystemExit
539
540
for match in re.finditer(r'File "(.+?)", line', excMsg):
541
file_ = match.group(1)
542
try:
543
file_ = os.path.relpath(file_, os.path.dirname(__file__))
544
except ValueError:
545
pass
546
file_ = file_.replace("\\", '/')
547
if "../" in file_:
548
file_ = re.sub(r"(\.\./)+", '/', file_)
549
else:
550
file_ = file_.lstrip('/')
551
file_ = re.sub(r"/{2,}", '/', file_)
552
excMsg = excMsg.replace(match.group(1), file_)
553
554
errMsg = maskSensitiveData(errMsg)
555
excMsg = maskSensitiveData(excMsg)
556
557
if conf.get("api") or not valid or kb.get("lastCtrlCTime"):
558
logger.critical("%s\n%s" % (errMsg, excMsg))
559
else:
560
logger.critical(errMsg)
561
dataToStdout("%s\n" % setColor(excMsg.strip(), level=logging.CRITICAL))
562
createGithubIssue(errMsg, excMsg)
563
564
finally:
565
kb.threadContinue = False
566
567
if (getDaysFromLastUpdate() or 0) > LAST_UPDATE_NAGGING_DAYS:
568
warnMsg = "your sqlmap version is outdated"
569
logger.warning(warnMsg)
570
571
if conf.get("showTime"):
572
dataToStdout("\n[*] ending @ %s\n\n" % time.strftime("%X /%Y-%m-%d/"), forceOutput=True)
573
574
kb.threadException = True
575
576
for tempDir in conf.get("tempDirs", []):
577
for prefix in (MKSTEMP_PREFIX.IPC, MKSTEMP_PREFIX.TESTING, MKSTEMP_PREFIX.COOKIE_JAR, MKSTEMP_PREFIX.BIG_ARRAY):
578
for filepath in glob.glob(os.path.join(tempDir, "%s*" % prefix)):
579
try:
580
os.remove(filepath)
581
except OSError:
582
pass
583
584
if any((conf.vulnTest, conf.smokeTest)) or not filterNone(filepath for filepath in glob.glob(os.path.join(tempDir, '*')) if not any(filepath.endswith(_) for _ in (".lock", ".exe", ".so", '_'))): # ignore junk files
585
try:
586
shutil.rmtree(tempDir, ignore_errors=True)
587
except OSError:
588
pass
589
590
if conf.get("hashDB"):
591
conf.hashDB.flush()
592
conf.hashDB.close() # NOTE: because of PyPy
593
594
if conf.get("harFile"):
595
try:
596
with openFile(conf.harFile, "w+") as f:
597
json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))
598
except SqlmapBaseException as ex:
599
errMsg = getSafeExString(ex)
600
logger.critical(errMsg)
601
602
if conf.get("api"):
603
conf.databaseCursor.disconnect()
604
605
if conf.get("dumper"):
606
conf.dumper.flush()
607
608
# short delay for thread finalization
609
_ = time.time()
610
while threading.active_count() > 1 and (time.time() - _) < THREAD_FINALIZATION_TIMEOUT:
611
time.sleep(0.01)
612
613
if cmdLineOptions.get("sqlmapShell"):
614
cmdLineOptions.clear()
615
conf.clear()
616
kb.clear()
617
conf.disableBanner = True
618
main()
619
620
if __name__ == "__main__":
621
try:
622
main()
623
except KeyboardInterrupt:
624
pass
625
except SystemExit:
626
raise
627
except:
628
traceback.print_exc()
629
finally:
630
# Reference: http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program
631
if threading.active_count() > 1:
632
os._exit(getattr(os, "_exitcode", 0))
633
else:
634
sys.exit(getattr(os, "_exitcode", 0))
635
else:
636
# cancelling postponed imports (because of CI/CD checks)
637
__import__("lib.controller.controller")
638
639