干貨分享丨Python從入門到編寫POC之常用的標准庫


Python從入門到編寫POC系列文章是i春秋論壇作家「Exp1ore」表哥原創的一套完整教程,想系統學習Python技能的小伙伴,不要錯過哦!

干貨分享丨Python從入門到編寫POC之常用的標准庫

 

常用的標准庫

安裝完Python之后,我們也同時獲得了強大的Python標准庫,通過使用這些標准庫可以為我們節省大量的時間,這里是一些常用標准庫的簡單說明。

Python的標准庫包括了很多模塊,從Python語言自身特定的類型和聲明,到一些只用於少數程序的不著名模塊,任何大型Python程序都有可能直接或間接地使用到這類模塊的大部分內容。

sys模塊

咱們之前已經接觸過了sys模塊,sys.path.append( ),可以通過help命令查看文檔,然后不斷的回車查看。

或者用這個命令:

>>> print sys.__doc__This module provides access to some objects used or maintained by theinterpreter and to functions that interact strongly with the interpreter.Dynamic objects:argv -- command line arguments; argv[0] is the script pathname if knownpath -- module search path; path[0] is the script directory, else ''modules -- dictionary of loaded modulesdisplayhook -- called to show results in an interactive sessionexcepthook -- called to handle any uncaught exception other than SystemExit To customize printing in an interactive session or to install a custom top-level exception handler, assign other functions to replace these.exitfunc -- if sys.exitfunc exists, this routine is called when Python exits Assigning to sys.exitfunc is deprecated; use the atexit module instead.stdin -- standard input file object; used by raw_input() and input()stdout -- standard output file object; used by the print statementstderr -- standard error object; used for error messages By assigning other file objects (or objects that behave like files) to these, it is possible to redirect all of the interpreter's I/O.last_type -- type of last uncaught exceptionlast_value -- value of last uncaught exceptionlast_traceback -- traceback of last uncaught exception These three are only available in an interactive session after a traceback has been printed.exc_type -- type of exception currently being handledexc_value -- value of exception currently being handledexc_traceback -- traceback of exception currently being handled The function exc_info() should be used instead of these three, because it is thread-safe.Static objects:float_info -- a dict with information about the float inplementation.long_info -- a struct sequence with information about the long implementation.maxint -- the largest supported integer (the smallest is -maxint-1)maxsize -- the largest supported length of containers.maxunicode -- the largest supported characterbuiltin_module_names -- tuple of module names built into this interpreterversion -- the version of this interpreter as a stringversion_info -- version information as a named tuplehexversion -- version information encoded as a single integercopyright -- copyright notice pertaining to this interpreterplatform -- platform identifierexecutable -- absolute path of the executable binary of the Python interpreterprefix -- prefix used to find the Python libraryexec_prefix -- prefix used to find the machine-specific Python libraryfloat_repr_style -- string indicating the style of repr() output for floatsdllhandle -- [Windows only] integer handle of the Python DLLwinver -- [Windows only] version number of the Python DLL__stdin__ -- the original stdin; don't touch!__stdout__ -- the original stdout; don't touch!__stderr__ -- the original stderr; don't touch!__displayhook__ -- the original displayhook; don't touch!__excepthook__ -- the original excepthook; don't touch!Functions:displayhook() -- print an object to the screen, and save it in __builtin__._excepthook() -- print an exception and its traceback to sys.stderrexc_info() -- return thread-safe information about the current exceptionexc_clear() -- clear the exception state for the current threadexit() -- exit the interpreter by raising SystemExitgetdlopenflags() -- returns flags to be used for dlopen() callsgetprofile() -- get the global profiling functiongetrefcount() -- return the reference count for an object (plus one :-)getrecursionlimit() -- return the max recursion depth for the interpretergetsizeof() -- return the size of an object in bytesgettrace() -- get the global debug tracing functionsetcheckinterval() -- control how often the interpreter checks for eventssetdlopenflags() -- set the flags to be used for dlopen() callssetprofile() -- set the global profiling functionsetrecursionlimit() -- set the max recursion depth for the interpretersettrace() -- set the global debug tracing function

sys.argv是變量,命令行參數,專門向Python解釋器傳遞參數他的功能是獲取程序外部向程序傳遞的參數。

舉個例子:

干貨分享丨Python從入門到編寫POC之常用的標准庫

 

為了更好的理解,再寫一個程序:

#coding = utf-8import sysdef demo(): if len(sys.argv) < 2: print 'no action' sys.exit() #退出當前程序 for i in range(len(sys.argv)): print 'arg['+str(i)+']',sys.argvif __name__ == '__main__': demo()
干貨分享丨Python從入門到編寫POC之常用的標准庫

 

sys.stdin,sys.stdout,sys.stderr,處理標准輸入,標准輸出,標准錯誤。

輸出和錯誤是內建在每個unix系統中的管道,print的本質就是sys.stdout.write。

>>> for i in range(6):... print "HELLO MOMO!"...HELLO MOMO!HELLO MOMO!HELLO MOMO!HELLO MOMO!HELLO MOMO!HELLO MOMO!>>> import sys>>> for i in range(6):... sys.stdout.write("HELLO BaZong\n")...HELLO BaZongHELLO BaZongHELLO BaZongHELLO BaZongHELLO BaZongHELLO BaZong

stdout是一個類文件對象,調用了其write函數就可以打印任何的字符串了,它們不會添加回車,要自己添加\n,但是只有write的辦法,沒有read的方法。

還是由於是類文件對象,因此可以講任何類文件賦值,然后重定向輸出,那可能會問,啥是重定向輸出,簡而言之,就是將輸出內容從"控制台"轉到"文件"。

舉個例子,進一步理解:

>>> import sys>>> print "HELLO BaZong" #標准輸出HELLO BaZong>>> demo = sys.stdout #重定向之前保存demo>>> demo2 = open('test.txt','w')>>> sys.stdout = demo2 #之后的輸出重定向到剛打開的test.txt>>> print "HELLO ichunqiu" #這句話只會輸出打印到txtz文件中,屏幕看不到輸出>>> demo2.close()>>> sys.stdout = demo #將stdout恢復成原來的方式>>> demo3 = open('test.txt','r')>>> demo3.read()'HELLO ichunqiu\n'

最后為啥多了一個\n?

是因為print會在即將要打印的字符串后面加一個硬回車。

os模塊

先看一下os模塊里有什么內容:

>>> import os>>> dir(os)['F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fstat', 'fsync', 'getcwd', 'getcwdu', 'getenv', 'getpid', 'isatty', 'kill', 'linesep', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'sys', 'system', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'umask', 'unlink', 'unsetenv', 'urandom', 'utime', 'waitpid', 'walk', 'write']

然后用help( )命令,這里介紹幾個常用的:

>>> import os>>> os.name #判斷現在正在實用的平台,Windows平台"nt",linux平台"posix"'nt'>>> os.getcwd() #獲取當前目錄'D:\\ichunqiu\\items'>>> os.listdir("D:/ichunqiu")['bsrc&ichunqiu', 'items', 'task']>>> import os>>> os.name #判斷現在正在實用的平台,Windows平台"nt",linux平台"posix"'nt'>>> os.getcwd() #獲取當前目錄'D:\\ichunqiu\\items'>>> os.listdir("D:/ichunqiu") #列D:/ichunqiu文件夾的目錄['bsrc&ichunqiu', 'items', 'task']>>> os.mkdir("demo") #在本文件x夾下建立一個叫demo的文件夾>>> os.listdir("D:/ichunqiu/items") #查看目錄有沒有demo的文件夾['cmd.bat', 'ctf.py', 'demo', 'demo.py', 'flag.txt', 'ichunqiu', 'test.txt']>>> os.rmdir("demo") #刪除叫demo的文件夾>>> os.listdir("D:/ichunqiu/items") #查看文件夾,發現沒有demo文件夾了['cmd.bat', 'ctf.py', 'demo.py', 'flag.txt', 'ichunqiu', 'test.txt']>>> os.rename("test.txt","test1.txt") #將test.txt重名為test1.txt>>> os.listdir("D:/ichunqiu/items") #查看文件夾,發現test.txt改成了test1.txt['cmd.bat', 'ctf.py', 'demo.py', 'flag.txt', 'ichunqiu', 'test1.txt']>>> os.remove("test1.txt") #刪除test1.txt的文件>>> os.listdir("D:/ichunqiu/items") #查看文件夾,發現沒有了test1.txt['cmd.bat', 'ctf.py', 'demo.py', 'flag.txt', 'ichunqiu']

os庫提供了在Python中使用操作系統的命令的方法就是用os.system()。

以下是Winods系統:

>>> command = 'dir'>>> import os>>> os.system(command)驅動器 D 中的卷沒有標簽。卷的序列號是 626B-88AAD:\ichunqiu\items 的目錄2017/08/23 10:34 <DIR> .2017/08/23 10:34 <DIR> ..2017/08/15 21:42 7 cmd.bat2017/08/21 21:22 521 ctf.py2017/08/23 10:34 7,446 demo.py2017/08/21 12:05 23 flag.txt2017/08/20 18:08 <DIR> ichunqiu2017/08/22 22:38 16 test.txt5 個文件 8,013 字節3 個目錄 353,137,557,504 可用字節0
干貨分享丨Python從入門到編寫POC之常用的標准庫

 

time模塊

time模塊很常用的,比如說在延時注入中,就要用到它,可以精確的知道程序的運行長短。

>>> import time>>> time.time() #獲取當前時間的時間戳1503480040.985>>> time.clock() #獲取進程的時間60.641674890547975>>> time.localtime() #時間戳轉換成當地的時間time.struct_time(tm_year=2017, tm_mon=8, tm_mday=23, tm_hour=17, tm_min=20, tm_sec=48, tm_wday=2, tm_yday=235, tm_isdst=0)>>> time.asctime() #將元祖表示為'Wed Aug 23 17:24:07 2017'這種形式'Wed Aug 23 17:24:27 2017'

json模塊

JSON(JavaScript Object Notation, JS 對象標記) 是一種輕量級的數據交換格式。它基於ECMAScript (w3c制定的js規范)的一個子集,采用完全獨立於編程語言的文本格式來存儲和表示數據。

簡潔和清晰的層次結構使得JSON成為理想的數據交換語言,易於人閱讀和編寫,同時也易於機器解析和生成,並有效地提升網絡傳輸效率。

Python標准庫中有JSON模塊,主要是兩個功能,序列化(encoding)與反序列化(decoding)。

encoding操作:dumps( )

>>> import json>>> data = [{"username":"ichunqiu","password":"BaZong","content":("BaZong","handsome")}]>>> print data[{'username': 'ichunqiu', 'content': ('BaZong', 'handsome'), 'password': 'BaZong'}]>>> data_json = json.dumps(data) #將data進行格式的編碼轉換>>> print data_json[{"username": "ichunqiu", "content": ["BaZong", "handsome"], "password": "BaZong"}]

這里的data_json是str類型,data是list類型。

decoding操作:loads( )

>>> import random>>> random.random() #生成大於等於0,小於等於1的隨機浮點數0.766691871394984>>> random.uniform(66,88) #生成66到88之間的隨機浮點數80.51121638510607>>> random.randint(66,88) #生成66到88的整數88>>> random.choice('BaZong') #在BaZong生成隨機字符'n'>>> demo = [1,2,3,4,5,6]>>> random.shuffle(demo) #打亂數字>>> demo[1, 4, 3, 5, 2, 6]

hashlib模塊

Python中的hashlib庫提供了大量的摘要算法,又叫散列算法,哈希算法。

舉個例子,計算一個md5值:

>>> import random>>> random.random() #生成大於等於0,小於等於1的隨機浮點數0.766691871394984>>> random.uniform(66,88) #生成66到88之間的隨機浮點數80.51121638510607>>> random.randint(66,88) #生成66到88的整數88>>> random.choice('BaZong') #在BaZong生成隨機字符'n'>>> demo = [1,2,3,4,5,6]>>> random.shuffle(demo) #打亂數字>>> demo[1, 4, 3, 5, 2, 6]

random模塊

生成隨機數的

>>> import random>>> dir(random)['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> import random>>> random.random() #生成大於等於0,小於等於1的隨機浮點數0.766691871394984>>> random.uniform(66,88) #生成66到88之間的隨機浮點數80.51121638510607>>> random.randint(66,88) #生成66到88的整數88>>> random.choice('BaZong') #在BaZong生成隨機字符'n'>>> demo = [1,2,3,4,5,6]>>> random.shuffle(demo) #打亂數字>>> demo[1, 4, 3, 5, 2, 6]

urllib/urlib2這兩個模塊,感興趣的小伙伴可以在網上自學哦。

以上是今天要分享的內容,大家看懂了嗎?

前期回顧:

Python從入門到編寫POC之特殊函數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM