网站首页 > 技术文章 正文
本文总结了运维工作中经常用到的一些实用代码块,方便在需要的时候直接搬过来使用即可
1.执行系统命令,获取返回结果
from subprocess import Popen, PIPE, STDOUT
cp = Popen('dir', stdout=PIPE, stderr=STDOUT, shell=True)
info=str(cp.stdout.readline().decode())
print(info)
2.时间处理及格式转换
#当前时间格式化
import datetime,time
data=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(data) #2020-02-05 10:22:17
#格式化转timeStamp
data=time.mktime(time.strptime('2020-07-09T14:49:51Z', "%Y-%m-%dT%H:%M:%SZ"))
print(data) #1594277391.0
#timeStamp转格式化
import datetime
data=datetime.datetime.fromtimestamp(1551576293.0).strftime("%Y-%m-%d %H:%M:%S")
print(data) #2019-03-03 09:24:53
#时间差
import time
data = int(time.time())-int(time.mktime(time.strptime('2020-07-09T14:49:51Z', "%Y-%m-%dT%H:%M:%SZ")))
print(data) #345s
#格式化时间加减
data=datetime.datetime.fromtimestamp(time.mktime(time.strptime('2013-10-10 23:40:00', "%Y-%m-%d %H:%M:%S"))+8*3600).strftime("%Y-%m-%d %H:%M:%S")
print(data) #2013-10-11 07:40:00
3.钉钉发送消息
为什么写这段呢,主要是使用python自带的urllib包,而不是使用requests,本着能使用自带的,就不使用其他的原则,写了这段代码
##############python3############################
from urllib import request
import os,json
def DingDing(msg):
url='https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxx'
data = {"msgtype": "text", "text": {"content": "%s\n脚本路径:%s" % (msg,os.path.realpath(__file__))}, "at": {"atMobiles": ["xxxxxxxx"], "isAtAll": False}}
req = request.Request(url=url,data=json.dumps(data).encode("utf-8"),headers={'Content-Type': 'application/json'},method='POST')
response = request.urlopen(req)
return response.read().decode()
##############python2############################
import urllib2,json
def DingDing(msg):
url='https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
data = {"msgtype": "text", "text": {"content": msg}, "at": {"atMobiles": ["xxxxxxxxxxxxxxx"], "isAtAll": False}}
request = urllib2.Request(url=url,headers={'Content-Type':'application/json'},data=json.dumps(data))
response = urllib2.urlopen(request)
return response.read()
4.日志配置
####日志自动切割
import time,sys,os,logging
from logging.handlers import RotatingFileHandler
log_obj = logging.getLogger()
fileHandle = logging.handlers.TimedRotatingFileHandler(os.path.join(sys.path[0], 'cron_ops.log'),when='d',interval=1,backupCount=10)
fileHandle.setFormatter(logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'))
log_obj.addHandler(fileHandle)
log_obj.info("日志内容")
####日志打印到控制台
import time,sys,logging
console_log = logging.getLogger()
console_log.setLevel(logging.INFO)
streamHandle = logging.StreamHandler()
streamHandle.setFormatter(logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'))
console_log.addHandler(streamHandle)
console_log.info("日志打印")
5.加解密代码
本代码也支持中文加解密,使用前需要先安装pycryptodome包
#pip3 install pycryptodome #https://pypi.tuna.tsinghua.edu.cn/simple/cryptography/
from Crypto.Cipher import DES3
import base64
class EncryptData:
def __init__(self):
self.key = "5YIGo8frLeqUAewDo2AVkNKU"
self.iv = b'xluhjoLD'
self.length = DES3.block_size
self.unpad = lambda date: date[0:-ord(date[-1])]
def pad(self, text):
count = len(text.encode('utf-8'))
add = self.length - (count % self.length)
entext = text + (chr(add) * add)
return entext
def encrypt(self, encrData):
self.des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv)
res = self.des3.encrypt(self.pad(encrData).encode("utf8"))
msg = str(base64.b64encode(res), encoding="utf8")
return msg
def decrypt(self, decrData):
self.des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv)
res = base64.decodebytes(decrData.encode("utf8"))
msg = self.des3.decrypt(res).decode("utf8")
return self.unpad(msg)
eg = EncryptData()
res = eg.encrypt("13918密钥的长度必须是16238353")
print(res) ####YtO3hoYxnohOtWgH2UrYh1nDZ58+QmksVbWLVDBJVg4kfaQWASCzAw==
print(eg.decrypt(res)) ####13918密钥的长度必须是16238353
6.字典key转对象
class selfAttrDict(dict):
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __getattr__(self, item):
return self.__getitem__(item)
def __delattr__(self, item):
self.__delitem__(item)
dicrs={"name":"dfddfdffd"}
ss=selfAttrDict(dicrs)
print(ss.name) ####dfddfdffd
猜你喜欢
- 2025-04-08 分享一份mysql一键优化脚本,值得收藏
- 2025-04-08 基于Python+MySql+Flask+Vue的电脑运维管理系统
- 2025-04-08 python常见的网络编程模式: Client/Server编程模式
- 2025-04-08 Python 生成器里面的 return 有什么用?
- 2025-04-08 Python-一些基本概念(python的意义和作用)
- 2025-04-08 使用 Python Flask 创建简易文件上传服务
- 2025-04-08 Python 爬虫入门五之 Cookie 的使用
- 2025-04-08 监控运维大屏展示,炫酷界面,尽在Grafana中
- 2025-04-08 python网络运维,批量修改交换机配置
- 2025-04-08 Python运维日志排序(python日志处理)
- 264℃Python短文,Python中的嵌套条件语句(六)
- 263℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 256℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 256℃Python实现字符串小写转大写并写入文件
- 116℃原来2025是完美的平方年,一起探索六种平方的算吧
- 96℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 89℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)