网站首页 > 博客文章 正文
本文总结了运维工作中经常用到的一些实用代码块,方便在需要的时候直接搬过来使用即可
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-01-18 防火墙NAT配置,配置NAT静态转换,配置NAT动态转换PAT及No-PAT模式
- 2025-01-18 四种网路类型外网穿透力与优化方法
- 2025-01-18 通过Python实现内网穿透的几种方式?
- 2025-01-18 小科普 | 联机游戏卡顿?改善你的NAT类型吧
- 2025-01-18 如何用Python实现神经网络(附完整代码)
- 2025-01-18 公司内网用户如何通过NAT地址访问外网,一文读懂!
- 2025-01-18 从联机游戏学习NAT类型
- 2025-01-18 python-网络编程总结
- 2025-01-18 工业路由器网关的网络协议之NAT技术
- 2025-01-18 NAT类型
你 发表评论:
欢迎- 367℃用AI Agent治理微服务的复杂性问题|QCon
- 358℃初次使用IntelliJ IDEA新建Maven项目
- 356℃手把手教程「JavaWeb」优雅的SpringMvc+Mybatis整合之路
- 351℃Maven技术方案最全手册(mavena)
- 348℃安利Touch Bar 专属应用,让闲置的Touch Bar活跃起来!
- 346℃InfoQ 2024 年趋势报告:架构篇(infoq+2024+年趋势报告:架构篇分析)
- 345℃IntelliJ IDEA 2018版本和2022版本创建 Maven 项目对比
- 342℃从头搭建 IntelliJ IDEA 环境(intellij idea建包)
- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)