文章目录
邮件和JSON
邮件编程
SMTP概述
SMTP对象
设置邮件
sendmail方法
本地发邮件示例
from email.mime.text import MIMEText
from email.header import Header
import smtplib
# 准备邮件
# plain表示纯文本,相对于富文本
msg = MIMEText('python 邮件测试\n', 'plain', 'utf8')
# 添加头部消息
msg['From'] = Header('root', 'utf8') # 发件人
msg['To'] = Header('tom', 'utf8') # 收件人
msg['Subject'] = Header('py test', 'utf8') # 主题
# 发送邮件
smtp = smtplib.SMTP('localhost') # 使用本机发送邮件
smtp.sendmail('root', ['tom', 'jerry'], msg.as_bytes())
SMTP认证
- 互联网发邮件示例
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import getpass
def send_email(body, sender, receivers, subject, server, passwd):
# 准备邮件
msg = MIMEText(body, 'plain', 'utf8')
# 添加头部消息
msg['From'] = Header(sender, 'utf8') # 发件人
msg['To'] = Header(receivers[0], 'utf8') # 收件人
msg['Subject'] = Header(subject, 'utf8') # 主题
# 发送邮件
smtp = smtplib.SMTP()
smtp.connect(server)
# smtp.starttls() # 如果服务器要求安全连接,则打开此注释
smtp.login(sender, passwd)
smtp.sendmail(sender, receivers, msg.as_bytes())
if __name__ == '__main__':
body = 'python发送邮件测试。\n'
sender = '********@qq.com'
receivers = ['********@qq.com', '**********@126.com']
subject = 'py mail'
server = 'smtp.qq.com'
passwd = getpass.getpass()
send_email(body, sender, receivers, subject, server, passwd)
JSON
JSON概述
- JavaScript Object Notation
- json应用
>>> import json
>>> data = {'name': 'tom', 'age': 20}
# 发送之前,需要将数据转换成json字符串
>>> jdata = json.dumps(data)
>>> type(jdata)
<class 'str'>
>>> jdata
'{"name": "tom", "age": 20}'
# 接收到的数据,再通过loads转换成对应的数据类型
>>> jdata
'{"name": "tom", "age": 20}'
>>> info = json.loads(jdata)
>>> type(info)
<class 'dict'>
>>> info
{'name': 'tom', 'age': 20}
JSON结构
dumps方法
loads方法
requests模块
requests基础
requests简介
requests特性
GET和POST
其他方法
请求参数
设定头部
发送请求数据
rquests应用示例
- api:应用程序接口
- 中国天气网提供的接口
- 实况天气:http://www.weather.com.cn/data/sk/城市代码.html
- 城市信息:http://www.weather.com.cn/data/cityinfo/城市代码.html
- 详细指数:http://www.weather.com.cn/data/zs/城市代码.html
- 城市代码通过网络搜索
# 安装
[root@localhost day02]# pip3 install requests
>>> import requests
# 文本形式的内容,使用text属性获取
>>> url1 = 'http://www.163.com'
>>> r1 = requests.get(url1)
>>> r1.text
# 非文本数据,使用content属性获取,bytes类型。文本数据也可以使用此种方式。
>>> url2 = 'http://world.people.com.cn/NMediaFile/2020/0217/MAIN202002171833000079364831028.JPG'
>>> r2 = requests.get(url2)
>>> r2.content
>>> with open('/tmp/a.jpg', 'wb') as fobj:
... fobj.write(r2.content)
# json数据,通过json()方法获取
>>> url3 = 'http://www.weather.com.cn/data/sk/101010100.html'
>>> r3 = requests.get(url3)
>>> r3.json() # 乱码,因为编码问题
{'weatherinfo': {'city': 'å\x8c\x97京', 'cityid': '101010100', 'temp': '27.9', 'WD': 'å\x8d\x97é£\x8e', 'WS': 'å°\x8fäº\x8e3级', 'SD': '28%', 'AP': '1002hPa', 'njd': 'æ\x9a\x82æ\x97\xa0å®\x9eå\x86µ', 'WSE': '<3', 'time': '17:55', 'sm': '2.1', 'isRadar': '1', 'Radar': 'JC_RADAR_AZ9010_JB'}}
>>> r3.encoding # 查看当前编码
'ISO-8859-1'
>>> r3.encoding = 'utf8' # 修改编码
>>> r3.json()
{'weatherinfo': {'city': '北京', 'cityid': '101010100', 'temp': '27.9', 'WD': '>南风', 'WS': '小于3级', 'SD': '28%', 'AP': '1002hPa', 'njd': '暂无实况', 'WSE': '<3', 'time': '17:55', 'sm': '2.1', 'isRadar': '1', 'Radar': 'JC_RADAR_AZ9010_JB'}}
- 传参
>>> kd_url = 'http://www.kuaidi99.com/query'
>>> params = {'type': 'youzhengguonei', 'postid': '9893442769997'}
>>> r = requests.get(kd_url, params=params)
>>> r.json()
- 修改请求头
>>> js_url = 'http://www.jianshu.com'
>>> r = requests.get(js_url)
>>> r.text # 403 forbidden
>>> headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}
>>> r = requests.get(js_url, headers=headers)
>>> r.text # 正常内容
天气查询
编写一个display_weather.py脚本,实现以下功能:
运行程序时,屏幕将出现你所在城市各区县名字
用户指定查询某区县,屏幕上将出现该区县当前的气温、湿度、风向、风速等
#!/usr/bin/python #这里是python的目录
from urllib.request import urlopen
import json
#打开网页,使用urllib模块的urlopen函数打开url,赋值给html
html = urlopen('http://www.weather.com.cn/data/sk/101010100.html')
#读html获取的数据,保存到data
data = html.read()
#从data中获取我们想要的信息,json.loads()是将json格式数据转换为字典
#(可以理解为json.loads()函数是将字符串转化为字典)
print(json.loads(data))
#关闭html
html.close()
执行脚本结果如下:
[root@ localhost day12]# python3 weather.py
{‘weatherinfo’:{‘city’:‘北京’,‘cityid’:‘101010100’,‘temp’:‘27.9’,‘WD’:‘南风’,‘WS’:‘小于3级’,‘SD’:‘28%’,‘AP’:‘1002hPa’,‘njd’:‘暂无实况’,‘WSE’:‘<3’,‘time’:‘17:55’,‘sm’:‘2.1’,‘isRadar’:‘1’,‘Radar’:‘JC_RADAR_AZ9010_JB’}}
从以上脚本执行结果中我们可以看到,从网站中获取到的数据是以字典形式显示,显示信息有城市、城市id,温度、风向等等,根据这种规律,编写下面代码
- 编写代码实现如下功能:
1.定义一个字典,该字典中键‘0’和‘1’对应的值为天气网址中城市对应的id,城市不同id则不同
2.运行程序时,屏幕将出现你所在城市名字
3.当用户指定查询某城市(即输入0或1时)
4.调用get_weather函数,函数的实际参数为city_codes字典对应值(即对应的城市id)
5. 打开天气网页,使用urllib模块的urlopen函数打开url,赋值给html
6.读html获取的数据,用json.loads()获取天气信息,获取到的信息为字典形式
7.从获取到的字典数据中提取气温、湿度、风向、风速等信息,保存在output变量中
8.将output变量作为get_weather函数的返回值,打印在屏幕上
#!/usr/bin/python
from urllib.request import urlopen
import json
def get_weather(city_code): #定义一个输入城市id的函数
5.打开天气网页,使用urllib模块的urlopen函数打开url,赋值给html
url = 'http://www.weather.com.cn/data/sk/%s.html' % city_code
html = urlopen(url)
6.读html获取的数据,用json.loads()获取我们想要的信息
#json.loads()是将json格式数据转换为字典
#(可以理解为json.loads()函数是将字符串转化为字典)
data = json.loads(html.read())
7.output为返回值,即最终屏幕显示的信息
output = '风向:%s, 风力: %s, 温度:%s, 湿度:%s' % (
#data获取到的天气信息为字典,该字典中weatherinfo键对应的值还是一个字典,这个字典中‘WD’键对应的值是风向,‘WS’键对应的值是风力,'temp'键对应的值是温度,'SD'键对应的值是湿度,利用键值对关系将相应数据显示出来即可
data['weatherinfo']['WD'],
data['weatherinfo']['WS'],
data['weatherinfo']['temp'],
data['weatherinfo']['SD']
)
return output
if __name__ == '__main__':
1.定义字典:键对应的值为天气网站网址接口中城市ID
city_codes = { '0': '101010100', '1': '101121404'}
2.代码执行后,屏幕给出的提示信息
prompt = """(0) 北京
(1) 台儿庄
请选择(0/1): """
3.根据提示信息,输入0或1
choice = input(prompt)
4.调用get_weather函数,其实际参数为city_codes字典对应值
8.打印调用get_weather函数返回值
print(get_weather(city_codes[choice]))
测试脚本执行
[root@ localhost day12]# python3 display_weather.py
(0) 北京
(1) 台儿庄
请选择(0/1): 0
风向:南风, 风力: 小于3级, 温度:27.9, 湿度:28%
[root@ localhost day12]# python3 display_weather.py
(0) 北京
(1) 台儿庄
请选择(0/1): 1
风向:东北风, 风力: 小于3级, 温度:22.3, 湿度:64%
钉钉机器人示例
在群里创建机器人并设置,可以通过钉钉网页版,网址为:https://im.dingtalk.com/
通过钉钉软件创建一个群聊机器人,要求:
编写代码,通过python脚本实现钉钉机器人在群中发送消息
使用json和requests模块
import requests
import json
import getpass
url = getpass.getpass()
headers = {'Content-Type': 'application/json;charset=utf-8'}
# data = {
# "msgtype": "text",
# "text": {
# "content": "宅家学习。我就是我, 是不一样的烟火@156xxxx8827"
# },
# "at": {
# "atMobiles": [], # @哪些人
# "isAtAll": False # 是否@所有人
# }
# }
# data = {
# "msgtype": "link",
# "link": {
# "text": """宅家学习。这个即将发布的新版本,创始人xx称它为“红树林”。
# 而在此之前,每当面临重大升级,产品经理们都会取一个应景的代号,这一次,为什么是
#“红树林”?""",
# "title": "时代的火车向前开",
# "picUrl": "http://world.people.com.cn/NMediaFile/2020/0217/MAIN202002171833000070170686703.JPG",
# "messageUrl": "http://www.sogou.com"
# }
# }
data = {
"msgtype": "markdown",
"markdown": {
"title":"杭州天气",
"text": "#### 杭州天气 @156xxxx8827\n" +
"> 9度,西北风1级,空气良89,相对温度73% 宅家学习\n\n" +
"> ![screenshot](http://world.people.com.cn/NMediaFile/2020/0217/MAIN202002171833000070170686703.JPG)\n" +
"> ###### 10点20分发布 [天气](http://fanyi.sogou.com/) \n"
},
"at": {
"atMobiles": [
"156xxxx8827",
"189xxxx8325"
],
"isAtAll": False
}
}
r = requests.post(url, headers=headers, data=json.dumps(data))
print(r.json())
zabbix编程
zabbix api简介
zabbix api 概述
zabbix 3.4的官网文档
https://www.zabbix.com/documentation/3.4/zh/manual
JSON-RPC
API结构
执行请求
详细会在下载示例
使用API
方法参考
工作流程
获取领牌
领牌响应信息
检索主机
获取主机组
创建主机
zabbix示例
import requests
import json
url = 'http://192.168.113.133/zabbix/api_jsonrpc.php'
headers = {'Content-Type': 'application/json-rpc'}
#####################################
# 获取zabbix版本
# data = {
# "jsonrpc": "2.0", # jsonrpc版本
# "method": "apiinfo.version", # 使用的方法
# "params": [], # 参数
# "id": 1 # 随便给定一个数字,表示作业号
# }
#####################################
# 获取其他隐私数据,需要认证。认证时采用令牌的形式
# 1e3972f1bf319cf35ea4bd8cc22f043b
# data = {
# "jsonrpc": "2.0",
# "method": "user.login",
# "params": {
# "user": "Admin",
# "password": "zabbix"
# },
# "id": 1
# }
#####################################
# 获取所有监控的主机
# data = {
# "jsonrpc": "2.0",
# "method": "host.get",
# "params": {
# "output": "extend",
# "filter": {
# "host": [
# # "Zabbix server",
# # "Linux server"
# ]
# }
# },
# "auth": "1e3972f1bf319cf35ea4bd8cc22f043b",
# "id": 1
# }
#####################################
# 获取Linux servers组id -> 2
# data = {
# "jsonrpc": "2.0",
# "method": "hostgroup.get",
# "params": {
# "output": "extend",
# "filter": {
# "name": [
# # "Zabbix servers",
# "Linux servers"
# ]
# }
# },
# "auth": "1e3972f1bf319cf35ea4bd8cc22f043b",
# "id": 1
# }
#####################################
# 获取Template OS Linux模板id -> 10001
# data = {
# "jsonrpc": "2.0",
# "method": "template.get",
# "params": {
# "output": "extend",
# "filter": {
# "host": [
# "Template OS Linux",
# # "Template OS Windows"
# ]
# }
# },
# "auth": "1e3972f1bf319cf35ea4bd8cc22f043b",
# "id": 1
# }
#####################################
# 创建一台监控主机名为nsd1909web1,它在Linux servers组中,应用Template OS Linux模板
data = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "nsd1909web1",
"interfaces": [ # 使用哪种方法进行监控
{
"type": 1,
"main": 1,
"useip": 1,
"ip": "192.168.113.1",
"dns": "",
"port": "10050"
}
],
"groups": [
{
"groupid": "2"
}
],
"templates": [
{
"templateid": "10001"
}
],
"inventory_mode": 0,
"inventory": {
"macaddress_a": "01234asdfasdf",
"macaddress_b": "56768234aljfieri23jlf"
}
},
"auth": "1e3972f1bf319cf35ea4bd8cc22f043b",
"id": 1
}
#####################################
r = requests.post(url, headers=headers, data=json.dumps(data))
print(r.json()) # 返回的数据只关心result内容