python自动化运维脚本范例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python自动化运维脚本范例相关的知识,希望对你有一定的参考价值。

1.列举当前目录以及所有子目录下的文件,并打印出绝对路径
#!/usr/bin/python
# coding=utf8

import os
import sys
 
if len(sys.argv) < 2:
  filepath="."
else:
  filepath=sys.argv[1]

for root,dirs,files in os.walk(filepath):
  for filename in files:
    path=os.path.join(root,filename)
    print path

2.写一个函数,计算字符串中所有数字的和
#!/usr/bin/python
# coding=utf8

import sys

number="123456"

def Numsum(num):
  sum=0
  if len(num) > 0:
    for i in range(len(num)):
      if num[i] > '0' and num[i] < '9':
        sum=sum+int(num[i])
        print "sum=%s" % sum
     else:
       sys.exit(1)

if __name__ == '__main__':
  Numsum(number)

3.每天生成一个文件,并把磁盘的使用情况写到到这个文件中,文件名为日期格式(yyyy-mm-dd),如2018-06-10.log    
#!/usr/bin/python
# coding=utf8

import time
import os
import getopt
import sys

disk_path="/root/disk"
memory_path="/root/memory"

if not os.path.exists(disk_path):
  os.makedirs(disk_path)

if not os.path.exists(memory_path):
  os.makedirs(memory_path)

def Disk(time):
  status=os.popen('df -hTP').readlines()
  a=''.join(status)
  f=open('/root/disk/'+time+'.log','w')
  f.write(a)
  f.close()

def Memory(time):
  status=os.popen('free -g').readlines()
  a=''.join(status)
  f=open('/root/memory/'+time+'.log','w')
  f.write(a)
  f.close()

time = time.strftime("%Y-%m-%d-%H:%M:%S")
options,args = getopt.getopt(sys.argv[1:],'-d-m',['disk_status','memory_status'])
for opt_name,opt_value in options:
  if opt_name in ('-d','--disk_status'):
    try:
      Disk(time)
      print "Disk_status Complete"
      exit()
    except:
      print "Fail"
  if opt_name in ('-m','--memory_status'):
    try:
      Memory(time)
      print "Memory_status Complete"
      exit()
    except:
      print "Fail"

4.从nginx日志中统计出每个IP的访问量有多少,访问量超过10次的ip,用防火墙禁止使用,并发送邮件,三天后再打开限制,
#!/usr/bin/python
#coding=utf8

import os
import subprocess
from email.mime.text import MIMEText
import smtplib

refuse_ip = '/etc/nginx/refuse_nginx'
sender = '[email protected]'
receiver = '[email protected]'
password = '123456'
subject = 'nginx ip refuse'

def SendMail(ip):
  try:
    print "11111"
    content = ip+' is refuse'
    msg = MIMEText(content,'plain','utf-8')
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject
    server=smtplib.SMTP('localhost')
    server.sendmail(sender,receiver,msg.as_string())
    print "发送成功"
  except smtplib.SMTPException:
    print "发送失败"
 
if not os.path.exists(refuse_ip):
  os.mknod(refuse_ip)

def nginx_protect(ip):
  f=open(refuse_ip,'r+')
  cmd='iptables -A INPUT -p tcp --dport 80 -s '+ip+' -j DROP'
  cmd2='at now + 1 minutes << EOF iptables -D INPUT -p tcp --dport 80 -s '+ip+' -j DROP sed -i "s/'+ip+'//" /etc/nginx/refuse_nginx EOF'
  for i in f:
    if ip not in i:
      f.write(ip)
      os.popen(cmd)
      os.popen(cmd2)      
      SendMail(ip)
  print("ip 限制成功")
 
list=[]
nginx_file="/var/log/nginx/access.log"
f=file(nginx_file).readlines()
for i in f:
  nginx_ip=i.split()[0]
  list.append(nginx_ip)
nginxip=set(list)
for j in nginxip:
  num=list.count(j)
  if num > 10:
    nginx_protect(j)
  print "IP:%s NUM:%s" %  (j,num)

5.写一个脚本计算出所有进程所占用内存大小
#!/usr/bin/python
# coding=utf8

import os

list=[]
cmd='ps aux'
sum=0
status=os.popen(cmd).readlines()
for i in status:
  a=i.split()[5]
  list.append(a)
for i in list[1:-1]:
  sum=sum+int(i)
print "%s:%sB" % (list[0],sum)

7.MySQL状态监控
#!/usr/bin/python
#coding=utf8

import MySQLdb

host="localhost"
user="wjq"
passwd="123456"
db="test"

Com_insert="show global status like 'Com_insert';"
Com_update="show global status like 'Com_update';"
Com_select="show global status like 'Com_select';"
Com_delete="show global status like 'Com_delete';"
Open_tables="show global status like 'Open_tables';"
Qcache_hits="show global status like 'Qcache_hits';"

def getConn(host,user,passwd,db):
  try:
    conn = MySQLdb.connect(host,user,passwd,db)
    return conn
  except:
    print("数据库连接失败")

def getValue(conn,query):
  cursor = conn.cursor()
  getNum = cursor.execute(query)
  if getNum > 0:
    data = cursor.fetchone()
  return int(data[1])

if __name__ == '__main__':
  conn=getConn(host,user,passwd,db)
  Com_insert=getValue(conn,Com_insert)
  Com_update=getValue(conn,Com_update)
  Com_select=getValue(conn,Com_select)
  Com_delete=getValue(conn,Com_delete)
  Open_tables=getValue(conn,Open_tables)
  Qcache_hits=getValue(conn,Qcache_hits)
  print " *****MySQL Status*****"
  print " Com_insert:%s " % Com_insert
  print " Com_update:%s " % Com_update
  print " Com_select:%s " % Com_select
  print " Com_delete:%s " % Com_delete
  print " Open_tables:%s " % Open_tables
  print " Qcache_hits:%s " % Qcache_hits

8.自定义密码长度,生成随机密码
#!/usr/bin/python
# coding=utf8
import random

list=[]
def Passwd(num):
  for i in range(int(num)):
    a=random.randrange(0,int(num))
    if i == a:
      b1=random.randint(0,9)
      list.append(str(b1))
    else:
      b2=chr(random.randint(65,90))
      list.append(b2)  
  b3=''.join(list)
  return b3    

if __name__ == '__main__':
  num=raw_input("生成密码的长度为:")
  password=Passwd(num)
  print password

9.python实现mysql的zabbix监控脚本

#!/usr/bin/python
#coding=utf8

import MySQLdb
import sys

host="localhost"
user="wjq"
passwd="123456"
db="test"
Com_insert="show global status like 'Com_insert';"
Com_update="show global status like 'Com_update';"
Com_select="show global status like 'Com_select';"
Com_delete="show global status like 'Com_delete';"
Open_tables="show global status like 'Open_tables';"
Qcache_hits="show global status like 'Qcache_hits';"

def getConn(host,user,passwd,db):
  try:
    a = MySQLdb.connect(host,user,passwd,db)
    return a
  except:
    print "数据库连接失败"

def getValue(conn,query):
  try:
    cursor = conn.cursor()
    getNum = cursor.execute(query)
    if getNum > 0:
      data = cursor.fetchone()
      return int(data[1])
  except:
    print "查询失败"

conn = getConn(host,user,passwd,db)
if sys.argv[1] == 'insert':    
  Com_insert = getValue(conn,Com_insert)
  print Com_insert  
elif sys.argv[1] == 'delete':
  Com_delete = getValue(conn,Com_delete)
  print Com_delete
elif sys.argv[1] == 'select':
  Com_select = getValue(conn,Com_select)
  print Com_select
elif sys.argv[1] == 'update':
  Com_update = getValue(conn,Com_update)
  print Com_update
elif sys.argv[1] == 'table_num':
  Open_tables = getValue(conn,Open_tables)
  print Open_tables
elif sys.argv[1] == 'cache_hit':
  Qcache_hits = getValue(conn,Qcache_hits)
  print Qcache_hits

以上是关于python自动化运维脚本范例的主要内容,如果未能解决你的问题,请参考以下文章

Python自动化脚本-运维人员宝典

Python自动化运维之2

高性能可扩展的python自动化运维框架

纯干货!python 在运维中的应用 (一):批量 ssh/sftp

Python自动化运维之1Python入门

Linux运维自动化脚本之rsync