python之路第五篇之模塊和加密算法(進階篇:續)


模塊

Python中,如果要引用一些內置的函數,該怎么處理呢?在Python中有一個概念叫做模塊(module)

簡單地說,模塊就是一個保存了Python代碼的文件。

模塊分類;

1)內置模塊

2)自定義模塊

3)第三方模塊

模塊存在方式:

“.py”  
"文件夾"

paramiko 模塊(這個模塊需要安裝,具體安裝方法很簡單,這里不做說明)

用途:linux 主機遠程 用到這個模塊

模塊的導入

在Python中用關鍵字import來引入某個模塊,比如要引用sys這個模塊,就可以在文件最開始的地方用import sys 來導入.

在調用sys模塊中的函數時,必須這樣引用:

 模塊名.函數名

為什么必須加上模塊名這樣調用呢?

因為可能存在這樣一種情況:在多個模塊中含有相同名稱的函數,此時如果只是通過函數名來調用,解釋器無法知道到底要調用哪個函數,所以如果像上述這樣引入模塊的時候,調用函數必須加上模塊名。

模塊導入方式一:

import sys      #導入模塊

print argv      #這樣會報錯
print sys.argv  #這樣才會輸出正常結果

但是有時候我們只需要用到模塊中的某個函數,只需要引入該函數即可,可以使用如下方法:

模塊導入方式二:

from 模塊名 import 函數名1,函數名2....

from sys import argv   #導入模塊
print argv

模塊導入方式三:

from 模塊名 import *

from sys import *  #導入模塊 (這種方式不推薦)
print sys

模塊重命名:

from 模塊名 import 函數名 as 新名字
form sys import argv as test
print test

模塊的獲取幾種方式:

1.自己寫
2.內置
3.下載

自定義模塊:

如何導入自定義模塊?

1.將自定義的模塊導入到python模塊默認路徑中,然后通過 “import 模塊名” 導入

通過如下方式可以獲取模塊路徑,然后將模塊導入到這個路徑中即可:

>>> import sys
>>> sys.path
['', '/Library/Python/2.7/site-packages/pip-0.7.2-py2.7.egg', 
'/Library/Python/2.7/site-packages/redis_py_cluster-1.0.0-py2.7.egg', 
'/Library/Python/2.7/site-packages/redis-2.10.3-py2.7.egg', 
'/Library/Python/2.7/site-packages/paramiko-1.10.1-py2.7.egg', 
'/Library/Python/2.7/site-packages', '/System/
.....
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/plat-darwin', '/'/Library/Python/2.7/site-packages']

因為我的是Mac 電腦,所以python 默認是這個路徑:'/Library/Python/2.7/site-packages'

2.通過 追加的方式,動態的導入自定義的模塊的路徑 到python默認模塊路徑中:

import sys     
sys.path.append('/home/ec2-user/')   #將這個模塊實際存放路徑加載到 python模塊默認路徑

import test #(test.py 這個文件存在在/home/ec2-user/目錄下,則可以通過這種方法)

注意:

如果需要導入一個新建的目錄,則這個目錄下需要存在一個__init__.py 文件:

__init__.py: 是個特殊的py文件,在python中,這個也就是文件夾及模塊包的區別 

內置模塊:

os模塊:用於提供系統級別的操作

os.getcwd()                #獲取當前工作目錄,即當前python腳本工作的目錄路徑
os.chdir("dirname")        #改變當前腳本工作目錄;相當於shell下cd
os.curdir                  #返回當前目錄: ('.')
os.pardir                  #獲取當前目錄的父目錄字符串名:('..')
os.makedirs('dirname1/dirname2')    #可生成多層遞歸目錄
os.removedirs('dirname1')           #若目錄為空,則刪除,並遞歸到上一級目錄,如若也為空,
                                     則刪除,依此類推
os.mkdir('dirname')        #生成單級目錄;相當於shell中mkdir dirname
os.rmdir('dirname')        #刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell
                            中rmdir dirname
os.listdir('dirname')      #列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印
os.remove()                #刪除一個文件
os.rename("oldname","newname")      #重命名文件/目錄
os.stat('path/filename')            #獲取文件/目錄信息
os.sep                     #輸出操作系統特定的路徑分隔符,win下為"\\",Linux下為"/"
os.linesep                 #輸出當前平台使用的行終止符,win下為"\t\n",Linux下為"\n"
os.pathsep                 #輸出用於分割文件路徑的字符串
os.name                    #輸出字符串指示當前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")           #運行shell命令,直接顯示
os.environ                          #獲取系統環境變量
os.path.abspath(path)               #返回path規范化的絕對路徑
os.path.split(path)                 #將path分割成目錄和文件名二元組返回
os.path.dirname(path)      #返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path)     #返回path最后的文件名。如何path以/或\結尾,那么就會返回空值。
                            即os.path.split(path)的第二個元素
os.path.exists(path)       #如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)        #如果path是絕對路徑,返回True
os.path.isfile(path)       #如果path是一個存在的文件,返回True。否則返回False
os.path.isdir(path)        #如果path是一個存在的目錄,則返回True。否則返回False
os.path.join(path1[, path2[, ...]]) #將多個路徑組合后返回,第一個絕對路徑之前的參數
                                     將被忽略
os.path.getatime(path)     #返回path所指向的文件或者目錄的最后存取時間
os.path.getmtime(path)     #返回path所指向的文件或者目錄的最后修改時間

sys:用於提供對解釋器相關的操作

sys.argv                   #命令行參數List,第一個元素是程序本身路徑
sys.exit(n)                #退出程序,正常退出時exit(0)
sys.version                #獲取Python解釋程序的版本信息
sys.maxint                 #最大的Int值
sys.path                   #返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform               #返回操作系統平台名稱
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]

詳細執行:

>>> os.getcwd()
'/Users/yangallen214'

>>> os.chdir('/Users/yangallen214/Desktop')
>>> os.getcwd()
'/Users/yangallen214/Desktop'

>>> os.curdir
'.'

>>> os.curdir
'.'
>>> os.pardir
'..'

>>> os.makedirs('./test/test1')
>>> os.listdir('./test')
['test1', 'yangyh', 'yangyh.zip']

>>> os.removedirs('./test/test1')
>>> os.listdir('./test')
['yangyh', 'yangyh.zip']

>>> os.mkdir('./test/test1')
>>> os.rmdir('./test/test1')
>>> os.listdir('./test')
['yangyh', 'yangyh.zip']

>>> os.makedirs('./test1111/test11')
>>> os.listdir('./test1111/')
['test11']
>>> os.remove('./test1111/test11')   #報錯,是因為它只能刪除文件
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module>
OSError: [Errno 1] Operation not permitted: './test1111/test11'

>>> os.rename('./test1111/test11','./test1111/test12')
>>> os.listdir('./test1111')
['test12']

>>> os.stat('./test1111/test12')
posix.stat_result(st_mode=16877, st_ino=15556867, st_dev=16777220L, st_nlink=2,
st_uid=501, st_gid=20, st_size=68, st_atime=1448451416, st_mtime=1448451416, 
st_ctime=1448451416)

>>> os.sep
'/'
>>>
>>> os.linesep
'\n'
>>> os.pathsep
':'
>>> os.name
'posix'

>>> os.system('pwd')
/Users/yangallen214
0

>>> os.environ
{'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'LOGNAME': 'yangallen214', 'USER': 
'yangallen214', 'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/
.....

>>> os.path.abspath('./test1111')
'/Users/yangallen214/test1111'

>>> os.path.split('./Desktop')
('.', 'Desktop')

>>> os.path.dirname('./Desktop')
'.'
>>> os.path.basename('./Desktop')
'Desktop'


>>> os.path.exists('./test1111/aa.txt')
False

>>> os.path.isabs('./Desktop')
False
>>> os.path.isabs('/Users/yangallen214/Desktop')
True

>>> os.path.isfile('./test1111/aa.txt')
False

>>> os.path.join('/Users/yangallen214/Desktop','./test1111/test12')
'/Users/yangallen214/Desktop/./test1111/test12'
>>> os.path.join('/Users/yangallen214/Desktop','/test1111/test12')
'/test1111/test12'
>>>
>>> os.path.join('/Users/yangallen214/Desktop','./test1111/test12','./test/')
'/Users/yangallen214/Desktop/./test1111/test12/./test/'
>>> os.path.join('/Users/yangallen214/Desktop','./test1111/test12','/test/')
'/test/'

>>> os.path.getatime('./test1111')
1448451671.0
>>> os.path.getmtime('./test1111')
1448451657.0


>>> import sys
>>> sys.argv
['']

>>> sys.version
'2.7.6 (default, Sep  9 2014, 15:04:36) \n[GCC 4.2.1 Compatible Apple LLVM 6.0
 (clang-600.0.39)]'
>>> sys.maxint
9223372036854775807
>>> sys.platform
'darwin'

ConfigParser 模塊

用於對特定的配置進行操作

ConfigParser方法:

1、config=ConfigParser.ConfigParser()  
創建ConfigParser實例  
  
2、config.sections()  
返回配置文件中節序列  
  
3、config.options(section)  
返回某個項目中的所有鍵的序列  
  
4、config.get(section,option)  
得到section中option的值,返回為string類型
  
5、config.add_section(str)  
添加一個配置文件節點(str)
  
6、config.set(section,option,val)  
設置section節點中,鍵名為option的值(val)  
  
7、config.read(filename)  
讀取配置文件  
  
8、config.write(obj_file)  
寫入配置文件  

9、config.items(section) 
得到該section的所有鍵值對

>>> import ConfigParser,sys
>>> 
>>> config=ConfigParser.ConfigParser()
>>> config.add_section("mybook")
>>> config.set("mybook","title","This is mytitile")
>>> config.set("mybook","author","Allen")
>>> config.add_section("size")
>>> config.set("size","size",1024)
>>> config.write(sys.stdout)    #執行結果如下
[mybook]
title = This is mytitile
author = Allen

[size]
size = 1024

Python hashlib和hmac模塊

Python中用於加密的函數位於hashlib,hmac模塊中,都是內置模塊,直接導入即可使用

hashlib模塊實現了md5,sha1,sha224,sha256,sha384,sha512等算法,
可以hashlib.algorithms查看

hmac模塊實現了hmac算法,需要一個key來進行加密

查看可用的加密方式:

>>> import hashlib
>>> hashlib.
hashlib.__all__                     hashlib.__getattribute__(           hashlib.__repr__(                   hashlib.new(
hashlib.__class__(                  hashlib.__hash__(                   hashlib.__setattr__(                hashlib.sha1(
hashlib.__delattr__(                hashlib.__init__(                   hashlib.__sizeof__(                 hashlib.sha224(
hashlib.__dict__                    hashlib.__name__                    hashlib.__str__(                    hashlib.sha256(
hashlib.__doc__                     hashlib.__new__(                    hashlib.__subclasshook__(           hashlib.sha384(
hashlib.__file__                    hashlib.__package__                 hashlib._hashlib                    hashlib.sha512(
hashlib.__format__(                 hashlib.__reduce__(                 hashlib.algorithms
hashlib.__get_builtin_constructor(  hashlib.__reduce_ex__(              hashlib.md5(
>>> hashlib.algorithms
('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')

hashlib 模塊

用於加密相關的操作,代替了md5模塊和sha模塊,主要提供 md5,sha1,sha224,sha256,sha384,sha512 算法

創建一個加密函數對象

>>> import tab   #(這種加密方式將廢棄)
>>> import md5
>>> hash = md5.new()
>>> hash.update('allen123')
>>> print hash.hexdigest()
432a44ddc0aa72ed8c200f53b6268af4
>>>
>>> import sha  #(這種加密方式將廢棄)
>>> hash = sha.new()
>>> hash.update('allen123')
>>> print hash.hexdigest()
2aa55594b365e70a7ee83d9b5923e493d21ee7ff
>>>
>>> import hashlib          #(hashlib)
>>> hash = hashlib.md5()
>>> hash.update('allen123')
>>> print hash.hexdigest()
432a44ddc0aa72ed8c200f53b6268af4
>>>
>>> hash = hashlib.sha1()   #(sha1)
>>> hash.update('allen123')
>>> print hash.hexdigest()
2aa55594b365e70a7ee83d9b5923e493d21ee7ff
>>>
>>>
>>> hash = hashlib.sha256() #(sha256)
>>> hash.update('allen123')
>>> print hash.hexdigest()
7d2ad2f73b51c875d301ae7c57f19772d628771b330a67a750701bdedcd37d5e
>>>
>>>
>>> hash = hashlib.sha384() #(sha384)
>>> hash.update('allen123')
>>> print hash.hexdigest()
b2637c4901864c63a7eadd0da97ddd19417cd81016cfbf20c4984007de04efe78a6cd9b2855e3fb8f0a88546dfe68e1e
>>>
>>>
>>> hash = hashlib.sha512() #(sha512)
>>> hash.update('allen123')
>>> print hash.hexdigest()
41772713f60dc12dd1d183b865c41e914b8ef56d7509b7ae657ad9f7a4be283172e79b71ef42474c4f4aa2b7c3a120e6bf719022d1a647fcbe2e7b3f64d42ddd
>>>


以上加密算法其實但還存在缺陷,別人通過撞庫可以反解,因此有必要對加密算法中添加自定義key來加密。
請看下面兩種:

>>> import hashlib
>>> hash = hashlib.md5('dkujhn33^57Jlddrrlkg')
>>> hash.update('allen123')
>>> print hash.hexdigest()
62b6828287f647d75432905c89b21305

hmac 模塊

它內部對我們創建key和內容再進行處理然后再加密

>>> import hmac
>>> hash = hmac.new("allen123")
>>> hash.update("^test123yyh123^&")
>>> print hash.hexdigest()
6aa286ef24c63e6072b3904802aa795a


免責聲明!

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



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