python——常用模块(yagmail模块、configparser模块、paramiko模块、os模块、pymysql模块)

本章内容:

  1. yagmail模块
  2. configparser模块
  3. paramiko模块
  4. os模块
  5. pymysql模块

yagmail模块

python标准库发送电子邮件的模块比较复杂,so,许多开源的库提供了更加易用的接口来发送电子邮件,其中yagmail是使用比较广泛的开源项目,yagmail底层依然使用smtplib和email模块,但是提供了更好的接口,并具有更好的易读性。

第一步:安装yagmail模块

pip install yagmail

第二步:发邮件

#导入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()

拓展1:发送多个用户

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

拓展2:发送附件

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

使用smtplib模块发邮件

python发送邮件(不带附件)

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发送邮件(带附件)

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模块

configparser是用来读取配置文件的包,配置文件的格式类似:[section]+内容(键=值)

示例:

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

使用方法

第一步:导入模块并初始化

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

第二部:常用方法

获取所有section节点

print(config.sections())

获取指定section的options(即:键=值中的键)

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

获取指定section指定option的值

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)

获取指定section的所有配置信息

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

查看section或option是否存在

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

修改指定section指定option的值(如果不存在该option会新创建)

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

添加section和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'))

删除section和option

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


paramiko模块

paramicko:模拟ssh登陆linux主机,也有上传下载功能

推荐阅读:https://www.cnblogs.com/xiao-apple36/p/9144092.html

第一步:pip 下载包

pip install paramiko

ssh 连接linux主机运行bash命令

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

通过paramiko模块连接主机上传

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

通过paramiko模块连接主机下载

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

基于公钥上传下载

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模块

getcwd() 获取当前工作路径

import os
print(os.getcwd())

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

chdir() 改变当前工作路径

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

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

chdir('..') 返回上级工作目录

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(创建递归目录)

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

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

mkdir 新建目录

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

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

rmdir 删除单级目录为空的文件夹

import os
os.rmdir('1')

listdir 列出指定文件夹下面所有文件和文件夹,包括隐藏文件,以列表方式打印出来

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

remove 删除指定文件

rename 修改文件夹或文件名字

stat 查看文件详细信息

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 运行shell命令,直接显示结果

[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() 判断路径是否存在,存在为True,不存在为False
os.path.isfile() 判断一个文件是否存在,存在为True,否则为False
os.path.isdir() 判断一个目录是否存在,存在为True,否则为False

os.path.join 路径拼接(重要常用)

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

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

D:\pyproject\day21\gouguoqinew

pymysql模块

#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()  # 关闭连接

猜你喜欢

转载自www.cnblogs.com/du-z/p/12725641.html
今日推荐