干货分享丨Python从入门到编写POC之常用的标准库

2020-07-01 8,445

Python从入门到编写POC系列文章是i春秋论坛作家「Exp1ore」表哥原创的一套完整教程,想系统学习Python技能的小伙伴,不要错过哦!

beb9667d7a2043f2afd67f9df6246dde.jpg


常用的标准库

安装完Python之后,我们也同时获得了强大的Python标准库,通过使用这些标准库可以为我们节省大量的时间,这里是一些常用标准库的简单说明。

Python的标准库包括了很多模块,从Python语言自身特定的类型和声明,到一些只用于少数程序的不著名模块,任何大型Python程序都有可能直接或间接地使用到这类模块的大部分内容。

sys模块

咱们之前已经接触过了sys模块,sys.path.append( ),可以通过help命令查看文档,然后不断的回车查看。

微信图片_20200701101932.gif

或者用这个命令:

>>> 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 modules
displayhook -- 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解释器传递参数他的功能是获取程序外部向程序传递的参数。

举个例子:

18534f8c5e784602baca14fec8d3aaf7.jpg

为了更好的理解,再写一个程序:

#coding = utf-8
import sys
def demo():        if len(sys.argv) < 2:                print 'no action'                sys.exit()  #退出当前程序        for i in range(len(sys.argv)):                print 'arg['+str(i)+']',sys.argv
if __name__ == '__main__':        demo()

747e09d3123f48f9b7a8a10ec853e80c.jpg

sys.stdin,sys.stdout,sys.stderr,处理标准输入,标准输出,标准错误。

输出和错误是内建在每个unix系统中的管道,print的本质就是sys.stdout.write。

image.png

stdout是一个类文件对象,调用了其write函数就可以打印任何的字符串了,它们不会添加回车,要自己添加\n,但是只有write的办法,没有read的方法。

还是由于是类文件对象,因此可以讲任何类文件赋值,然后重定向输出,那可能会问,啥是重定向输出,简而言之,就是将输出内容从"控制台"转到"文件"。

举个例子,进一步理解:

image.png

最后为啥多了一个\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( )命令,这里介绍几个常用的:

image.png

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

以下是Winods系统:

>>> command = 'dir'>>> import os>>> os.system(command)驱动器 D 中的卷没有标签。卷的序列号是 626B-88AA
D:\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

c58d41bbd39d4f8b94771a11f51d6e5d.gif


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( )

>>> demo_data = json.loads(data_json)  #将data_json解码
>>> print demo_data
[{u'username': u'ichunqiu', u'content': [u'BaZong', u'handsome'], u'password': u'BaZong'}]

hashlib模块

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

举个例子,计算一个md5值:

image.png

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']

image.png

urllib/urlib2这两个模块,感兴趣的小伙伴可以在网上自学哦。

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


前期回顾>>

Python从入门到编写POC之特殊函数


本文作者:i春秋聚集地

本文为安全脉搏专栏作者发布,转载请注明:https://www.secpulse.com/archives/134333.html

Tags:
评论  (0)
快来写下你的想法吧!

i春秋聚集地

文章数:24 积分: 225

i春秋聚集地旨在为信息安全爱好者提供及时有效的信息渠道和体验平台,欢迎关注公众号(icqedu),和“i春秋学院”微博了解更多网络安全新知识~

安全问答社区

安全问答社区

脉搏官方公众号

脉搏公众号