Python运维常用的脚本,提高工作效率就靠它了

Python运维常用的脚本,提高工作效率就靠它了前言用Python做运维的小伙伴肯定会进行重复的工作,这个时候脚本的重要性就体现出来了一个好的脚本工具可以帮你省去很多重复的工作,创造更大的价值下面小编就带你们看看Python运维最常用的脚本吧清除指定redis缓存#!/usr/bin/envpython3#-*-coding:utf-8-*-#@Time:2018-12-2015:19…

大家好,又见面了,我是你们的朋友全栈君。

Python运维常用的脚本,提高工作效率就靠它了

前言

用Python做运维的小伙伴肯定会进行重复的工作,这个时候脚本的重要性就体现出来了

一个好的脚本工具可以帮你省去很多重复的工作,创造更大的价值

下面小编就带你们看看Python运维最常用的脚本吧

Python运维常用的脚本,提高工作效率就靠它了

清除指定redis缓存

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018-12-20 15:19
# @Author  : opsonly
# @Site    : 
# @File    : redisdel.py
# @Software: PyCharm

import 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 os

dir = "/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: PyCharm

import 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] + 1
        else:
            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()

Python运维常用的脚本,提高工作效率就靠它了

查看网段里有多少ip地址

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018-12-18 15:31
# @Author  : opsonly
# @Site    : 
# @File    : ipTest.py
# @Software: PyCharm
import IPy

ip = 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: PyCharm

from flask import Flask,request,render_template,make_response,Response
import json,os,re,requests
import subprocess

app = 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: PyCharm

import psutil

def memissue():
    print('内存信息:')
    mem = psutil.virtual_memory()
    # 单位换算为MB
    memtotal = mem.total/1024/1024
    memused = mem.used/1024/1024
    membaifen = 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('/')
    #单位换算为GB
    diskused = diskuse.used / 1024 / 1024 / 1024
    disktotal = diskuse.total / 1024 / 1024 / 1024
    diskbaifen = diskused / disktotal * 100
    print('%.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: PyCharm

import 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 s

for 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,wget

class RDS_BINLOG_RELATE(object):

    def __init__(self):
        #阿里云的id和key
        self.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

        #返回url
        url = url + "/?" + urllib.parse.urlencode(header)
        return url

    #按照规则替换
    def percentEncode(self,store):
        encodeStr = store
        res = 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()

喜欢小编的文章的小伙伴欢迎关注小编哦~

文章持续更新

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/158144.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • pycharm pip版本不对_python没有pip

    pycharm pip版本不对_python没有pip我在pycharm的Terminal中,更新pip的时候,出现了以下错误:原因:可能与最近的Windows10更新有关。我的版本如下:在cmd中输入msinfo32,回车,可以看到版本信息。解决办法:直接运行cmd,输入python-mpipinstall-Upip,就可正常升级pip了。PS:查到的另外一个解决办法是安装win_unicode_consol…

    2025年7月16日
    7
  • pycharm激活吗破解方法

    pycharm激活吗破解方法,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月15日
    52
  • discuz的diy功能介绍

    discuz的diy功能介绍

    2022年2月23日
    51
  • 最新版本git下载安装&配置教程「建议收藏」

    最新版本git下载安装&配置教程「建议收藏」原文地址https://blog.csdn.net/zx1996119/article/details/80814752下载地址:https://git-scm.com/downloads如图:这里下载完成后是酱子的如图(windows64位的)1.双击打开后,点击Next2.再次点击Next(这里我改了安装的路径)3.下图方框…

    2022年5月1日
    61
  • 剑指Offer面试题:9.打印1到最大的n位数

    一题目:打印1到最大的n位数二不考虑大数解法三字符串模拟算法解法解决这个问题需要表达一个大数。最常用也是最容易的方法是用字符串或者数组表达大数。该算法的步骤如下:Step1.把字符串中的

    2021年12月19日
    43
  • js ajax 跨域问题 解决方案[通俗易懂]

    js ajax 跨域问题 解决方案[通俗易懂]什么是跨域问题?跨域问题来源于JavaScript的”同源策略”,即只有协议+主机名+端口号(如存在)相同,则允许相互访问。也就是说JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源。跨域问题是针对JS和ajax的,html本身没有跨域问题。查看浏览器开发者工具Console报错:Failedtoloadhttp://a.a.com:8080/A/FromServlet?userName=123:No’Access-Control-Allow-Origi.

    2022年8月24日
    10

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号