章工运维 章工运维
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)

章工运维

业精于勤,荒于嬉
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)
  • python

    • python基础

      • python基础知识
      • python基础较难的15个知识点
    • FastAPI

    • python每日练习脚本

    • python3给防火墙添加放行
    • python生成部署脚本
    • python将多个文件内容输出到一个文件中
    • 使用 Aligo 定时备份服务器文件
    • python监控日志文件并发送钉钉告警
    • python监控数据库脚本并发送钉钉告警
    • 使用python编写自动化发布脚本
    • 查询redis列表某个元素
    • centos7安装python3
    • python环境管理工具介绍
    • conda安装和镜像源配置
    • pip更换国内源
    • python爬虫
    • python环境启动服务报错缺少glibc库版本
    • 监控目录或文件变化
    • 批量更改文件
    • python引用数据库
      • python引用数据库两种方式
        • 方式一
        • 方式二
  • shell

  • go

  • 编程
  • python
章工运维
2022-12-13
目录

python引用数据库

# python引用数据库两种方式

# 方式一

# -*- coding: UTF-8 -*-
import pymysql
import requests
import json
#建立连接
conn = pymysql.connect(host='##', port=3306, database='##', user='##', password='####')
#拿到游标
cursor = conn.cursor()
#执行sql语句
sql = "SELECT * FROM bh_job_exec WHERE job_cde='company' AND exec_status='SUCCESS' AND JSON_UNQUOTE(JSON_EXTRACT(exec_param, '$.businessDate')) = DATE_SUB(CURDATE(),INTERVAL 1 DAY);"
# print(sql)
def sendDing(msg):
    dingding_url='https://oapi.dingtalk.com/robot/send?access_token=xxxxx'
    data = {"msgtype": "text","text": {"content": "告警:"+str(msg)}}
    headers = {'Content-Type':'application/json;charset=UTF-8'}
    send_data = json.dumps(data).encode('utf-8')
    ret = requests.post(url=dingding_url,data=send_data,headers=headers)


try:
    row = cursor.execute(sql)
    # print(row)
    # Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
    data=cursor.fetchone()
    #print(data)
    #进行判断
    if data:
        #print("GFSS结算成功")
        sendDing("GFSS结算成功")
    else:
        #print("GFSS结算失败")
        sendDing("GFSS结算失败")
except:
    print("Error: unable to fetch data")
finally:
    cursor.close()
    #关闭数据库
    conn.close()


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# 方式二

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pymysql
import pickle
import os.path,sys
import urllib.request
import urllib.parse
import json
ding_url = "https://oapi.dingtalk.com/robot/send?access_token=xxxx" 
def get_tabcol_current():
    tabcol_dic = {}
    ## 目标库的信息
    db = pymysql.connect(host='xxx',
                         port=13306,
                         user='xx',
                         password='xx',
                         database='xxx')
    cursor = db.cursor()
 
    sql = "SELECT * FROM `terminal_session` WHERE date_end is Null"
 
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
      if row[1] in tabcol_dic:
          tabcol_dic[row[1]].append(row[2])
      else:
          tabcol_dic[row[1]]=[row[2]]
    cursor.close()
    db.close()
    # print(tabcol_dic) 
    return tabcol_dic
    
def send_msg_by_ding(message):
    header = {
        "Content-Type": "application/json"
    }
    data = {
        "msgtype": "text", 
        "text": {"content": message}
    }
    send_data = json.dumps(data).encode('utf-8')
    req = urllib.request.Request(ding_url, data=send_data, headers=header, method='POST')
    ret = urllib.request.urlopen(req)
    if ret.status != 200:
        print("send message error!")
def main():    
    ret = get_tabcol_current()
    # print(ret)
    add_dic = ret
    # add_dic = list(ret.values())
    # del_dic = list(ret.keys())
    message = "堡垒机告警:\n"
    if add_dic:
        for (tab,cols) in add_dic.items():
            cols.sort()
            message = message + tab + " 登录了: " + ', '.join(cols) + "\n"
    if add_dic:
        send_msg_by_ding(message)
    # print(del_dic)
    # print(1111)
if __name__ == '__main__':
    main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
微信 支付宝
上次更新: 2024/12/04, 17:15:49

← 批量更改文件 进程pid判断脚本→

最近更新
01
shell脚本模块集合
05-13
02
生活小技巧(认知版)
04-29
03
生活小技巧(防骗版)
04-29
更多文章>
Theme by Vdoing | Copyright © 2019-2025 | 点击查看十年之约 | 鄂ICP备2024072800号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式