python运维自动化脚本案例-python自动化运维脚本范例

1.列举当前目录以及所有子目录下的文件,并打印出绝对路径#!/usr/bin/python# coding=utf8import osimport 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 path2.写一个函数,计算字符串中所有数字的和#!/usr/bin/python# coding=utf8import sysnumber="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=utf8import timeimport osimport getoptimport sysdisk_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=utf8import osimport subprocessfrom email.mime.text import MIMETextimport smtplibrefuse_ip = "/etc/nginx/refuse_nginx"sender = "wjq@123"receiver = "wujqc@yonyou.com"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=utf8import oslist=[]cmd="ps aux"sum=0status=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) 6.MySQL状态监控#!/usr/bin/python#coding=utf8import MySQLdbhost="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_hits7.自定义密码长度,生成随机密码#!/usr/bin/python# coding=utf8import randomlist=[]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 password8.python实现mysql的zabbix监控脚本#!/usr/bin/python#coding=utf8import MySQLdbimport syshost="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_deleteelif sys.argv[1] == "select": Com_select = getValue(conn,Com_select) print Com_selectelif sys.argv[1] == "update": Com_update = getValue(conn,Com_update) print Com_updateelif sys.argv[1] == "table_num": Open_tables = getValue(conn,Open_tables) print Open_tableselif sys.argv[1] == "cache_hit": Qcache_hits = getValue(conn,Qcache_hits) print Qcache_hits

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值