源码阅读

yangzhisheng_branch
XU 2 months ago
parent d59959cff9
commit 60938dff4c

@ -5,111 +5,111 @@ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
from __future__ import print_function
from __future__ import print_function # 导入print_function特性确保在Python 2和3中print函数的行为一致
try:
import sys
import sys # 导入sys模块用于处理与Python解释器相关的操作
# 防止Python自动生成.pyc文件
sys.dont_write_bytecode = True
sys.dont_write_bytecode = True # 设置不生成.pyc字节码文件以减少磁盘空间占用和加载时间
try:
# 检查sqlmap的安装是否正确
__import__("lib.utils.versioncheck") # this has to be the first non-standard import
except ImportError:
sys.exit("[!] wrong installation detected (missing modules). Visit 'https://github.com/sqlmapproject/sqlmap/#installation' for further details")
__import__("lib.utils.versioncheck") # 动态导入lib.utils.versioncheck模块通常用于检查版本兼容性
except ImportError: # 如果导入失败(例如模块不存在),则执行以下代码
sys.exit("[!] wrong installation detected (missing modules). Visit 'https://github.com/sqlmapproject/sqlmap/#installation' for further details") # 退出程序并提示安装错误,建议用户访问指定链接查看安装说明
# 导入标准库模块
import bdb
import glob
import inspect
import json
import logging
import os
import re
import shutil
import sys
import tempfile
import threading
import time
import traceback
import warnings
import bdb # 导入bdb模块用于调试器支持
import glob # 导入glob模块用于文件路径匹配
import inspect # 导入inspect模块用于获取对象信息
import json # 导入json模块用于处理JSON数据
import logging # 导入logging模块用于记录日志信息
import os # 导入os模块用于与操作系统进行交互
import re # 导入re模块用于正则表达式操作
import shutil # 导入shutil模块用于文件操作如复制、删除等
import sys # 再次导入sys模块确保其可用性
import tempfile # 导入tempfile模块用于创建临时文件和目录
import threading # 导入threading模块用于多线程支持
import time # 导入time模块用于时间相关操作
import traceback # 导入traceback模块用于获取异常信息
import warnings # 导入warnings模块用于处理警告信息
# 忽略DeprecationWarning除非命令行参数中包含"--deprecations"
if "--deprecations" not in sys.argv:
warnings.filterwarnings(action="ignore", category=DeprecationWarning)
else:
warnings.resetwarnings()
warnings.filterwarnings(action="ignore", message="'crypt'", category=DeprecationWarning)
warnings.simplefilter("ignore", category=ImportWarning)
if sys.version_info >= (3, 0):
warnings.simplefilter("ignore", category=ResourceWarning)
if "--deprecations" not in sys.argv: # 如果命令行参数中不包含"--deprecations"
warnings.filterwarnings(action="ignore", category=DeprecationWarning) # 忽略所有DeprecationWarning类别的警告
else: # 如果命令行参数中包含"--deprecations"
warnings.resetwarnings() # 重置警告过滤器
warnings.filterwarnings(action="ignore", message="'crypt'", category=DeprecationWarning) # 忽略特定消息的DeprecationWarning
warnings.simplefilter("ignore", category=ImportWarning) # 忽略所有ImportWarning类别的警告
if sys.version_info >= (3, 0): # 如果Python版本大于等于3.0
warnings.simplefilter("ignore", category=ResourceWarning) # 忽略所有ResourceWarning类别的警告
# 忽略特定警告
warnings.filterwarnings(action="ignore", message="Python 2 is no longer supported")
warnings.filterwarnings(action="ignore", message=".*was already imported", category=UserWarning)
warnings.filterwarnings(action="ignore", message=".*using a very old release", category=UserWarning)
warnings.filterwarnings(action="ignore", message=".*default buffer size will be used", category=RuntimeWarning)
warnings.filterwarnings(action="ignore", category=UserWarning, module="psycopg2")
warnings.filterwarnings(action="ignore", message="Python 2 is no longer supported") # 忽略关于Python 2不再支持的警告
warnings.filterwarnings(action="ignore", message=".*was already imported", category=UserWarning) # 忽略关于模块已导入的UserWarning
warnings.filterwarnings(action="ignore", message=".*using a very old release", category=UserWarning) # 忽略关于使用旧版本的UserWarning
warnings.filterwarnings(action="ignore", message=".*default buffer size will be used", category=RuntimeWarning) # 忽略关于默认缓冲区大小的RuntimeWarning
warnings.filterwarnings(action="ignore", category=UserWarning, module="psycopg2") # 忽略psycopg2模块的UserWarning
# 导入sqlmap的核心日志模块
from lib.core.data import logger
from lib.core.data import logger # 从lib.core.data模块导入logger对象用于记录日志信息
# 导入sqlmap的核心功能模块
from lib.core.common import banner
from lib.core.common import checkPipedInput
from lib.core.common import checkSums
from lib.core.common import createGithubIssue
from lib.core.common import dataToStdout
from lib.core.common import extractRegexResult
from lib.core.common import filterNone
from lib.core.common import getDaysFromLastUpdate
from lib.core.common import getFileItems
from lib.core.common import getSafeExString
from lib.core.common import maskSensitiveData
from lib.core.common import openFile
from lib.core.common import setPaths
from lib.core.common import weAreFrozen
from lib.core.convert import getUnicode
from lib.core.common import setColor
from lib.core.common import unhandledExceptionMessage
from lib.core.compat import LooseVersion
from lib.core.compat import xrange
from lib.core.data import cmdLineOptions
from lib.core.data import conf
from lib.core.data import kb
from lib.core.datatype import OrderedSet
from lib.core.enums import MKSTEMP_PREFIX
from lib.core.exception import SqlmapBaseException
from lib.core.exception import SqlmapShellQuitException
from lib.core.exception import SqlmapSilentQuitException
from lib.core.exception import SqlmapUserQuitException
from lib.core.option import init
from lib.core.option import initOptions
from lib.core.patch import dirtyPatches
from lib.core.patch import resolveCrossReferences
from lib.core.settings import GIT_PAGE
from lib.core.settings import IS_WIN
from lib.core.settings import LAST_UPDATE_NAGGING_DAYS
from lib.core.settings import LEGAL_DISCLAIMER
from lib.core.settings import THREAD_FINALIZATION_TIMEOUT
from lib.core.settings import UNICODE_ENCODING
from lib.core.settings import VERSION
from lib.parse.cmdline import cmdLineParser
from lib.utils.crawler import crawl
except Exception as ex:
print("An error occurred: " + str(ex))
except KeyboardInterrupt:
errMsg = "user aborted"
if "logger" in globals():
logger.critical(errMsg)
raise SystemExit
else:
import time
sys.exit("\r[%s] [CRITICAL] %s" % (time.strftime("%X"), errMsg))
def modulePath():
from lib.core.common import banner # 从lib.core.common模块导入banner函数用于显示程序横幅
from lib.core.common import checkPipedInput # 从lib.core.common模块导入checkPipedInput函数用于检查管道输入
from lib.core.common import checkSums # 从lib.core.common模块导入checkSums函数用于校验文件哈希值
from lib.core.common import createGithubIssue # 从lib.core.common模块导入createGithubIssue函数用于创建GitHub问题
from lib.core.common import dataToStdout # 从lib.core.common模块导入dataToStdout函数用于将数据输出到标准输出
from lib.core.common import extractRegexResult # 从lib.core.common模块导入extractRegexResult函数用于提取正则表达式匹配结果
from lib.core.common import filterNone # 从lib.core.common模块导入filterNone函数用于过滤None值
from lib.core.common import getDaysFromLastUpdate # 从lib.core.common模块导入getDaysFromLastUpdate函数用于计算自上次更新以来的天数
from lib.core.common import getFileItems # 从lib.core.common模块导入getFileItems函数用于从文件中读取内容
from lib.core.common import getSafeExString # 从lib.core.common模块导入getSafeExString函数用于安全地获取异常信息
from lib.core.common import maskSensitiveData # 从lib.core.common模块导入maskSensitiveData函数用于屏蔽敏感数据
from lib.core.common import openFile # 从lib.core.common模块导入openFile函数用于打开文件
from lib.core.common import setPaths # 从lib.core.common模块导入setPaths函数用于设置文件路径
from lib.core.common import weAreFrozen # 从lib.core.common模块导入weAreFrozen函数用于检查程序是否被冻结打包
from lib.core.convert import getUnicode # 从lib.core.convert模块导入getUnicode函数用于将字符串转换为Unicode格式
from lib.core.common import setColor # 从lib.core.common模块导入setColor函数用于设置输出颜色
from lib.core.common import unhandledExceptionMessage # 从lib.core.common模块导入unhandledExceptionMessage函数用于处理未捕获的异常信息
from lib.core.compat import LooseVersion # 从lib.core.compat模块导入LooseVersion类用于版本号比较
from lib.core.compat import xrange # 从lib.core.compat模块导入xrange函数用于兼容Python 2和3的range函数
from lib.core.data import cmdLineOptions # 从lib.core.data模块导入cmdLineOptions对象用于存储命令行选项
from lib.core.data import conf # 从lib.core.data模块导入conf对象用于存储配置信息
from lib.core.data import kb # 从lib.core.data模块导入kb对象用于存储知识库信息
from lib.core.datatype import OrderedSet # 从lib.core.datatype模块导入OrderedSet类用于存储有序集合
from lib.core.enums import MKSTEMP_PREFIX # 从lib.core.enums模块导入MKSTEMP_PREFIX常量表示临时文件前缀
from lib.core.exception import SqlmapBaseException # 从lib.core.exception模块导入SqlmapBaseException类表示sqlmap的基础异常
from lib.core.exception import SqlmapShellQuitException # 从lib.core.exception模块导入SqlmapShellQuitException类表示shell退出异常
from lib.core.exception import SqlmapSilentQuitException # 从lib.core.exception模块导入SqlmapSilentQuitException类表示静默退出异常
from lib.core.exception import SqlmapUserQuitException # 从lib.core.exception模块导入SqlmapUserQuitException类表示用户退出异常
from lib.core.option import init # 从lib.core.option模块导入init函数用于初始化选项
from lib.core.option import initOptions # 从lib.core.option模块导入initOptions函数用于初始化命令行选项
from lib.core.patch import dirtyPatches # 从lib.core.patch模块导入dirtyPatches函数用于应用临时补丁
from lib.core.patch import resolveCrossReferences # 从lib.core.patch模块导入resolveCrossReferences函数用于解决交叉引用问题
from lib.core.settings import GIT_PAGE # 从lib.core.settings模块导入GIT_PAGE常量表示GitHub页面地址
from lib.core.settings import IS_WIN # 从lib.core.settings模块导入IS_WIN常量表示当前操作系统是否为Windows
from lib.core.settings import LAST_UPDATE_NAGGING_DAYS # 从lib.core.settings模块导入LAST_UPDATE_NAGGING_DAYS常量表示提醒更新的天数
from lib.core.settings import LEGAL_DISCLAIMER # 从lib.core.settings模块导入LEGAL_DISCLAIMER常量表示法律声明
from lib.core.settings import THREAD_FINALIZATION_TIMEOUT # 从lib.core.settings模块导入THREAD_FINALIZATION_TIMEOUT常量表示线程结束的超时时间
from lib.core.settings import UNICODE_ENCODING # 从lib.core.settings模块导入UNICODE_ENCODING常量表示默认的Unicode编码
from lib.core.settings import VERSION # 从lib.core.settings模块导入VERSION常量表示程序版本号
from lib.parse.cmdline import cmdLineParser # 从lib.parse.cmdline模块导入cmdLineParser函数用于解析命令行参数
from lib.utils.crawler import crawl # 从lib.utils.crawler模块导入crawl函数用于爬取数据
except Exception as ex: # 捕获所有异常
print("An error occurred: " + str(ex)) # 打印异常信息
except KeyboardInterrupt: # 捕获用户中断如按下Ctrl+C
errMsg = "user aborted" # 定义错误信息
if "logger" in globals(): # 如果logger对象已定义
logger.critical(errMsg) # 记录严重错误信息
raise SystemExit # 退出程序
else: # 如果logger对象未定义
import time # 导入time模块
sys.exit("\r[%s] [CRITICAL] %s" % (time.strftime("%X"), errMsg)) # 退出程序并打印错误信息,包含当前时间
def modulePath(): # 定义modulePath函数用于获取程序的目录路径
"""
获取程序的目录路径即使使用了 py2exe 进行冻结打包也能正确获取
@ -118,15 +118,15 @@ def modulePath():
"""
try:
# 如果程序被py2exe冻结则使用sys.executable获取路径否则使用__file__获取
_ = sys.executable if weAreFrozen() else __file__
except NameError:
_ = sys.executable if weAreFrozen() else __file__ # 如果程序被冻结使用sys.executable获取路径否则使用__file__获取当前文件路径
except NameError: # 如果__file__未定义在某些环境下可能发生则执行以下代码
# 如果__file__未定义在某些环境下可能发生则使用inspect模块获取当前函数的文件路径
_ = inspect.getsourcefile(modulePath)
_ = inspect.getsourcefile(modulePath) # 使用inspect模块获取当前函数的源文件路径
# 获取_的目录路径并转换为Unicode编码
return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystemencoding() or UNICODE_ENCODING)
return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystemencoding() or UNICODE_ENCODING) # 返回_的目录路径并将其转换为Unicode编码
def checkEnvironment():
def checkEnvironment(): # 定义checkEnvironment函数用于检查运行环境是否适合运行sqlmap
"""
检查运行环境是否适合运行 sqlmap
@ -134,32 +134,33 @@ def checkEnvironment():
"""
try:
# 检查程序目录是否存在
os.path.isdir(modulePath())
except UnicodeEncodeError:
os.path.isdir(modulePath()) # 检查modulePath函数返回的路径是否为目录
except UnicodeEncodeError: # 如果系统无法正确处理非ASCII路径则执行以下代码
# 如果系统无法正确处理非ASCII路径则记录错误信息并退出
errMsg = "your system does not properly handle non-ASCII paths. "
errMsg += "Please move the sqlmap's directory to the other location"
logger.critical(errMsg)
raise SystemExit
errMsg = "your system does not properly handle non-ASCII paths. " # 定义错误信息提示系统无法处理非ASCII路径
errMsg += "Please move the sqlmap's directory to the other location" # 建议用户将sqlmap目录移动到其他位置
logger.critical(errMsg) # 记录严重错误信息
raise SystemExit # 退出程序
# 检查sqlmap的版本是否低于1.0,如果是,则说明运行环境有问题
if LooseVersion(VERSION) < LooseVersion("1.0"):
errMsg = "your runtime environment (e.g. PYTHONPATH) is "
errMsg += "broken. Please make sure that you are not running "
errMsg += "newer versions of sqlmap with runtime scripts for older "
errMsg += "versions"
logger.critical(errMsg)
raise SystemExit
if LooseVersion(VERSION) < LooseVersion("1.0"): # 如果当前版本低于1.0
errMsg = "your runtime environment (e.g. PYTHONPATH) is " # 定义错误信息,提示运行环境有问题
errMsg += "broken. Please make sure that you are not running " # 建议用户检查是否使用了旧版本的运行脚本
errMsg += "newer versions of sqlmap with runtime scripts for older " # 提示用户不要使用旧版本的运行脚本运行新版本的sqlmap
errMsg += "versions" # 提示用户检查运行环境
logger.critical(errMsg) # 记录严重错误信息
raise SystemExit # 退出程序
# 如果是通过pip安装的sqlmap则需要对sys.modules进行一些修补操作
if "sqlmap.sqlmap" in sys.modules:
for _ in ("cmdLineOptions", "conf", "kb"):
if "sqlmap.sqlmap" in sys.modules: # 如果sqlmap.sqlmap模块已加载
for _ in ("cmdLineOptions", "conf", "kb"): # 遍历需要修补的变量名
# 将lib.core.data模块中的cmdLineOptions、conf、kb变量添加到全局变量中
globals()[_] = getattr(sys.modules["lib.core.data"], _)
globals()[_] = getattr(sys.modules["lib.core.data"], _) # 将lib.core.data模块中的变量添加到全局变量中
for _ in ("SqlmapBaseException", "SqlmapShellQuitException", "SqlmapSilentQuitException", "SqlmapUserQuitException"):
for _ in ("SqlmapBaseException", "SqlmapShellQuitException", "SqlmapSilentQuitException", "SqlmapUserQuitException"): # 遍历需要修补的异常类名
# 将lib.core.exception模块中的异常类添加到全局变量中
globals()[_] = getattr(sys.modules["lib.core.exception"], _)
globals()[_] = getattr(sys.modules["lib.core.exception"], _) # 将lib.core.exception模块中的异常类添加到全局变量中
def main():
"""
当从命令行运行时这是 sqlmap 的主函数

Loading…
Cancel
Save