Python-commonly used modules (yagmail module, configparser module, paramiko module, os module, pymysql module)

In this chapter:

  1. yagmail module
  2. configparser module
  3. paramiko module
  4. os module
  5. pymysql module

yagmail module

The module for sending emails in the Python standard library is more complicated. So, many open source libraries provide a more easy-to-use interface to send emails. Among them, yagmail is a widely used open source project. The bottom layer of yagmail still uses smtplib and email modules, but provides It has a better interface and has better legibility.

Step 1: Install yagmail module

pip install yagmail

Step 2: Send email

#导入yagmail模块
import yagmail

#1.实例化出来一个yagmail对象
yag = yagmail.SMTP(user='[email protected]',password='xxxx',host='smtp.163.com')

##(可选)编写内容(其实contents就是一个变量)
contents='hello world!!!'

#2.发送邮件操作
yag.send(to='接收端@163.com',subject=None,contents=contents)

##3.断开连接
yag.close()

Extension 1: Send multiple users

yag.send(to=['[email protected]','[email protected]'],subject=subject,contents)

Extension 2: Send attachments

contents=['邮件内容','附件路径']

Send mail using smtplib module

python send mail (without attachment)

import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receiver = '[email protected]'
subject = '报警'
username = '[email protected]'
password = 'xxxx'
msg = MIMEText(strs, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = 'Tim<[email protected]>'
msg['To'] = "[email protected]"
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

python send mail (with attachment)

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

USER = '[email protected]'
PASSWORD = 'xxxxxx'
# 如名字所示: Multipart就是多个部分
msg = MIMEMultipart()
HOST = 'smtp.163.com'
msg['subject'] = 'test email from python'
msg['to'] = '[email protected]'
msg['from'] = '[email protected]'
text = MIMEText('我是纯文本')
msg.attach(text)
#添加附件1
xlsxpart = MIMEApplication(open('test1.xlsx', 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='test1.xlsx')
msg.attach(xlsxpart)
#添加附件2
xlsxpart2 = MIMEApplication(open('test2.xlsx', 'rb').read())
xlsxpart2.add_header('Content-Disposition', 'attachment', filename='test2.xlsx')
msg.attach(xlsxpart2)
#开始发送邮件
client = smtplib.SMTP()
client.connect(HOST)
client.login(USER, PASSWORD)
client.sendmail('[email protected]', ['[email protected]'], msg.as_string())
client.quit()
print('发送成功........')

configparser module

configparser is a package used to read the configuration file. The format of the configuration file is similar: [section] + content (key = value)

Examples:

[db]
db_host = 127.0.0.1
db_port = 69
db_user = root
db_pass = root
host_port = 69

Instructions

Step 1: Import the module and initialize

import configparser
config= configparser.ConfigParser()
config.read('file_path',encoding="utf-8")

Part 2: Common methods

Get all section nodes

print(config.sections())

Get the options of the specified section (ie: key = key in value)

r=config.options('db')
print(r)

Get the value of the specified option in the specified section

r=config.get('db','db_host')
# r1 = config.getint("db", "k1") #将获取到值转换为int型
# r2 = config.getboolean("db", "k2" ) #将获取到值转换为bool型
# r3 = config.getfloat("db", "k3" ) #将获取到值转换为float型
print(r)

Get all configuration information of the specified section

r=config.items('db')
print(r)

Check if the section or option exists

config.has_section("section") #是否存在该section
config.has_option("section", "option")  #是否存在该option

Modify the value of the specified option in the specified section (if the option does not exist, it will be newly created)

config.set('db','db_host','127.0.0.2')
config.write(open('file_path','w')) #如果没有这一步源文件内容不改变

Add section and option

if not config.has_section('addsection')
    config.add_section('addsection')
if not config.has_option('section','addoption')
    config.set('section','addoption','value')
config.write(open('file_path','w'))

Delete section and option

config.remove_section('section') #删除整个section所有内容


paramiko module

paramicko: simulate ssh login to linux host, also have upload and download function

Recommended reading: https://www.cnblogs.com/xiao-apple36/p/9144092.html

The first step: pip download package

pip install paramiko

ssh connect to linux host and run bash command

import paramiko
hostname = '192.168.137.3'
port = 22
username = 'root'
password = '123'
ssh = paramiko.SSHClient()
# 自动添加策略,保存服务器的主机名和密钥信息,如果不添加,那么不再本地know_hosts文件中记录的主机将无法连接
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,port=port,username=username,password=password)
stdin,stdout,stderr = ssh.exec_command("可用命令")
print(stdout.read().decode('utf-8'))

Upload to host via paramiko module

import paramiko
hostname = '192.168.137.3'
port = 22 
username = 'root'
password = '123'
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(r'/root/ping.sh', '/root/ping.sh')  #不同于scp必须为要传输的文件重新赋名
t.close()

Connect to the host to download via paramiko module

import paramiko
hostname =  '192.168.137.3'
port = 22
username = 'root'
password = '123'
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/root/test3.yml', r'C:\Users\51963\Desktop\test3.yml')
t.close()

Upload and download based on public key

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa') 

transport = paramiko.Transport(('192.168.1.21', 22))
transport.connect(username='root', pkey=private_key )
   
sftp = paramiko.SFTPClient.from_transport(transport)
 
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
 
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
   
transport.close()

os module

getcwd () Get the current working path

import os
print(os.getcwd())

...................................
D:\untitled\venv\Include

chdir () changes the current working path

import os
print(os.getcwd())
os.chdir('new')
print(os.getcwd())

.............................
D:\untitled\venv\Include
D:\untitled\venv\Include\new

chdir ('..') returns the working directory of the superior

import os
print(os.getcwd())
os.chdir('new')
print(os.getcwd())
os.chdir('..')
print(os.getcwd())

................................
D:\untitled\venv\Include
D:\untitled\venv\Include\new
D:\untitled\venv\Include

mkdirs (create recursive directories)

import os
os.makedirs('1/2/3')
os.chdir('1/2/3')
print(os.getcwd())

...............................
D:\untitled\venv\Include\1\2\3

mkdir New directory

import os
os.mkdir('1')
os.chdir('1')
print(os.getcwd())

.............................
D:\untitled\venv\Include\1

rmdir deletes a folder where the single-level directory is empty

import os
os.rmdir('1')

listdir List all files and folders under the specified folder, including hidden files, printed out in a list

import os
print(os.listdir('path'))

remove delete the specified file

rename changes the folder or file name

stat View file details

import os
print(os.stat("gouguoqinew/testnew"))

........................................................................

os.stat_result(st_mode=33206, st_ino=15085150720, st_dev=75373296, st_nlink=1, st_uid=0, st_gid=0, st_size=28, st_atime=1528473600, st_mtime=1528552906, st_ctime=1528552713)

st_size=28    文件大小,单位是字节

st_atime=1528473600  用户上一次的访问时间

st_mtime=1528552906  用户上一次修改的时间(常用)

st_ctime=1528552713   用户的创建文件的时间

system runs shell commands and directly displays the results

[root@localhost python]# cat os.system.py

#!/usr/bin/env  python
# _*_ coding:utf8 _*_
import os
os.system("cd /home && ls")
[root@localhost python]# python os.system.py
python 

os.path.exists () judges whether the path exists, exists as True, and does not exist as False
os.path.isfile () judges whether a file exists, exists as True, otherwise False
os.path.isdir () judges a directory Whether it exists, it is True, otherwise it is False

os.path.join Path stitching (important and commonly used)

import os
a="D:\pyproject"
b="day21\gouguoqinew"
print(os.path.join(a,b))

........................................................................

D:\pyproject\day21\gouguoqinew

pymysql module

#pymysql操作数据库
import pymysql
# 打开数据库连接
db = pymysql.connect(host="192.168.254.24", user="root",
                     password="root", db="mysql", port=3306)

# 使用cursor()方法获取操作游标
cur = db.cursor()

# 1.查询操作
# 编写sql 查询语句  user 对应我的表名
sql = "select host,user,password from user"
try:
    cur.execute(sql)  # 执行sql语句
    results = cur.fetchall()  # 获取查询的所有记录
    for i in results:#遍历结果
        print(i)
except Exception as e:
    raise e
finally:
    db.close()  # 关闭连接

Guess you like

Origin www.cnblogs.com/du-z/p/12725641.html