Python运维常用的脚本,提高工作效率就靠它了
前言
用Python做运维的小伙伴肯定会进行重复的工作,这个时候脚本的重要性就体现出来了
一个好的脚本工具可以帮你省去很多重复的工作,创造更大的价值
下面小编就带你们看看Python运维最常用的脚本吧
清除指定redis缓存
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-20 15:19 # @Author : opsonly # @Site : # @File : redisdel.py # @Software: PyCharmimport redis#选择连接的数据库 db = input('输入数据库:') r = redis.Redis(host='127.0.0.1',port=6379,db=0)#输入要匹配的键名 id = input('请输入要执匹配的字段:') arg = '*' + id + '*'n = r.keys(arg) #查看匹配到键值 for i in n:print(i.decode('utf-8'))#确定清除的键名 delid = input('输入要删除的键:')print('清除缓存 %s 成功' % delid)
判断是否是一个目录
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-18 15:16 # @Author : opsonly # @Site : # @File : opsUse.py # @Software: PyCharm import osdir = "/var/www/html/EnjoyCarApi/" if os.path.isdir(dir):print('%s is a dir' % dir) else:print('%s is not a dir' % dir)
统计nginx日志前十ip访问量并以柱状图显示
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-18 15:49 # @Author : opsonly # @Site : # @File : nginx_ip.py # @Software: PyCharmimport matplotlib.pyplot as plt # nginx_file = 'nginx2018-12-18_07:45:26'ip = {} # 筛选nginx日志文件中的ip with open(nginx_file) as f:for i in f.readlines():s = i.strip().split()[0]lengh = len(ip.keys())# 统计每个ip的访问量以字典存储if s in ip.keys():ip[s] = ip[s] + 1else:ip[s] = 1#以ip出现的次数排序返回对象为list ip = sorted(ip.items(), key=lambda e:e[1], reverse=True)#取列表前十 newip = ip[0:10:1] tu = dict(newip)x = [] y = [] for k in tu:x.append(k)y.append(tu[k]) plt.title('ip access') plt.xlabel('ip address') plt.ylabel('PV')#x轴项的翻转角度 plt.xticks(rotation=70)#显示每个柱状图的值 for a,b in zip(x,y):plt.text(a, b, '%.0f' % b, ha='center', va= 'bottom',fontsize=7)plt.bar(x,y) plt.legend() plt.show()
查看网段里有多少ip地址
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-18 15:31 # @Author : opsonly # @Site : # @File : ipTest.py # @Software: PyCharm import IPyip = IPy.IP('172.16.0.0/26')print(ip.len()) for i in ip:print(i)
gitlab钩子脚本,实现简单自动化操作
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-18 17:41 # @Author : opsonly # @Site : # @File : gitlabCi.py # @Software: PyCharmfrom flask import Flask,request,render_template,make_response,Response import json,os,re,requests import subprocessapp = Flask(__name__) null = "" cmd = "/var/www/html/ladmin-devel/" @app.route('/test',methods=['POST']) def hello():json_dict = json.loads(request.data)name = json_dict['event_name']ref = json_dict['ref'][11:]project = json_dict['project']['name']if name == 'push' and ref == 'master':os.chdir(cmd)s = subprocess.getoutput('sudo -u nginx composer install')return Response(s)else:return Response('none')if __name__ == '__main__':app.run(host='0.0.0.0',port=8080)
系统内存与磁盘检测
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-17 17:16 # @Author : opsonly # @Site : # @File : systemissue.py # @Software: PyCharmimport psutildef memissue():print('内存信息:')mem = psutil.virtual_memory()# 单位换算为MBmemtotal = mem.total/1024/1024memused = mem.used/1024/1024membaifen = str(mem.used/mem.total*100) + '%'print('%.2fMB' % memused)print('%.2fMB' % memtotal)print(membaifen)def cuplist():print('磁盘信息:')disk = psutil.disk_partitions()diskuse = psutil.disk_usage('/')#单位换算为GBdiskused = diskuse.used / 1024 / 1024 / 1024disktotal = diskuse.total / 1024 / 1024 / 1024diskbaifen = diskused / disktotal * 100print('%.2fGB' % diskused)print('%.2fGB' % disktotal)print('%.2f' % diskbaifen)memissue() print('*******************') cuplist()
解析一组域名的ip地址
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-20 10:21 # @Author : opsonly # @Site : # @File : dnsReloves.py # @Software: PyCharmimport dns.resolver from collections import defaultdict hosts = ['baidu.com','weibo.com'] s = defaultdict(list) def query(hosts):for host in hosts:ip = dns.resolver.query(host,"A")for i in ip:s[host].append(i)return sfor i in query(hosts):print(i,s[i])
下载阿里云RDS二进制日志
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018-12-12 13:52 # @Author : opsonly # @Site : # @File : rds_binlog.py # @Software: PyCharm''' 查询阿里云rds binlog日志 '''import base64,urllib.request import hashlib import hmac import uuid,time,json,wgetclass RDS_BINLOG_RELATE(object):def __init__(self):#阿里云的id和keyself.access_id = '**********************'self.access_key = '**********************'#通过id和key来进行签名def signed(self):timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())header = {'Action': 'DescribeBinlogFiles','DBInstanceId': 'rm-wz9azm783q621n9','StartTime': '2018-07-11T15:00:00Z','EndTime': timestamp,'Format': 'JSON','Version': '2014-08-15','AccessKeyId': self.access_id,'SignatureVersion': '1.0','SignatureMethod': 'HMAC-SHA1','SignatureNonce': str(uuid.uuid1()),'TimeStamp': timestamp,}#对请求头进行排序sortedD = sorted(header.items(), key=lambda x: x[0])url = 'https://rds.aliyuncs.com'canstring = ''#将请求参数以#连接for k, v in sortedD:canstring += '&' + self.percentEncode(k) + '=' + self.percentEncode(v)#对请求连接进行阿里云要的编码规则进行编码stiingToSign = 'GET&%2F&' + self.percentEncode(canstring[1:])bs = self.access_key + '&'bs = bytes(bs, encoding='utf8')stiingToSign = bytes(stiingToSign, encoding='utf8')h = hmac.new(bs, stiingToSign, hashlib.sha1)stiingToSign = base64.b64encode(h.digest()).strip()#将签名加入到请求头header['Signature'] = stiingToSign#返回urlurl = url + "/?" + urllib.parse.urlencode(header)return url#按照规则替换def percentEncode(self,store):encodeStr = storeres = urllib.request.quote(encodeStr)res = res.replace('+', '%20')res = res.replace('*', '%2A')res = res.replace('%7E', '~')return str(res)#筛选出链接下载二进制日志文件def getBinLog(self):binlog_url = self.signed()req = urllib.request.urlopen(binlog_url)req = req.read().decode('utf8')res = json.loads(req)for i in res['Items']['BinLogFile']:wget.download(i['DownloadLink'])s = RDS_BINLOG_RELATE() s.getBinLog()
喜欢小编的文章的小伙伴欢迎关注小编哦~
文章持续更新
Python运维常用的脚本,提高工作效率就靠它了相关推荐
- python运维常用模块-运维常用python库模块
sutil: 是一个跨平台库(https://github.com/giampaolo/psutil)能够实现获取系统运行的进程和系统利用率(内存,CPU,磁盘,网络等),主要用于系统监控,分析和系统 ...
- linux运维脚本编写,Linux运维常用shell脚本实例 (转)
1.用shell脚本批量建立Linux用户 实现要求:创建用户student1到student50,指定组为student组!而且每个用户需要设定一个不同的密码! #!/bin/bash for i ...
- TRACE32使用小技巧—使用脚本提高工作效率
之前使用TRACE32一直是通过手动设置芯片及其他相关设置,其实TRACE32有很强大的脚本语言,几乎所有的功能都可以通过编写脚本的方式来进行,可以大大提高效率.以下脚本通过原来将原来需要点击10次左 ...
- 【Python】分享几个简单易懂的Python技巧,能够极大的提高工作效率哦!
今天和大家来分享几个关于Python的小技巧,都是非常简单易懂的内容,希望大家看了之后能够有所收获. 01 将字符串倒转 my_string = "ABCDE" reversed_ ...
- python运维模块_Python 运维常用模块
基础库:sys.os(os.path.os.stat).time.logging.prarmiko.re.random Python运维常用的20个库 1.psutil是一个跨平台库(https:// ...
- linux运维自动化脚本,linux运维自动化shell脚本小工具
linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU # ...
- python运维脚本面试_运维开发工程师 面试题 shell编程
1. 32位随机密码生成 cat /proc/sys/kernel/random/uuid | tr -d '-' 2.查看当前系统每个ip的tcp连接数 -n 强制显示IP地址 -t 显示TCP连接 ...
- oracle 运营维护_Oracle数据库日常运维常用脚本
大 中 小 Oracle数据库日常运维常用脚本 1 查看所有数据文件 select file_name from dba_data_files union select file_name from ...
- python程序员需要掌握哪些技术-python运维要掌握哪些内容
python运维需要会什么 随着移动互联网的普及,服务器运维所面临的挑战也随之越来越大.当规模增长到一定程度,手动管理方式已经无法应对,自动化运维成为解决问题的银弹. Python凭借其灵活性,在自动 ...
最新文章
- 吴恩达老师深度学习视频课笔记:人脸识别
- 【iOS工具】rvm、Ruby环境和CocoaPods安装使用及相关报错问题解决(2016 12 15 更新)...
- 从“几何深度学习”看深度学习江湖的统一
- 在linux上面合并多个windows文件乱码的问题
- Vue是如何渲染页面的,渲染过程以及原理代码
- CRSLab:可能是最适合你的对话推荐系统开源库
- boost::mp11::mp_bind_back相关用法的测试程序
- Linux内核路由表介绍及相关函数
- 《MySQL——锁》
- spring加载application.xml异常
- 为什么找不到使用rem的网站
- 采集的时候,列表的编码是gb2312,内容页的编码却是UTF-8,这种网站怎么采集?
- MFC异形窗口-多边形窗口-根据图片自定义窗口形状-CRgn
- 计算机操作系统|汤小丹|第四版|习题答案(五)
- 工作表冻结前两行_冻结所有工作表宏
- 推荐一款免费的万能电子书格式转换工具电子书转换器NeatConverter
- linux怎样编写脚本文档,Linux下批处理文件编写
- 软件开发的流程是怎样的?
- 王选: 从Dijkstra谈帅才的洞察力
- 史上最难oracle数据库练习题(附答案)