Python module basics


Module, a collection of codes that implements a certain function using Yitong code.

Similar to functional programming and process-oriented programming, functional programming completes a function and can be called by other codes, providing code reusability and coupling between codes. For a complex function, multiple functions may be required to complete (the functions can be in different .py files). The code collection composed of n .py files is called a module.

For example: os is a system-related module; file is a module related to file operations

There are three types of modules:

  • Customized modules
  • Built-in module
  • Open source module

Custom module

1. Define module

Scenario One:

Scenario two:

## Scenario Three:


##2. Import module


The reason why Python is becoming more and more widely used depends, to a certain extent, on the There are a large number of modules available for use. If you want to use a module, you need to import it. There are several ways to import modules:

import modulefrom module.xx.xx import xxfrom module.xx.xx import xx as rename  
from module.xx.xx import *

The import module actually tells the Python interpreter to interpret the py file.

  • Import a py file, and the interpreter interprets the py file.
  • Import a package, and the interpreter interprets the py file. The __init__.py file under the package

Then the question is, when importing the module, which path is used as the basis? That is: sys.path

import sys
print sys.path
  
结果:

['E:\Python\\xc1\xb7\xcf\xb0', 'E:\Python', 'C:\Windows\SYSTEM32\python27.zip', 'D:\Install\Python\DLLs', 'D:\Install\Python\lib', 'D:\Install\Python\lib\plat-win', 'D:\Install\Python\lib\lib-tk', 'D:\Install\Python', 'D:\Install\Python\lib\site-packages']
If the sys.path path list does not have the path you want, you can add it through sys.path.append('path').
Various directories can be obtained through the os module, such as:
import sys
import os

pre_path = os.path.abspath('../')
sys.path.append(pre_path)

Open source module

1. Download and install

There are two ways to download and install:

yum 
pip
apt-get
...
下载源码
解压源码
进入目录
编译源码    python setup.py build
安装源码    python setup.py install
Note: When using source code installation, you need to use gcc compilation and python development environment, so you need to execute it first:
yum install gcc
yum install python-devel
或
apt-get python-dev
After successful installation, the module will be automatically installed into a directory in sys.path, such as:
/usr/lib/python2.7/site-packages/

2. Import the module

Same as the import method in custom modules

3. Module paramiko

paramiko is a module used for remote control. This module can be used to command or control the remote server. For file operations, it is worth mentioning that the remote management within fabric and ansible is implemented using paramiko.

1. Download and install

# pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto
 
# 下载安装 pycrypto
wget http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gz
tar -xvf pycrypto-2.6.1.tar.gz
cd pycrypto-2.6.1
python setup.py build
python setup.py install
 
# 进入python环境,导入Crypto检查是否安装成功
 
# 下载安装 paramiko
wget http://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gz
tar -xvf paramiko-1.10.1.tar.gz
cd paramiko-1.10.1
python setup.py build
python setup.py install
 
# 进入python环境,导入paramiko检查是否安装成功
2. Use the module
#!/usr/bin/env python
#coding:utf-8

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.108', 22, 'alex', '123')
stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close();
import paramiko

private_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(private_key_path)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('主机名 ', 端口, '用户名', key)

stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close()
import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='123')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test.py','/tmp/test.py') 
t.close()


import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='123')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test.py','/tmp/test2.py')
t.close()

上传或者下载文件 - 通过用户名和密码
import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test3.py','/tmp/test3.py') 

t.close()

import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test3.py','/tmp/test4.py') 

t.close()

上传或下载文件 - 通过密钥


Built-in module

1. os

is used to provide system-level operations

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所指向的文件或者目录的最后修改时间

2. sys

is used to provide Provides interpreter-related operations

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]

SYS模块

3. hashlib

is used for encryption-related operations, replacing the md5 module and sha module, mainly providing SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithm

import md5
hash = md5.new()
hash.update('admin')
print hash.hexdigest()
import sha

hash = sha.new()
hash.update('admin')
print hash.hexdigest()
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()
hash.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 algorithms are still very powerful, they still have flaws, that is, they can be reversed through credential stuffing. Therefore, it is necessary to add a custom key to the encryption algorithm before performing encryption.
import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5('898oaFs09f')
hash.update('admin')
print hash.hexdigest()
is not powerful enough? Python also has a hmac module, which internally creates keys and content for us to process and then encrypt them
import hmac
h = hmac.new('wueiqi')
h.update('hellowo')
print h.hexdigest()