1.time & DateTime Module
#_ *_coding:utf-8_*_import timeimport datetime print (Time.clock ()) #返回处理器时间, 3.3 started obsolete print (Time.process_time ()) # Returns processor Time, 3.3 beginning of obsolete print (Time.time ()) #返回当前系统时间戳print (Time.ctime ()) #输出Tue Jan 26 18:23:48 2016, current system time print (Time.ctime ( Time.time () -86640)) #将时间戳转为字符串格式print (Time.gmtime (Time.time () -86640)) #将时间戳转换成struct_time格式print (Time.localtime ( Time.time () -86640) #将时间戳转换成struct_time格式, but the returned local time print (Time.mktime (Time.localtime ())) #与time. LocalTime () function instead, Turn the Struct_time format back into timestamp format #time.sleep (4) #sleepprint (Time.strftime ("%y-%m-%d%h:%m:%s", Time.gmtime ())) #将struct_ The time format is converted to the specified string format print (Time.strptime ("2016-01-28", "%y-%m-%d")) #将字符串格式转换成struct_time格式 #datetime module print ( Datetime.date.today ()) #输出格式 2016-01-26print (Datetime.date.fromtimestamp (Time.time () -864400)) #2016-01-16 Turn timestamp into date format current_time = Datetime.datetime.now () #print (current_time) #输出2016 -01-26 19:04:30.335935print (current_ Time.timetuple ()) #返回struct_time格式 #datetime. replace ([year[, month[, day[, hour[, minute[, second[, Microsecond[, Tzinfo]]) print (Current_time.replace (2014,9,12)) #输出2014-09-12 19:06:24.074900, returns the current time, but the specified value will be replaced Str_to_ Date = Datetime.datetime.strptime ("21/11/06 16:30", "%d/%m/%y%h:%m") #将字符串转换成日期格式new_date = Datetime.datetime.now () + Datetime.timedelta (days=10) #比现在加10天new_date = Datetime.datetime.now () + Datetime.timedelta (days=-10) #比现在减10天new_ Date = Datetime.datetime.now () + Datetime.timedelta (hours=-10) #比现在减10小时new_date = Datetime.datetime.now () + Datetime.timedelta (seconds=120) #比现在 +120sprint (new_date)
2.os module:
OS.GETCWD () Gets the current working directory, that is, the directory path of the current Python script work os.chdir ("DirName") changes the current script working directory, equivalent to the shell Cdos.curdir return the current directory: ('. ') Os.pardir Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ') can generate a multi-level recursive directory Os.removedirs (' dirname1 ') if the directory is empty, then deleted, and recursively to the previous level of the directory, if also empty, then delete, and so on Os.mkdir (' DirName ') to generate a single-level directory, equivalent to the shell mkdir dirnameos.rmdir (' dirname ') delete the single-level empty directory, if the directory is not empty can not be deleted, error; equivalent to the shell rmdir Dirnameos.listdir (' dirname ') lists all files and subdirectories under the specified directory, including hidden files, and prints os.remove () Delete a file Os.rename ("Oldname", "newname") Rename File/directory Os.stat (' Path/filename ') Get File/directory information OS.SEP output operating system-specific path delimiter, win under "\ \", Linux for "/" OS.LINESEP output the current platform using the line terminator, win under "\t\n", Linux "\ N "os.pathsep output string to split file path Os.name output string indicates the current usage platform. Win-> ' NT '; Linux-> ' POSIX ' Os.system ("Bash command") runs a shell command that directly displays the Os.environ get system environment variable Os.path.abspath (PATH) Return path normalized absolute path Os.path.split (path) splits path into directory and file name two tuples return Os.path.dirname (path) to the directory where path is returned. In fact, the first element of Os.path.split (path) os.path.basename returns the last file name of path. If path ends with a/or \, then a null value is returned. A second element of Os.path.split (PATH) os.path.exists (Path) If path exists, returns true if path does not exist, return Falseos.path.isabs (PATH) If path is an absolute path, return Trueos.path.isfile (PATH) If path is a file that exists, Returns True. Otherwise, return Falseos.path.isdir (path) True if path is a directory that exists. Otherwise return Falseos.path.join (path1[, path2[, ...]) When multiple paths are combined, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the last access time of the file or directory to which path is pointing os.path.getmtime (path) Returns the last modified time of the file or directory to which path is pointing
3.random module:
Mport randomprint random.random () Print random.randint print Random.randrange (1,10)
Use it to generate a random verification code:
Import Randomcheckcode = ' For I in range (4): Current = Random.randrange (0,4) if current! = I: temp = chr (rand Om.randint (65,90)) else: temp = random.randint (0,9) Checkcode + = str (temp) Print Checkcode
4.sys module:
SYS.ARGV command line argument list, the first element is the program itself path Sys.exit (n) exits the program, exit normally (0) sys.version Gets the version information of the Python interpreter Sys.maxint the largest int value Sys.path returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing Sys.platform Returns the operating system platform name Sys.stdout.write (' please: ') val = Sys.stdin.readline () [:-1]
5.hashlib module:
For cryptographic related operations, instead of the MD5 module and the SHA module, mainly provides SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithm
Import Hashlib # ######## MD5 ######## hash = HASHLIB.MD5 () hash.update (' admin ') print hash.hexdigest () # ######## SHA1 # # # # # # # hash = HASHLIB.SHA1 () hash.update (' admin ') print hash.hexdigest () # ######## sha256 ######## hash = hashlib.sha256 () ha Sh.update (' admin ') print hash.hexdigest () # ######## sha384 ######## hash = hashlib.sha384 () hash.update (' admin ') Print hash.hexdigest () # ######## sha512 ######## hash = hashlib.sha512 () hash.update (' admin ') print hash.hexdigest ()
Although the above encryption algorithm is still very strong, but the time has the flaw, namely: through the collision library can reverse the solution. Therefore, it is necessary to add a custom key to the encryption algorithm to do encryption.
Import Hashlib # ######## MD5 ######## hash = hashlib.md5 (' 898oafs09f ') hash.update (' admin ') print hash.hexdigest ()
Python also has an HMAC module that internally creates keys and content for us to process and then encrypt
Import Hmach = hmac.new (' Wueiqi ') h.update (' Hellowo ') print h.hexdigest ()
6.json module:
Serialization:
Import jsonuser_info = { ' name ': username, ' password ':p assword,}f = open (' ... /user_info/user_info.json
Deserialization:
Import jsonf = Open ('./user_info.json ', ' r ') data = Json.loads (F.read ()) print (Data,type (data)) Result: ({' Password ': ' 1 ') , ' name ': ' 2 '}, <type ' Dict ' >)
7.shutil module:
Base_name: The file name of the compressed package, or the path to the compressed package. is only the file name, save to the current directory, otherwise save to the specified path, such as: www. = Save to the current path such as:/users/eddy/www = Save to/users/eddy/format: package type, "Zip", "tar", "Bztar", "Gztar" Root_dir: Folder path to compress (default current directory) Owner: User, default Current user group: groups, default current group logger: used for logging, usually logging. Logger Object #将/users/eddy/downloads/test file package to place the current program directory import shutil ret = shutil.make_archive ("wwwwwwwwww", ' Gztar ', Root_dir= '/users/eddy/downloads/test ') #将/users/eddy/downloads/test files under package placement/users/eddy/Catalog Import shutil ret = Shuti L.make_archive ("/users/eddy/wwwwwwwwww", ' Gztar ', root_dir= '/users/eddy/downloads/test ') shutil handling of compressed packets is called ZipFile and Tarfile two modules, verbose: Import zipfile # compression z = zipfile. ZipFile (' Laxi.zip ', ' W ') z.write (' A.log ') z.write (' Data.data ') Z.close () # Unzip z = zipfile. ZipFile (' Laxi.zip ', ' R ') Z.extractall () z.close () ZipFile compression extract Import Tarfile # Compress tar = Tarfile.open (' Your.tar ', ' W ') Tar.add ('/users/eddy/pycharmprojects/bbs2.zip ', arcname= ' Bbs2.zip ') tar.add ('/users/eddy/pycharmProjects/cmdb.zip ', arcname= ' Cmdb.zip ') Tar.close () # Unzip tar = Tarfile.open (' Your.tar ', ' R ') Tar.extractall () # To set the decompression address Tar.close ()
8.logging module:
Module for easy logging and thread-safe
Import Logginglogging.debug (' This was debug message ') Logging.info (' This is Info message ') logging.warning (' This is Warning message ') printed on screen: WARNING:root:This is warning message
By default, logging prints the log to the screen with a log level of warning;
Log level size relationships are: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the log level yourself.
Output logs to files and screens at the same time:
Import Logginglogging.basicconfig (level=logging. DEBUG, format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ', datefmt = '%a,%d%b%Y%h:%m:%s ', filename= ' Myapp.log ', filemode= ' W ') ############################### ################################################################## #定义一个StreamHandler, print info-level or higher log information to standard error, and add it to the current log processing object #console = logging. Streamhandler () console.setlevel (logging.info) formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ') Console.setformatter (Formatter) Logging.getlogger ('). AddHandler (console) ########################################################################################### ##### #logging. Debug (' This is Debug message ') Logging.info ("This is Info message") logging.warning (' This is warning Message ') on screen: Root:info This is INFO messageroot:warning the contents of this is WARNING Message./myapp.log file : Sun, May 21:48:54 Demo2.py[line:11] DebuG This is the debug Messagesun, 21:48:54 Demo2.py[line:12] Info This is info Messagesun, 21:48:54 demo 2.PY[LINE:13] WARNING This is WARNING message
9.paramiko module:
Paramiko is a module for remote control, which can be used to command or file the remote server, it is worth saying that the fabric and ansible internal remote management is the use of Paramiko to reality.
(1) Download and install:
# Pycrypto, because the Paramiko module is internally dependent on Pycrypto, so download and install Pycrypto # download Install Pycryptowget http://files.cnblogs.com/files/wupeiqi/ PYCRYPTO-2.6.1.TAR.GZTAR-XVF pycrypto-2.6.1.tar.gzcd pycrypto-2.6.1python setup.py buildpython setup.py Install # Enter the python environment, import crypto check whether the installation is successful # download install Paramikowget Http://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gztar- XVF paramiko-1.10.1.tar.gzcd paramiko-1.10.1python setup.py buildpython setup.py Install # into the Python environment, Import Paramiko Check whether the installation was successful
(2) Execute the command, connect to the server via username and password:
#!/usr/bin/env python#coding:utf-8import paramikossh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) ssh.connect (' 192.168.1.108 ', +, ' Alex ', ' 123 ') stdin, stdout, stderr = Ssh.exec_command (' df ') print Stdout.read () ssh.close ();
(3) Upload or download files, verified by username and password:
Import Os,sysimport Paramikot = Paramiko. Transport (' 182.92.219.86 ', ()) T.connect (username= ' Wupeiqi ', password= ' 123 ') sftp = Paramiko. Sftpclient.from_transport (t) sftp.put ('/tmp/test.py ', '/tmp/test.py ') t.close () import Os,sysimport Paramikot = Paramiko. Transport (' 182.92.219.86 ', ()) T.connect (username= ' Wupeiqi ', password= ' 123 ') sftp = Paramiko. Sftpclient.from_transport (t) sftp.get ('/tmp/test.py ', '/tmp/test2.py ') t.close ()
(4) Upload or download the file via key verification:
Import Paramikopravie_key_path = '/home/auto/.ssh/id_rsa ' key = Paramiko. Rsakey.from_private_key_file (pravie_key_path) t = Paramiko. Transport (' 182.92.219.86 ', ()) T.connect (username= ' Wupeiqi ', pkey=key) sftp = Paramiko. Sftpclient.from_transport (t) sftp.put ('/tmp/test3.py ', '/tmp/test3.py ') t.close () Import Paramikopravie_key_path = '/ Home/auto/.ssh/id_rsa ' key = Paramiko. Rsakey.from_private_key_file (pravie_key_path) t = Paramiko. Transport (' 182.92.219.86 ', ()) T.connect (username= ' Wupeiqi ', pkey=key) sftp = Paramiko. Sftpclient.from_transport (t) sftp.get ('/tmp/test3.py ', '/tmp/test4.py ') t.close ()
Use of Python time, datetime, OS, random, SYS, HASHLIB, JSON, shutil, logging, Paramiko modules