几个小案例

发送邮件

import yagmail
#第三方模块 pip install yagmail
with open('E:/pwd.txt') as f:
    email_pwd = f.read()[:-1]
subject='主题'
email_content = """内容
****
"""
email_users = ['admin@hapa.cc', 'mail@hapa.cc']
yag = yagmail.SMTP(user='****@126.com',
                   password=email_pwd,
                   host='smtp.126.com',
                   port=465,
                   smtp_ssl=True)
yag.send(email_users,subject,email_content)

钉钉机器人

webhook = 'https://oapi.dingtalk.com/robot/send?access_token=d374ad90d1f293b7d7ac799c3e3a2'
import requests
send_content = "hapa:demo"
content = {
    "msgtype": "text",
    "text": {
        "content": send_content
    },
    "at": {
       "atMobiles": [
           '188*****08'
       ]
    }
#     "at": {
#        # 发送给群里的所有人
#         "isAtAll": True
#     }
}
headers = {"Content-Type": "application/json;charset=utf-8"}
r = requests.post(url=webhook, json=content, headers=headers)
print(r.content.decode())

正则表达式

import re
#match 只匹配整个字符串开头
#search 从开头到结尾匹配到第一个结束
#findall 所有
#sub替换
#split相当于awk -F
s='hapa is a man'
r=re.match('ha\w+',s)
r1=re.search('a\w+',s)
r2=re.findall('a\w+',s)
r3=re.sub('a\w+','!',s)
r4=re.split('a',s)
if r1:
    print(r1.group())
#apa
if r2:
    print(r2)
#['apa', 'an']
print(r3)
#h! is a m!
print(r4)
#['h', 'p', ' is ', ' m', 'n']
r=re.match('ha\w+',s)
r1=re.match('ha(\w+)',s)
print(r.groups(),r1.groups())
#() ('pa',)
r2=re.findall('a\w+',s)
r3=re.findall('a(\w+)',s)
print(r3)
#['pa', 'n']

操作MYSQL

import pymysql

conn=pymysql.connect(
    host='202.53.*.*',
    port=3306,
    user='demo',
    passwd='*******',
    db='test'
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
keys = base_info.keys()
values = base_info.values()
sql = sql.format(*keys)
cursor.execute(sql, tuple(values))
conn.commit()
cursor.close()
'''
query_sql = "select id, host_name, os from base_info;"
row_nums = cursor.execute(query_sql)
print(row_nums)
print(cursor.fetchone())
print("*" * 20)
print(cursor.fetchmany(2))
#取出2条记录,返回二维元组。
print("*" * 20)
print(cursor.fetchall())
cursor.close()
conn.close()
'''

会话保持

import random, string, hashlib
import redis
rs = redis.StrictRedis(host="192.168.188.8",
                       port=6379,
                       db=0,
                       decode_responses=True,
                       password="123"
                       )

def generate_sessid():
    """生产随机字符串
    Return: 返回 session id
    """
    
    # 获取基本的字符串0-9 a-z A-Z
    base_str = f"{string.digits + string.ascii_letters}"
    # 拼接
    sessid = ''.join(random.sample(base_str, 20))
    return sessid

def hash_pwd(pwd):
    """传入一串字符,进行 MD5 计算
    Keyword arguments:
    pwd -- 字符串
    Return: md5 加密值
    """
    
    password = hashlib.md5(pwd.encode('utf-8'))
    return password.hexdigest()

def save_session(name, sessid='', ex=7200):
    """保存会话信息,并存入缓存
    Keyword arguments:
    name -- 用户名
    pwd -- 加密过的密码
    sessid -- 会话 id
    Return:
    """
    rs.hset(name, "sessid", sessid)
    # 保存会话有效时间
    rs.setex(f"{name}_{sessid}", ex, sessid)


def check_session(name, sessid):
    if rs.ttl(f"{name}_{sessid}") in (-2, 0):
        return False
    else:
        return True

def login():
    """
    用户登录,验证,验证成功返回用户名
    :return 用户名和 会话 ID
    """
    sessid=''
    while True:
        inp = input("输入用户名和密码,中间用空格隔开,比如: shark 123\n>>:").strip()
        user_pwd = inp.split()
        if len(user_pwd) == 2:
            name, source_pwd = user_pwd
        else:
            print("格式错误,请重新输入")
            continue
        pwd = hash_pwd(source_pwd)
        user = rs.hget(name, "name")
        redis_pwd = rs.hget(name, "pwd")
        redis_sessid=rs.hget(name,'sessid')
        if name == user and pwd == redis_pwd:
            if redis_sessid != '(nil)':
                ex=check_session(name, redis_sessid)
                if ex:
                    print('会话未过期')
                else:
                    save_session(name,sessid=redis_sessid,ex=100)
                    print('请重新登陆')
            else:
                generate_sessid()
                save_session(name,sessid,ex=100)
                print('欢迎首次登陆')
        else:
            print("用户名密码错误, 请重新输入")
            continue

if __name__ == "__main__":
    login()

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇