在閱讀sqlmap源碼時學到的知識--檢查運行環境

    最近在讀sqlmap的源碼,懵懵懂懂中頁大約學到了一些知識(說給本身聽的話:因而可知,所謂的可以解決全部遇到問題的python水平,只能說明你碰見的都是簡單的需求。。。。),老規矩,在這裏寫一下,一則備忘,二則鞏固python

    首先,sqlmap第一步sql

1 def main():
2     """
3     Main function of sqlmap when running from command line.
4     """
5 
6     try:
7         checkEnvironment()
8         setPaths(modulePath())
9         banner()

第一步就是檢查環境,進入checkEnvironment查看,發現函數

1 def checkEnvironment():
2     try:
3         os.path.isdir(modulePath())
4     except UnicodeEncodeError:
5         errMsg = "your system does not properly handle non-ASCII paths. "
6         errMsg += "Please move the sqlmap's directory to the other location"
7         logger.critical(errMsg)
8         raise SystemExit

這個地方有一個modulePath()引發了個人興趣,由於點進去查看了一下他是個啥,居然沒看明白。。。工具

 1 def modulePath():
 2     """
 3     This will get us the program's directory, even if we are frozen
 4     using py2exe
 5     """
 6 
 7     try:
11         _ = sys.executable if weAreFrozen() else __file__
12     except NameError:
13         _ = inspect.getsourcefile(modulePath)
14 
15     return getUnicode(os.path.dirname(os.path.realpath(_)),
16                       encoding=sys.getfilesystemencoding() or UNICODE_ENCODING)
 _ = sys.executable if weAreFrozen() else __file__

這一句從邏輯上分析,‘_ ’這個變量,若是weAreFrozen()==True,那麼它等於sys.executable,sys.executable點進去查看,原來是python.exe所處位置,可是從代碼上來看,這段
應該是獲取的sqlmap目錄,而不該該是解釋器目錄啊,而後else獲取的是__file__,這個都知道,獲取執行目錄,相對路勁執行獲取相對目錄,絕對路勁執行獲取絕對目錄,想一想看,難道說
weAreFrozen永遠不可能爲True嗎?

咱們點進去看一下這個weAreFrozen究竟是什麼
1 def weAreFrozen():
2     """
3     Returns whether we are frozen via py2exe.
4     This will affect how we find out where we are located.
5     Reference: http://www.py2exe.org/index.cgi/WhereAmI
6     """
7 
8     return hasattr(sys, "frozen")

     學識有限,沒看出這是啥意思。。。那就去註釋裏面那個網址瞅瞅。。就是http://www.py2exe.org/index.cgi/WhereAmI這個。英文水平有限,只能看懂個大概意思,大約是說測試

若是sys含有frozen屬性,證實你運行的是被打包成exe的文件,若是沒有的話,你執行的就是script。哦?是這樣嗎?寫個腳本驗證下:ui

1 # -*- coding: utf-8 -*-
2 # ====================================================
3 # @ Creator:Hainan.Zhang
4 # @ Date:2017-7-21
5 # 測試
6 # ====================================================
7 import sys
8 print sys.executable
9 print hasattr(sys, "frozen")

咱們使用pyinstaller將這個.py文件打包成exe編碼

而後這行一下,pyinstaller在命令行運行,將在命令行路勁新增build和dist文件夾,要去dist裏面找這個test.exe。spa

確實沒錯,原來打包成exe的文件,那麼sys.executable將顯示爲被執行exe路勁,sys會多出frozen屬性。咱們接着看modulePath,後面一旦出現NameError,那麼在except語句命令行

中,_賦值爲inspect.getsourcefile(modulePath),getsourcefile的做用點進去看註釋就很明顯 ,也是返回這段代碼所在路勁。3d

  modulePath的最後,return語句中調用了本身寫的getUnicode函數,將獲取的路勁轉換爲想要的編碼encoding=sys.getfilesystemencoding() or UNICODE_ENCODING

 若是該文件指定了編碼格式,那麼編碼格式爲指定格式,若是沒有,就轉換爲unicode,有一本書叫作什麼改善python程序的59個方法,裏面寫到,咱們要本身實現編碼轉換函數,已解決本身項目中的編碼問題,這個getUnicode能夠做爲範例。防止中文,日文等路勁的影響。

     sqlmap不愧是神級工具,源碼裏面這一小段,讓我收穫頗多,堅持讀下去。有感悟的時候再和你們分享

相關文章
相關標籤/搜索