精华内容
下载资源
问答
  • Python运维中常用的几十个Python运维脚本本文由马哥教育Python自动化实战班4期学员推荐,转载自互联网,作者为mark,内容略经小编改编和加工,观点跟作者无关,最后感谢作者的辛苦贡献与付出。file是一个类,使用...

    原标题:经典!Python运维中常用的几十个Python运维脚本

    本文由马哥教育Python自动化实战班4期学员推荐,转载自互联网,作者为mark,内容略经小编改编和加工,观点跟作者无关,最后感谢作者的辛苦贡献与付出。

    file是一个类,使用file('file_name', 'r+')这种方式打开文件,返回一个file对象,以写模式打开文件不存在则会被创建。但是更推荐使用内置函数open()来打开一个文件。

    首先open是内置函数,使用方式是open('file_name', mode, buffering),返回值也是一个file对象,同样,以写模式打开文件如果不存在也会被创建一个新的。

    f=open('/tmp/hello','w')

    #open(路径+文件名,读写模式)

    #读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式

    如:'rb','wb','r+b'等等

    读写模式的类型有:

    rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)

    w 以写方式打开,

    a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)

    r+ 以读写模式打开

    w+ 以读写模式打开 (参见 w )

    a+ 以读写模式打开 (参见 a )

    rb 以二进制读模式打开

    wb 以二进制写模式打开 (参见 w )

    ab 以二进制追加模式打开 (参见 a )

    rb+ 以二进制读写模式打开 (参见 r+ )

    wb+ 以二进制读写模式打开 (参见 w+ )

    ab+ 以二进制读写模式打开 (参见 a+ )

    注意:

    1、使用'W',文件若存在,首先要清空,然后(重新)创建,

    2、使用'a'模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。

    f.read([size]) size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串)

    file.readline() 返回一行

    file.readline([size]) 返回包含size行的列表,size 未指定则返回全部行

    for line in f:

    print line #通过迭代器访问

    f.write("hellon") #如果要写入字符串以外的数据,先将他转换为字符串.

    f.tell() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).

    f.seek(偏移量,[起始位置])

    用来移动文件指针

    偏移量:单位:比特,可正可负

    起始位置:0-文件头,默认值;1-当前位置;2-文件尾

    f.close() 关闭文件

    要进行读文件操作,只需要把模式换成'r'就可以,也可以把模式为空不写参数,也是读的意思,因为程序默认是为'r'的。

    >>>f = open('a.txt', 'r')

    >>>f.read(5)

    'hello'

    read( )是读文件的方法,括号内填入要读取的字符数,这里填写的字符数是5,如果填写的是1那么输出的就应该是"h’。

    打开文件文件读取还有一些常用到的技巧方法,像下边这两种:

    1、read( ):表示读取全部内容

    2、readline( ):表示逐行读取

    一、用Python写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径

    #!/magedu/bin/env python

    import os

    for root,dirs,files in os.walk('/tmp'):

    for name in files:

    print (os.path.join(root,name))

    os.walk()

    原型为:os.walk(top, topdown=True, =None, followlinks=False)

    我们一般只使用第一个参数。(topdown指明遍历的顺序)

    该方法对于每个目录返回一个三元组,(dirpath, dirnames, filenames)。

    第一个是路径,第二个是路径下面的目录,第三个是路径下面的非目录(对于windows来说也就是文件)

    os.listdir(path)

    其参数含义如下。path 要获得内容目录的路径

    二、写程序打印三角形

    #!/magedu/bin/env python

    input = int(raw_input('input number:'))

    for i in range(input):

    for j in range(i):

    print '*',

    print 'n'

    三、猜数器,程序随机生成一个个位数字,然后等待用户输入,输入数字和生成数字相同则视为成功。

    成功则打印三角形。失败则重新输入(提示:随机数函数:random)

    #!/magedu/bin/env python

    import random

    while True:

    input = int(raw_input('input number:'))

    random_num = random.randint(1, 10)

    print input,random_num

    if input == random_num:

    for i in range(input):

    for j in range(i):

    print '*',

    print 'n'

    else:

    print 'please input number again'

    四、请按照这样的日期格式(xxxx-xx-xx)每日生成一个文件,例如今天生成的文件为2016-09-23.log, 并且把磁盘的使用情况写到到这个文件中。

    #!/magedu/bin/env python

    #!coding=utf-8

    import time

    import os

    new_time = time.strftime('%Y-%m-%d')

    disk_status = os.popen('df -h').readlines()

    str1 = ''.join(disk_status)

    f = file(new_time+'.log','w')

    f.write('%s' % str1)

    f.flush()

    f.close()

    五、统计出每个IP的访问量有多少?(从日志文件中查找)

    #!/magedu/bin/env python

    #!coding=utf-8

    list = []

    f = file('/tmp/1.log')

    str1 = f.readlines()

    f.close()

    for i in str1:

    ip = i.split()[0]

    list.append(ip)

    list_num = set(list)

    for j in list_num:

    num = list.count(j)

    print '%s : %s' %(j,num)

    1. 写个程序,接受用户输入数字,并进行校验,非数字给出错误提示,然后重新等待用户输入。

    2. 根据用户输入数字,输出从0到该数字之间所有的素数。(只能被1和自身整除的数为素数)

    #!/magedu/bin/env python

    #coding=utf-8

    import tab

    import sys

    while True:

    try:

    n = int(raw_input('请输入数字:').strip())

    for i in range(2, n + 1):

    for x in range(2, i):

    if i % x == 0:

    break

    else:

    print i

    except ValueError:

    print('你输入的不是数字,请重新输入:')

    except KeyboardInterrupt:

    sys.exit('n')

    六、python练习 抓取web页面

    from urllib import urlretrieve

    def firstNonBlank(lines):

    for eachLine in lines:

    if not eachLine.strip():

    continue

    else:

    return eachLine

    def firstLast(webpage):

    f=open(webpage)

    lines=f.readlines()

    f.close

    print firstNonBlank(lines), #调用函数

    lines.reverse()

    print firstNonBlank(lines),

    def download(url= 'http://www.magedu.com/72446.html',process=firstLast):

    try:

    retval = urlretrieve(url) [0]

    except IOError:

    retval = None

    if retval:

    process(retval)

    if __name__ == '__main__':

    download()

    七、Python中的sys.argv[]用法练习

    #!/magedu/bin/python

    # -*- coding:utf-8 -*-

    import sys

    def readFile(filename):

    f = file(filename)

    while True:

    fileContext = f.readline()

    if len(fileContext) ==0:

    break;

    print fileContext

    f.close()

    if len(sys.argv) < 2:

    print "No function be setted."

    sys.exit()

    if sys.argv[1].startswith("-"):

    option = sys.argv[1][1:]

    if option == 'version':

    print "Version1.2"

    elif option == 'help':

    print "enter an filename to see the context of it!"

    else:

    print "Unknown function!"

    sys.exit()

    else:

    for filename in sys.argv[1:]:

    readFile(filename)

    八、python迭代查找目录下文件

    #两种方法

    #!/magedu/bin/env python

    import os

    dir='/root/sh'

    '''

    def fr(dir):

    filelist=os.listdir(dir)

    for i in filelist:

    fullfile=os.path.join(dir,i)

    if not os.path.isdir(fullfile):

    if i == "1.txt":

    #print fullfile

    os.remove(fullfile)

    else:

    fr(fullfile)

    '''

    '''

    def fw()dir:

    for root,dirs,files in os.walk(dir):

    for f in files:

    if f == "1.txt":

    #os.remove(os.path.join(root,f))

    print os.path.join(root,f)

    '''

    九、ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。

    (提示,使用ps aux 列出所有进程,过滤出RSS那列,然后求和)

    #!/magedu/bin/env python

    #!coding=utf-8

    import os

    list = []

    sum = 0

    str1 = os.popen('ps aux','r').readlines()

    for i in str1:

    str2 = i.split()

    new_rss = str2[5]

    list.append(new_rss)

    for i in list[1:-1]:

    num = int(i)

    sum = sum + num

    print '%s:%s' %(list[0],sum)

    写一个脚本,判断本机的80端口是否开启着,如果开启着什么都不做,如果发现端口不存在,那么重启一下httpd服务,并发邮件通知你自己。脚本写好后,可以每一分钟执行一次,也可以写一个死循环的脚本,30s检测一次。

    #!/magedu/bin/env python

    #!coding=utf-8

    import os

    import time

    import sys

    import smtplib

    from email.mime.text import MIMEText

    from email.MIMEMultipart import MIMEMultipart

    def sendsimplemail (warning):

    msg = MIMEText(warning)

    msg['Subject'] = 'python first mail'

    msg['From'] = 'root@localhost'

    try:

    smtp = smtplib.SMTP()

    smtp.connect(r'smtp.126.com')

    smtp.login('要发送的邮箱名', '密码')

    smtp.sendmail('要发送的邮箱名', ['要发送的邮箱名'], msg.as_string())

    smtp.close()

    except Exception, e:

    print e

    while True:

    http_status = os.popen('netstat -tulnp | grep httpd','r').readlines()

    try:

    if http_status == []:

    os.system('service httpd start')

    new_http_status = os.popen('netstat -tulnp | grep httpd','r').readlines()

    str1 = ''.join(new_http_status)

    is_80 = str1.split()[3].split(':')[-1]

    if is_80 != '80':

    print 'httpd 启动失败'

    else:

    print 'httpd 启动成功'

    sendsimplemail(warning = "This is a warning!!!")#调用函数

    else:

    print 'httpd正常'

    time.sleep(5)

    except KeyboardInterrupt:

    sys.exit('n')

    #!/magedu/bin/python

    #-*- coding:utf-8 -*-

    #输入这一条就可以在Python脚本里面使用汉语注释!此脚本可以直接复制使用;

    while True: #进入死循环

    input = raw_input('Please input your username:')

    #交互式输入用户信息,输入input信息;

    if input == "wenlong":

    #如果input等于wenlong则进入此循环(如果用户输入wenlong)

    password = raw_input('Please input your pass:')

    #交互式信息输入,输入password信息;

    p = '123'

    #设置变量P赋值为123

    while password != p:

    #如果输入的password 不等于p(123), 则进此入循环

    password = raw_input('Please input your pass again:')

    #交互式信息输入,输入password信息;

    if password == p:

    #如果password等于p(123),则进入此循环

    print 'welcome to select system!' #输出提示信息;

    while True:

    #进入循环;

    match = 0

    #设置变量match等于0;

    input = raw_input("Please input the name whom you want to search :")

    #交互式信息输入,输入input信息;

    while not input.strip():

    #判断input值是否为空,如果input输出为空,则进入循环;

    input = raw_input("Please input the name whom you want to search :")

    #交互式信息输入,输入input信息;

    name_file = file('search_name.txt')

    #设置变量name_file,file('search_name.txt')是调用名为search_name.txt的文档

    while True:

    #进入循环;

    line = name_file.readline() #以行的形式,读取search_name.txt文档信息;

    if len(line) == 0: #当len(name_file.readline() )为0时,表示读完了文件,len(name_file.readline() )为每一行的字符长度,空行的内容为n也是有两个字符。len为0时进入循环;

    break #执行到这里跳出循环;

    if input in line: #如果输入的input信息可以匹配到文件的某一行,进入循环;

    print 'Match item: %s' %line #输出匹配到的行信息;

    match = 1 #给变量match赋值为1

    if match == 0 : #如果match等于0,则进入 ;

    print 'No match item found!' #输出提示信息;

    else: print "Sorry ,user %s not found " %input #如果输入的用户不是wenlong,则输出信息没有这个用户;

    #!/magedu/bin/python

    while True:

    input = raw_input('Please input your username:')

    if input == "wenlong":

    password = raw_input('Please input your pass:')

    p = '123'

    while password != p:

    password = raw_input('Please input your pass again:')

    if password == p:

    print 'welcome to select system!'

    while True:

    match = 0

    input = raw_input("Please input the name whom you want to search :")

    while not input.strip():

    print 'No match item found!'

    input = raw_input("Please input the name whom you want to search :")

    name_file = file('search_name.txt')

    while True:

    line = name_file.readline()

    if len(line) == 0:

    break

    if input in line:

    print 'Match item: ' , line

    match = 1

    if match == 0 :

    print 'No match item found!'

    else: print "Sorry ,user %s not found " %input

    十、Python监控CPU情况

    1、实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果

    2、特别注意:被监控的机器上需要支持snmp。yum install -y net-snmp*安装

    """

    #!/magedu/bin/python

    import os

    def getAllitems(host, oid):

    sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split('n')[:-1]

    return sn1

    def getDate(host):

    items = getAllitems(host, '.1.3.6.1.4.1.2021.11')

    date = []

    rate = []

    cpu_total = 0

    #us = us+ni, sy = sy + irq + sirq

    for item in items:

    float_item = float(item.split(' ')[3])

    cpu_total += float_item

    if item == items[0]:

    date.append(float(item.split(' ')[3]) + float(items[1].split(' ')[3]))

    elif item == item[2]:

    date.append(float(item.split(' ')[3] + items[5].split(' ')[3] + items[6].split(' ')[3]))

    else:

    date.append(float_item)

    #calculate cpu usage percentage

    for item in date:

    rate.append((item/cpu_total)*100)

    mean = ['%us','%ni','%sy','%id','%wa','%cpu_irq','%cpu_sIRQ']

    #calculate cpu usage percentage

    result = map(None,rate,mean)

    return result

    if __name__ == '__main__':

    hosts = ['192.168.10.1','192.168.10.2']

    for host in hosts:

    print '==========' + host + '=========='

    result = getDate(host)

    print 'Cpu(s)',

    #print result

    for i in range(5):

    print ' %.2f%s' % (result[i][0],result[i][1]),

    print

    print

    十一、Python监控网卡流量

    1、实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果

    2、特别注意:被监控的机器上需要支持snmp。yum install -y net-snmp*安装

    """

    #!/magedu/bin/python

    import re

    import os

    #get SNMP-MIB2 of the devices

    def getAllitems(host,oid):

    sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('n')[:-1]

    return sn1

    #get network device

    def getDevices(host):

    device_mib = getAllitems(host,'RFC1213-MIB::ifDescr')

    device_list = []

    for item in device_mib:

    if re.search('eth',item):

    device_list.append(item.split(':')[3].strip())

    return device_list

    #get network date

    def getDate(host,oid):

    date_mib = getAllitems(host,oid)[1:]

    date = []

    for item in date_mib:

    byte = float(item.split(':')[3].strip())

    date.append(str(round(byte/1024,2)) + ' KB')

    return date

    if __name__ == '__main__':

    hosts = ['192.168.10.1','192.168.10.2']

    for host in hosts:

    device_list = getDevices(host)

    inside = getDate(host,'IF-MIB::ifInOctets')

    outside = getDate(host,'IF-MIB::ifOutOctets')

    print '==========' + host + '=========='

    for i in range(len(inside)):

    print '%s : RX: %-15s TX: %s ' % (device_list[i], inside[i], outside[i])

    print

    ————开班喜讯————

    温馨提醒:马哥教育Python自动化开发班将于8月28日在北京海淀上地开班,小班制魔鬼式授课,钜惠限时抢位中。

    马哥教育2017年Python自动化运维开发实战班,马哥联合BAT、豆瓣等一线互联网Python开发达人,根据目前企业需求的Python开发人才进行了深度定制,加入了大量一线互联网公司:大众点评、饿了么、腾讯等生产环境真是项目,课程由浅入深,从Python基础到Python高级,让你融汇贯通Python基础理论,手把手教学让你具备Python自动化开发需要的前端界面开发、Web框架、大监控系统、CMDB系统、认证堡垒机、自动化流程平台六大实战能力,让你从0开始蜕变成Hold住年薪20万的Python自动化开发人才。

    292e93fdb7634497b5a9843c648f5ee1_th.jpg

    —Python学习免费交流QQ群:542679406(千人群)—返回搜狐,查看更多

    责任编辑:

    展开全文
  • Python运维脚本

    2015-11-05 17:29:24
    /usr/bin/env python # ueage: python tomcat.py start|stop|restart" import paramiko import threading import sys def ssh2(ip, username, passwd, cmd): try: ssh = paramiko.SSHCli...
    #!/usr/bin/env python
    # ueage: python tomcat.py start|stop|restart"
    import paramiko
    import threading
    import sys
    
    
    def ssh2(ip, username, passwd, cmd):
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(ip, 22, username, passwd, timeout=5)
            for m in cmd:
                stdin, stdout, stderr = ssh.exec_command(m)
                out = stdout.readlines()
                for o in out:
                    print o,
                print '###%s has done\n' % (ip)
            ssh.close()
        except:
            print '%s\tError\n' % (ip)
    
    
    def usage():
        print "ueage: python tomcat.py start|stop|restart|diskcheck|tomcatcheck|rmolddir"
        sys.exit(1)
    
    
    if __name__ == '__main__':
        argc = len(sys.argv)
        if argc < 2:
            usage()
        else:
            for i in sys.argv[1:]:
                if i == 'status':
                    cmd = ['/nfs/tomcat/tomcat.sh status && ls -l /opt/tomcat/webapps/']
                elif i == 'start':
                    cmd = ['/nfs/tomcat/tomcat.sh start']
                elif i == 'stop':
                    cmd = ['/nfs/tomcat/tomcat.sh stop']
                elif i == 'restart':
                    cmd = ['/nfs/tomcat/tomcat.sh restart']
                elif i == 'diskcheck':
                    cmd = ['df -h']
                elif i == 'tomcatcheck':
                    cmd = ['/nfs/tomcat/tomcat.sh tomcatcheck']
                elif i == 'rmolddir':
                    cmd = ['cd /opt/tomcat/webapps/; rm -rf admin trade admin']
                elif i == 'rmtrade':
                    cmd = ['cd /opt/tomcat/webapps/; rm -rf trade']
                else:
                    usage()
    
            username = "tomcat"
            passwd = "tomcat"
            print "Begin......"
            for i in range(1, 5):
                ip = 'tomcat' + str(i)
                run = threading.Thread(target=ssh2, args=(ip, username, passwd, cmd))
                run.start()
    

     

    Python资料: 

    http://www.cnblogs.com/gannan/archive/2012/02/06/2339883.html

    http://letong.me/category/python

    展开全文
  • Python运维脚本网络收集

    千次阅读 2020-08-24 14:39:04
    Python运维脚本网络收集 阅读目录 常用系统脚本 python 命令行模块 from optparse import OptionParser parser = OptionParser() parser.add_option("-u", "--user", action="store_true", dest="users", ...

    Python运维脚本网络收集

    阅读目录

    python 命令行模块

    from optparse import OptionParser
    
    parser = OptionParser()
    parser.add_option("-u", "--user", action="store_true", dest="users", default=False, help="user names")
    parser.add_option("-p", "--port", action="store_true", dest="ports", default=False, help="user ports")
    (options, args) = parser.parse_args() 
    
    if options.users==True:
        print("user names is true")
    if options.ports==True:
        print("passwd is true")
    

    Python 批量遍历目录文件,并修改访问时间

    >>> path="D:/UASM64/include/"
    >>> dirs = os.listdir(path)
    >>> for file in dirs:
    ...     print(os.path.join(path,file))
    
    import os
    
    path = "D:/UASM64/include/"
    dirs = os.listdir(path)
    temp=[];
    
    for file in dirs:
        temp.append(os.path.join(path, file))
    for x in temp:
        os.utime(x, (1577808000, 1577808000))
    

    遍历目录和文件

    import os
    
    
    def list_all_files(rootdir):
        import os
        _files = []
        list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
        for i in range(0,len(list)):
               path = os.path.join(rootdir,list[i])
               if os.path.isdir(path):
                  _files.extend(list_all_files(path))
               if os.path.isfile(path):
                  _files.append(path)
        return _files
    
    a=list_all_files("C:/Users/LyShark/Desktop/a")
    print(a)
    

    python检测指定端口状态

    import socket
    
    sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sk.settimeout(1)
    
    for ip in range(0,254):
        try:
            sk.connect(("192.168.1."+str(ip),443))
            print("192.168.1.%d server open \n"%ip)
        except Exception:
            print("192.168.1.%d server not open"%ip)
    
    sk.close()
    

     

    python实现批量执行CMD命令

    import sys
    import os
    import paramiko
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    print("------------------------------>\n")
    print("使用说明,在当前目录创建ip.txt写入ip地址")
    print("------------------------------>\n")
    
    user=input("输入用户名:")
    passwd=input("输入密码:")
    port=input("输入端口:")
    cmd=input("输入执行的命令:")
    
    file = open("./ip.txt", "r")
    line = file.readlines()
    
    for i in range(len(line)):
            print("对IP: %s 执行"%line[i].strip('\n'))
            
            ssh.connect(hostname=line[i].strip('\n'),port=port,username=user,password=passwd)
            stdin, stdout, stderr = ssh.exec_command(cmd)
            result = stdout.read()
    
            if not result:
                result=stderr.read()
            ssh.close()
    
            print(result.decode())
    

     

    python3-实现钉钉报警

    import requests
    import sys
    import json
    
    dingding_url = 'https://oapi.dingtalk.com/robot/send?access_token=6d11af3252812ea50410c2ccb861814a6ed11b2306606934a5d4ca9f2ec8c09'
    
    data = {"msgtype": "markdown","markdown": {"title": "监控","text": "apche异常"}}
    
    headers = {'Content-Type':'application/json;charset=UTF-8'}
    
    send_data = json.dumps(data).encode('utf-8')
    requests.post(url=dingding_url,data=send_data,headers=headers)
    
    #coding: utf-8
    import psutil
    import requests
    import time
    import os
    import json
    
    monitor_name = set(['httpd','cobblerd'])  # 用户指定监控的服务进程名称
    
    proc_dict = {}
    proc_name = set()  # 系统检测的进程名称
    monitor_map = {
        'httpd': 'systemctl restart httpd',
        'cobblerd': 'systemctl restart cobblerd'  # 系统在进程down掉后,自动重启
    }
    
    dingding_url = 'https://oapi.dingtalk.com/robot/send?access_token=b5258c4335ed8ab792075013c965efcbf4f8940f92e7bd936cdc7842d3bf9405'
    # 钉钉机器人token使用参考文档:http://www.pc6.com/infoview/Article_108931.html
    
    while True:
        for proc in psutil.process_iter(attrs=['pid','name']):
            proc_dict[proc.info['pid']] = proc.info['name']
            proc_name.add(proc.info['name'])
    
        proc_stop = monitor_name - proc_name  # 通过集合的形式来找出停掉的进程名,前者有但是后者没有的
    
        if proc_stop: # 如果确实有监控的进程停掉了,那么我们需要告警以及自动重启功能
            for p in proc_stop:
                p_status = '停止'
                p_name = p
                data = {
                    "msgtype": "markdown",
                    "markdown": {
                        "title": "监控信息",
                        "text": "### %s\n" % time.strftime("%Y-%m-%d %X") +
                        "> #### 服务名:%s \n\n" % p_name +
                        "> #### 状态:%s \n\n" % p_status +
                        "> #### 正在尝试启动"
                    },
                }
                headers = {'Content-Type':'application/json;charset=UTF-8'}
                send_data = json.dumps(data).encode('utf-8')
                requests.post(url=dingding_url,data=send_data,headers=headers)
    
                os.system(monitor_map[p_name]) # 执行重启命令,然后判断是否重启成功
                proc_set = set()
                for proc_again in psutil.process_iter(attrs=['pid','name']):
                    proc_set.add(proc_again.info['name'])
    
                if p in proc_set: # 如果进程启动成功,p是以前停掉的进程,proc_set是已经重启过一次后的所有进程集合
                    p_status = '成功'
                    p_name = p
                    data = {
                        "msgtype": "markdown",
                        "markdown": {
                            "title": "监控信息",
                            "text": "### %s\n" % time.strftime("%Y-%m-%d %X") +
                            "> #### 服务名:%s \n\n" % p_name +
                            "> #### 状态:%s \n\n" % p_status +
                            "> #### 已经启动成功,服务正在运行!"
                        },
                    }
                    headers = {'Content-Type':'application/json;charset=UTF-8'}
                    send_data = json.dumps(data).encode('utf-8')
                    requests.post(url=dingding_url,data=send_data,headers=headers)
                else:
                    p_status = '重启失败'
                    p_name = p
                    data = {
                        "msgtype": "markdown",
                        "markdown": {
                            "title": "监控信息",
                            "text": "### %s\n" % time.strftime("%Y-%m-%d %X") +
                            "> #### 服务名:%s \n\n" % p_name +
                            "> #### 状态:%s \n\n" % p_status +
                            "> #### Sorry,服务启动失败鸟!"
                        },
                    }
                    headers = {'Content-Type':'application/json;charset=UTF-8'}
                    send_data = json.dumps(data).encode('utf-8')
                    requests.post(url=dingding_url,data=send_data,headers=headers)
        time.sleep(5)
    

     

    判断指定端口是否开放

    import socket
    
    port_number = [135,443,80]
    
    for index in port_number:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex(('127.0.0.1', index))
        if result == 0:
            print("Port %d is open" % index)
        else:
            print("Port %d is not open" % index)
        sock.close()
    

     

    判断指定端口并且实现钉钉轮询报警

    #By LyShark
    
    import requests
    import sys
    import json
    import socket
    import time
    
    
    def dingding(title,text):
        dingding_url = 'https://oapi.dingtalk.com/robot/send?access_token=6d11af3252812ea50410c2ccb861814a69ed11b2306606934a5d4ca9f2c8c09'
        data = {"msgtype": "markdown","markdown": {"title": title,"text": text}}
        headers = {'Content-Type':'application/json;charset=UTF-8'}
        send_data = json.dumps(data).encode('utf-8')
        requests.post(url=dingding_url,data=send_data,headers=headers)
    
    def net_scan():
        port_number = [80,135,443]
        for index in port_number:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            result = sock.connect_ex(('127.0.0.1', index))
            if result == 0:
                print("Port %d is open" % index)
            else:
                return index
            sock.close()
    
    
    while True:
        dingding("Warning",net_scan())
        time.sleep(60)
    

     

    python-实现SSH批量CMD执行命令

    # By:LyShark
    
    import sys
    import os
    import paramiko
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    
    
    def ssh_cmd(user,passwd,port,userfile,cmd):
        file = open(userfile, "r")
        line = file.readlines()
        for i in range(len(line)):
            print("对IP: %s 执行"%line[i].strip('\n'))
            ssh.connect(hostname=line[i].strip('\n'),port=port,username=user,password=passwd)
            cmd=cmd
            stdin, stdout, stderr = ssh.exec_command(cmd)
            result = stdout.read()
    
            if not result:
                result=stderr.read()
            ssh.close()
    
            print(result.decode())
    
    
    ssh_cmd("lyshark","123","22","./ip.txt","free -h |grep 'Mem:' |awk '{print $3}'")
    

     

    用python写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径

    import sys
    import os
    
    for root,dirs,files in os.walk("C://"):
        for name in files:
            print(os.path.join(root,name))
    os.walk()
    

     

    按照这样的日期格式(xxxx-xx-xx)每日生成一个文件,例如今天生成的文件为2013-09-23.log, 并且把磁盘的使用情况写到到这个文件中。

    import os
    import sys
    import time
    
    new_time = time.strftime("%Y-%m-%d")
    disk_status = os.popen("df -h").readlines()
    
    str1 = ''.join(disk_status)
    f = open(new_time+'.log','w')
    f.write("%s"%str1)
    
    f.flush()
    f.close()
    

     

    统计出每个IP的访问量有多少?(从日志文件中查找)

    import sys
    
    list = []
    
    f = open("/var/log/httpd/access_log","r")
    str1 = f.readlines()
    f.close()
    
    for i in str1:
            ip=i.split()[0]
            list.append(ip)
    
    list_num=set(list)
    
    for j in list_num:
            num=list.count(j)
            print("%s -----> %s" %(num,j))
    

     

    写个程序,接受用户输入数字,并进行校验,非数字给出错误提示,然后重新等待用户输入。

    #根据用户输入数字,输出从0到该数字之间所有的素数。(只能被1和自身整除的数为素数)
    import tab
    import sys
    
    while True:
            try:
                    num=int(input("输入数字:").strip())
                    for x in range(2,num+1):
                            for y in range(2,x):
                                    if x % y == 0:
                                            break
                                    else:
                                            print(x)
            except ValueError:
                    print("您输入的不是数字")
            except KeyboardInterrupt:
                    sys.exit("\n")
    

     

    ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。

    #(提示,使用ps aux 列出所有进程,过滤出RSS那列,然后求和)
    import sys
    import os
    
    list=[]
    sum=0
    
    str1=os.popen("ps aux","r").readlines()
    
    for i in str1:
            str2=i.split()
            new_rss=str2[5]
            list.append(new_rss)
    for i in list[1:-1]:
            num=int(i)
            sum=sum+num
    
    print("%s ---> %s"%(list[0],sum))
    

     

    关于Python 命令行参数argv

    import sys
    
    if len(sys.argv) < 2:
        print ("没有输入任何参数")
        sys.exit()
    
    if sys.argv[1].startswith("-"):
        option = sys.argv[1][1:]
    
        if option == "version":
            print ("版本信息")
        elif option == "help":
            print ("帮助菜单")
        elif option == "option":
            print("配置菜单")
        else:
            print ("异常")
            sys.exit()
    

     

    利用random生成6位数字加字母随机验证码

    import sys
    import random
    
    rand=[]
    
    for x in range(6):
            y=random.randrange(0,5)
            if y == 2 or y == 4:
                    num=random.randrange(0,9)
                    rand.append(str(num))
            else:
                    temp=random.randrange(65,91)
                    c=chr(temp)
                    rand.append(c)
    result="".join(rand)
    print(result)
    

     

    自动化-使用pexpect非交互登陆系统

    import pexpect
    import sys
    
    ssh = pexpect.spawn('ssh lyshark@59.110.167.239')
    fout = file('sshlog.txt', 'w')
    ssh.logfile = fout
    
    
    ssh.expect("lyshark@59.110.167.239's password:")
    
    
    ssh.sendline("密码")
    ssh.expect('#')
    
    ssh.sendline('ls /home')
    ssh.expect('#')
    

     

    Python-取系统时间

    import sys
    import time
    
    time_str = time.strftime("日期:%Y-%m-%d",time.localtime())
    print(time_str)
    
    time_str= time.strftime("时间:%H:%M",time.localtime())
    print(time_str)
    

     

    psutil-获取内存使用情况

    import sys
    import os
    import psutil
    
    
    #获取系统内存使用情况
    
    memory_convent = 1024 * 1024
    mem =psutil.virtual_memory()
    
    
    print("内存容量为:"+str(mem.total/(memory_convent))+"MB\n")
    print("已使用内存:"+str(mem.used/(memory_convent))+"MB\n")
    print("可用内存:"+str(mem.total/(memory_convent)-mem.used/(1024*1024))+"MB\n")
    print("buffer容量:"+str(mem.buffers/( memory_convent ))+"MB\n")
    print("cache容量:"+str(mem.cached/(memory_convent))+"MB\n")
    

     

    Python-通过SNMP协议监控CPU
    注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

    #!/usr/bin/python
    import os
    
    def getAllitems(host, oid):
            sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split('\n')[:-1]
            return sn1
    
    def getDate(host):
            items = getAllitems(host, '.1.3.6.1.4.1.2021.11')
    
            date = []
            rate = []
            cpu_total = 0
    
            #us = us+ni, sy = sy + irq + sirq
    
            for item in items:
                    float_item = float(item.split(' ')[3])
                    cpu_total += float_item
                    if item == items[0]:
                            date.append(float(item.split(' ')[3]) + float(items[1].split(' ')[3]))
                    elif item == item[2]:
                            date.append(float(item.split(' ')[3] + items[5].split(' ')[3] + items[6].split(' ')[3]))
                    else:
                            date.append(float_item)
    
            #calculate cpu usage percentage
    
            for item in date:
                    rate.append((item/cpu_total)*100)
    
            mean = ['%us','%ni','%sy','%id','%wa','%cpu_irq','%cpu_sIRQ']
    
            #calculate cpu usage percentage
            result = map(None,rate,mean)
            return result
    
    
    if __name__ == '__main__':
    
            hosts = ['192.168.1.17','192.168.1.17']
    
            for host in hosts:
                    print '==========' + host + '=========='
                    result = getDate(host)
                    print 'Cpu(s)',
                    #print result
                    for i in range(5):
                            print ' %.2f%s' % (result[i][0],result[i][1]),
                    print
                    print
    

     

    Python-通过SNMP协议监控系统负载
    注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

    #!/usr/bin/python
    import os
    import sys
    
    def getAllitems(host, oid):
            sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')
            return sn1
    
    def getload(host,loid):
            load_oids = '1.3.6.1.4.1.2021.10.1.3.' + str(loid)
            return getAllitems(host,load_oids)[0].split(':')[3]
    
    if __name__ == '__main__':
    
            hosts = ['192.168.1.17','192.168.1.17']
    
            print ('==============System Load==============')
    
            for host in hosts:
                    load1 = getload(host, 1)
                    load10 = getload(host, 2)
                    load15 = getload(host, 3)
                    print ('%s load(1min): %s ,load(10min): %s ,load(15min): %s' % (host,load1,load10,load15))
    

     

    Python-通过SNMP协议监控内存
    注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

    #!/usr/bin/python
    import os
    
    def getAllitems(host, oid):
    
            sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]
            return sn1
    
    
    def getSwapTotal(host):
    
            swap_total = getAllitems(host, 'UCD-SNMP-MIB::memTotalSwap.0')[0].split(' ')[3]
            return swap_total
    
    
    def getSwapUsed(host):
    
            swap_avail = getAllitems(host, 'UCD-SNMP-MIB::memAvailSwap.0')[0].split(' ')[3]
            swap_total = getSwapTotal(host)
            swap_used = str(round(((float(swap_total)-float(swap_avail))/float(swap_total))*100 ,2)) + '%'
            return swap_used
    
    
    def getMemTotal(host):
    
            mem_total = getAllitems(host, 'UCD-SNMP-MIB::memTotalReal.0')[0].split(' ')[3]
            return mem_total
    
    
    def getMemUsed(host):
    
            mem_total = getMemTotal(host)
            mem_avail = getAllitems(host, 'UCD-SNMP-MIB::memAvailReal.0')[0].split(' ')[3]
            mem_used = str(round(((float(mem_total)-float(mem_avail))/float(mem_total))*100 ,2)) + '%'
            return mem_used
    
    if __name__ == '__main__':
    
            hosts = ['192.168.1.17','192.168.1.17']
            print ("Monitoring Memory Usage")
    
            for host in hosts:
    
                    mem_used = getMemUsed(host)
                    swap_used = getSwapUsed(host)
    
                    print ('==========' + host + '==========')
                    print ('Mem_Used = %-15s  Swap_Used = %-15s' %(mem_used,swap_used))
                    print()
    

     

    Python-通过SNMP协议监控磁盘
    注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

    #!/usr/bin/python
    
    import re
    import os
    
    def getAllitems(host,oid):
    
            sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]
            return sn1
    
    
    def getDate(source,newitem):
    
            for item in source[5:]:
                    newitem.append(item.split(':')[3].strip())
            return newitem
    
    
    def getRealDate(item1,item2,listname):
    
            for i in range(len(item1)):
                    listname.append(int(item1[i])*int(item2[i])/1024)
            return listname
    
    
    def caculateDiskUsedRate(host):
    
            hrStorageDescr = getAllitems(host, 'HOST-RESOURCES-MIB::hrStorageDescr')
            hrStorageUsed = getAllitems(host, 'HOST-RESOURCES-MIB::hrStorageUsed')
            hrStorageSize = getAllitems(host, 'HOST-RESOURCES-MIB::hrStorageSize')
            hrStorageAllocationUnits = getAllitems(host, 'HOST-RESOURCES-MIB::hrStorageAllocationUnits')
    
    
            disk_list = []
            hrsused = []
            hrsize = []
            hrsaunits = []
                                                                 
            #get disk_list
    
            for item in hrStorageDescr:
                    if re.search('/',item):
                            disk_list.append(item.split(':')[3])
    
            #print disk_list      
    
                                                                 
    
            getDate(hrStorageUsed,hrsused)
            getDate(hrStorageSize,hrsize)
    
            #print getDate(hrStorageAllocationUnits,hrsaunits)
    
                                                                 
    
            #get hrstorageAllocationUnits
    
            for item in hrStorageAllocationUnits[5:]:
                    hrsaunits.append(item.split(':')[3].strip().split(' ')[0])
    
            #caculate the result
    
            #disk_used = hrStorageUsed * hrStorageAllocationUnits /1024 (KB)
    
            disk_used = []
            total_size = []
            disk_used = getRealDate(hrsused,hrsaunits,disk_used)
            total_size = getRealDate(hrsize,hrsaunits,total_size)
    
                                                                 
    
            diskused_rate = []
    
            for i in range(len(disk_used)):
                    diskused_rate.append(str(round((float(disk_used[i])/float(total_size[i])*100), 2)) + '%')
    
            return diskused_rate,disk_list
    
                                                                 
    
    if __name__ == '__main__':
    
            hosts = ['192.168.1.17','192.168.1.17']
    
            for host in hosts:
    
                    result = caculateDiskUsedRate(host)
                    diskused_rate = result[0]
                    partition = result[1]
    
                    print ("==========",host,'==========')
    
                    for i in range(len(diskused_rate)):
                            print ('%-20s used: %s' %(partition[i],diskused_rate[i]))
                    print()
    

     

    Python-通过SNMP协议监控网卡流量
    注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*

    #!/usr/bin/python
    
    import re
    import os
    
    #get SNMP-MIB2 of the devices
    def getAllitems(host,oid):
            sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]
            return sn1
    
    #get network device
    def getDevices(host):
            device_mib = getAllitems(host,'RFC1213-MIB::ifDescr')
            device_list = []
    
            for item in device_mib:
                    if re.search('eth',item):
                            device_list.append(item.split(':')[3].strip())
            return device_list
    
    #get network date
    
    def getDate(host,oid):
            date_mib = getAllitems(host,oid)[1:]
            date = []
    
            for item in date_mib:
                    byte = float(item.split(':')[3].strip())
                    date.append(str(round(byte/1024,2)) + ' KB')
            return date
    
    
    if __name__ == '__main__':
    
            hosts = ['192.168.1.17','192.168.1.17']
    
            for host in hosts:
                    device_list = getDevices(host)
                    inside = getDate(host,'IF-MIB::ifInOctets')
                    outside = getDate(host,'IF-MIB::ifOutOctets')
    
                    print '==========' + host + '=========='
    
                    for i in range(len(inside)):
                            print '%s : RX: %-15s   TX: %s ' % (device_list[i], inside[i], outside[i])
                    print
    

     

    Python-实现多级菜单

    import os
    import sys
    
    ps="[None]->"
    ip=["192.168.1.1","192.168.1.2","192.168.1.3"]
    flage=1
    
    while True:
        ps="[None]->"
        temp=input(ps)
        if (temp=="test"):
            print("test page !!!!")
        elif(temp=="user"):
            while (flage == 1):
                ps="[User]->"
                temp1=input(ps)
                if(temp1 =="exit"):
                    flage=0
                    break
                elif(temp1=="show"):
                    for i in range(len(ip)):
                        print(i)
    

     

    Python实现一个没用的东西

    import sys
    
    
    ps="[root@localhost]# "
    ip=["192.168.1.1","192.168.1.2","192.168.1.3"]
    
    while True:
        temp=input(ps)
        temp1=temp.split()
    
        try:
            
            if(temp=="show"):
                for i in range(len(ip)):
                    print(ip[i])
            elif( temp1[0] == "user" and temp1[1] != "" ):
                print("您的执行参数是:"+temp1[1])
        except Exception:
            continue
    

     

    检查各个进程读写的磁盘IO

    #!/usr/bin/env python
    # -*- coding=utf-8 -*-
     
    import sys
    import os
    import time
    import signal
    import re
     
    class DiskIO:
       def __init__(self, pname=None, pid=None, reads=0, writes=0):
           self.pname = pname
           self.pid = pid
           self.reads = 0
           self.writes = 0
     
    def main():
       argc = len(sys.argv)
       if argc != 1:
           print ("usage: please run this script like [./lyshark.py]")
           sys.exit(0)
       if os.getuid() != 0:
           print ("Error: This script must be run as root")
           sys.exit(0)
       signal.signal(signal.SIGINT, signal_handler)
       os.system('echo 1 > /proc/sys/vm/block_dump')
       print ("TASK              PID       READ      WRITE")
       while True:
           os.system('dmesg -c > /tmp/diskio.log')
           l = []
           f = open('/tmp/diskio.log', 'r')
           line = f.readline()
           while line:
               m = re.match(\
                   '^(\S+)(\d+)(\d+): (READ|WRITE) block (\d+) on (\S+)', line)
               if m != None:
                   if not l:
                       l.append(DiskIO(m.group(1), m.group(2)))
                       line = f.readline()
                       continue
                   found = False
                   for item in l:
                       if item.pid == m.group(2):
                           found = True
                           if m.group(3) == "READ":
                               item.reads = item.reads + 1
                           elif m.group(3) == "WRITE":
                               item.writes = item.writes + 1
                   if not found:
                       l.append(DiskIO(m.group(1), m.group(2)))
               line = f.readline()
           time.sleep(1)
           for item in l:
               print ("%-10s %10s %10d %10d" % \
                   (item.pname, item.pid, item.reads, item.writes))
    def signal_handler(signal, frame):
       os.system('echo 0 > /proc/sys/vm/block_dump')
       sys.exit(0)
    
    
    if __name__=="__main__":
       main()
    

     

    利用Pexpect实现自动非交互登陆linux

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import pexpect
    import sys
    
    ssh = pexpect.spawn('ssh root@59.110.167.239')
    fout = file('sshlog.log', 'w')
    ssh.logfile = fout
    
    
    ssh.expect("root@59.110.167.239's password:")
    
    ssh.sendline("密码")
    
    ssh.expect('#')
    ssh.sendline('ls /home')
    ssh.expect('#')
    

     

    利用psutil模块获取系统的各种统计信息

    import sys
    import psutil
    import time
    import os 
     
    #获取当前时间
    time_str =  time.strftime( "%Y-%m-%d", time.localtime( ) )
    file_name = "./" + time_str + ".log"
     
    if os.path.exists ( file_name ) == False :
       os.mknod( file_name )
       handle = open ( file_name , "w" )
    else :
       handle = open ( file_name , "a" )
     
     
    #获取命令行参数的个数
    if len( sys.argv ) == 1 :
       print_type = 1
    else :
       print_type = 2
     
    def isset ( list_arr , name ) :
        if name in list_arr :
           return True
        else :
           return False
     
    print_str = "";
     
    #获取系统内存使用情况
    if ( print_type == 1 ) or isset( sys.argv,"mem" )  :
     memory_convent = 1024 * 1024
     mem = psutil.virtual_memory()
     print_str +=  " 内存状态如下:\n" 
     print_str = print_str + "   系统的内存容量为: "+str( mem.total/( memory_convent ) ) + " MB\n" 
     print_str = print_str + "   系统的内存以使用容量为: "+str( mem.used/( memory_convent ) ) + " MB\n" 
     print_str = print_str + "   系统可用的内存容量为: "+str( mem.total/( memory_convent ) - mem.used/( 1024*1024 )) + "MB\n"
     print_str = print_str + "   内存的buffer容量为: "+str( mem.buffers/( memory_convent ) ) + " MB\n" 
     print_str = print_str + "   内存的cache容量为:" +str( mem.cached/( memory_convent ) ) + " MB\n"
     
     
    #获取cpu的相关信息
    if ( print_type == 1 ) or isset( sys.argv,"cpu" ) :
     print_str += " CPU状态如下:\n"
     cpu_status = psutil.cpu_times()
     print_str = print_str + "   user = " + str( cpu_status.user ) + "\n" 
     print_str = print_str + "   nice = " + str( cpu_status.nice ) + "\n"
     print_str = print_str + "   system = " + str( cpu_status.system ) + "\n"
     print_str = print_str + "   idle = " + str ( cpu_status.idle ) + "\n"
     print_str = print_str + "   iowait = " + str ( cpu_status.iowait ) + "\n"
     print_str = print_str + "   irq = " + str( cpu_status.irq ) + "\n"
     print_str = print_str + "   softirq = " + str ( cpu_status.softirq ) + "\n" 
     print_str = print_str + "   steal = " + str ( cpu_status.steal ) + "\n"
     print_str = print_str + "   guest = " + str ( cpu_status.guest ) + "\n"
     
     
    #查看硬盘基本信息
    if ( print_type == 1 ) or isset ( sys.argv,"disk" ) :
     print_str +=  " 硬盘信息如下:\n" 
     disk_status = psutil.disk_partitions()
     for item in disk_status :
         print_str = print_str + "   "+ str( item ) + "\n"
     
    #查看当前登录的用户信息
    if ( print_type == 1 ) or isset ( sys.argv,"user" ) :
     print_str +=  " 登录用户信息如下:\n " 
     user_status = psutil.users()
     for item in  user_status :
         print_str = print_str + "   "+ str( item ) + "\n"
     
    print_str += "---------------------------------------------------------------\n"
    print ( print_str )
    handle.write( print_str )
    handle.close()
    
    # 输出内存使用情况(以字节为单位)
    
    import psutil
    
    mem = psutil.virtual_memory()
    print mem.total,mem.used,mem
    print psutil.swap_memory()  # 输出获取SWAP分区信息
    
    # 输出CPU使用情况
    
    cpu = psutil.cpu_stats()
    printcpu.interrupts,cpu.ctx_switches
      
    psutil.cpu_times(percpu=True)      # 输出每个核心的详细CPU信息
    psutil.cpu_times().user              # 获取CPU的单项数据 [用户态CPU的数据]
    psutil.cpu_count()                   # 获取CPU逻辑核心数,默认logical=True
    psutil.cpu_count(logical=False) # 获取CPU物理核心数
    
    # 输出磁盘信息
    
    psutil.disk_partitions()         # 列出全部的分区信息
    psutil.disk_usage('/')               # 显示出指定的挂载点情况【字节为单位】
    psutil.disk_io_counters()       # 磁盘总的IO个数
    psutil.disk_io_counters(perdisk=True)  # 获取单个分区IO个数
    
    
    # 输出网卡信息
    psutil.net_io_counter() 获取网络总的IO,默认参数pernic=False
    psutil.net_io_counter(pernic=Ture)获取网络各个网卡的IO
    
    # 获取进程信息
    psutil.pids()     # 列出所有进程的pid号
    p = psutil.Process(2047)
    p.name()   列出进程名称
    p.exe()    列出进程bin路径
    p.cwd()    列出进程工作目录的绝对路径
    p.status()进程当前状态[sleep等状态]
    p.create_time()   进程创建的时间 [时间戳格式]
    p.uids()
    p.gids()
    p.cputimes()  【进程的CPU时间,包括用户态、内核态】
    p.cpu_affinity()  # 显示CPU亲缘关系
    p.memory_percent()   进程内存利用率
    p.meminfo()   进程的RSS、VMS信息
    p.io_counters()   进程IO信息,包括读写IO数及字节数
    p.connections()   返回打开进程socket的namedutples列表
    p.num_threads()   进程打开的线程数
    
    #下面的例子中,Popen类的作用是获取用户启动的应用程序进程信息,以便跟踪程序进程的执行情况
    
    import psutil
    from subprocess import PIPE
    p =psutil.Popen(["/usr/bin/python" ,"-c","print 'helloworld'"],stdout=PIPE)
    p.name()
    p.username()
    p.communicate()
    p.cpu_times()
    
    # 其它
    psutil.users()    # 显示当前登录的用户,和Linux的who命令差不多
      
    # 获取开机时间
    psutil.boot_time() 结果是个UNIX时间戳,下面我们来转换它为标准时间格式,如下:
    datetime.datetime.fromtimestamp(psutil.boot_time())  # 得出的结果不是str格式,继续进行转换 datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d%H:%M:%S')
    

     

    Python生成一个随机密码

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import random, string
    def GenPassword(length):
    
        #随机出数字的个数
        numOfNum = random.randint(1,length-1)
        numOfLetter = length - numOfNum
    
        #选中numOfNum个数字
        slcNum = [random.choice(string.digits) for i in range(numOfNum)]
    
        #选中numOfLetter个字母
        slcLetter = [random.choice(string.ascii_letters) for i in range(numOfLetter)]
    
        #打乱这个组合
        slcChar = slcNum + slcLetter
        random.shuffle(slcChar)
        #生成密码
        genPwd = ''.join([i for i in slcChar])
        return genPwd
    if __name__ == '__main__':
        print (GenPassword(6))
    

    一个没有完成的命令行工具

    import sys
    import os
    
    iplist=[('192.168.1.10', 44123), ('192.168.1.20', 44125), ('192.168.1.30', 44126), ('192.168.1.40', 44127), ('192.168.1.50', 44130)]
    cmd="[Shell] # "
    
    def list():
        for i in range(len(iplist)):
            print("主机:%s  端口号:%s"%(iplist[i][0],iplist[i][1]))
    
    def use(temp):
        for i in range(len(iplist)):
            if iplist[i][0] ==temp:
                x="["+str(temp)+"] #"
                return x
        return cmd
    
    
    
    def main():
        while True:
            global cmd
            try:
                shell=str(input(cmd))
                if(shell == ""):
                    continue
                elif(shell == "show"):
                    list()
                elif(shell.split(" ")[0].strip() == "use"):
                    cmd=str(use(shell.split(" ")[1].strip()))
                elif(shell=="exit"):
                    if cmd!="[Shell] # ":
                        cmd="[Shell] # "
                    else:
                        exit(0)
                else:
                    print("未知命令行")
            except Exception:
                continue
    

    另一个简单的登录例子

    import socket
    import os
    
    db=["admin","guest","lyshark"]
    
    def check(db,recv):
        for i in range(len(db)):
            if bytes(db[i],encoding="utf-8") == bytes(recv):
                return 1
        return 0
    
    def sock():
        server=socket.socket()
        server.bind(("localhost",9999))
        server.listen(5)
    
        conn,addr=server.accept()
        recv_data=conn.recv(1024)
        num=check(db,recv_data)
        if num ==1:
            print("账户存在...")
            conn.send(bytes("账户存在....",encoding="utf-8"))
        else:
            print("账户不存在...")
            conn.send(bytes("账户不存在....", encoding="utf-8"))
    sock()
    import socket
    import os
    client=socket.socket()
    client.connect(("localhost",9999))
    
    user=input("输入名称:").strip()
    client.send(bytes(user,encoding="utf-8"))
    
    num=client.recv(1024)
    print(str(num,encoding="utf-8"))
    

    回到顶部

    常用系统脚本

    监控系统CPU

    import psutil
    
    >>> psutil.cpu_times()
    scputimes(user=8277.5625, system=2510.953125, idle=31077.65625, interrupt=147.375, dpc=133.0625)
    >>> psutil.cpu_times().user
    8277.5625
    >>> psutil.cpu_count(logical=False)
    8
    >>> psutil.cpu_percent(interval=1, percpu=True)
    [18.5, 14.1, 14.1, 4.7]
    

    监控系统内存

    >>> import psutil
    >>> 
    >>> psutil.virtual_memory()
    svmem(total=8457035776, available=5508038656, percent=34.9, used=2948997120, free=5508038656)
    >>> psutil.total
    8457035776
    >>> psutil.free
    5508038656
    >>> psutil.swap_memory()
    sswap(total=9799213056, used=3736629248, free=6062583808, percent=38.1, sin=0, sout=0)
    

    监控系统磁盘

    >>> import psutil
    >>> 
    >>> psutil.disk_usage("C:\\")                #获取指定分区(参数)的使用情况
    sdiskusage(total=115865546752, used=31459299328, free=84406247424, percent=27.2)
    >>> psutil.disk_io_counters()                #获取硬盘总的IO个数,与读写信息
    sdiskio(read_count=1577844, write_count=1529528, read_bytes=71110199808, write_bytes=103924939776, read_time=6624, write_time=8764)
    

    监控网络数据包

    >>> import psutil
    >>> 
    >>> psutil.net_io_counters()
    snetio(bytes_sent=1841534, bytes_recv=11572249, packets_sent=14450, packets_recv=16930, errin=0, errout=0, dropin=0, dropout=0)
    >>> psutil.net_io_counters().bytes_sent
    1841539
    

    管理系统进程信息

    >>> import psutil
    >>> 
    >>> psutil.pids()                      #列出所有进程号
    [0, 4, 360, 544, 636, 708, 716, 808, 880, 304, 384, 1028, 1120]
    >>> 
    >>> p=psutil.Process(1956)             #实例化进程PID
    >>> p.name()                           #取进程名字
    >>> p.num_threads()                    #取进程线程数
    >>> p.memory_percent()                 #取进程利用率
    >>> p.status()                         #进程状态
    >>> p.exe()                            #取bin路径
    >>> p.cwd()                            #进程工作目录绝对路径
    >>> p.io_counters()                    #进程IO信息,包括读写IO数及字节数
    

    文本分词

    #从左到右将字符串解析为标记流(stream of tokens)
    In [17]: text = 'foo = 23 + 42 * 10'
    
    In [18]: tokens= [('NAME','foo'),('EQ','='),('NUM','23'),('PLUS','+'),('NUM','42'),('TIMES','*'),('NUM','
        ...: 10')]
    
    In [19]: import re
    #使用正则表达式
    InIn [20]: NAME = r'(?P<NAME>[a-zA_][a-zA-Z_0-9]*)'
    
    In [21]: NUM = r'(?P<NUM>\d+)'
    
    In [22]: PLUS = r'(?P<PLUS>\+)'
    
    In [23]: TIMES = r'(?P<TIMES>\*)'
    
    In [24]: EQ = r'(?P<EQ>=)'
    
    In [25]: WS = r'(?P<WS>\s+)'
    
    In [26]: master_pat = re.compile('|'.join([NAME,NUM,PLUS,TIMES,EQ,WS]))
    #使用模式对象的scanner()方法来完成分词操作
    In [27]: scanner = master_pat.scanner('foo = 42')
    #在给定的文本中重复调用match()方法,一次匹配一个模式,下面是匹配过程
    In [28]: scanner.match()
    Out[28]: <re.Match object; span=(0, 3), match='foo'>
    
    In [29]: _.lastgroup,_.group()
    Out[29]: ('NAME', 'foo')
    
    In [30]: scanner.match()
    Out[30]: <re.Match object; span=(3, 4), match=' '>
    
    In [31]: _.lastgroup,_.group()
    Out[31]: ('WS', ' ')
    
    In [32]: scanner.match()
    Out[32]: <re.Match object; span=(4, 5), match='='>
    
    In [33]: _.lastgroup,_.group()
    Out[33]: ('EQ', '=')
    
    In [34]: scanner.match()
    Out[34]: <re.Match object; span=(5, 6), match=' '>
    
    In [35]: _.lastgroup,_.group()
    Out[35]: ('WS', ' ')
    
    In [36]: scanner.match()
    Out[36]: <re.Match object; span=(6, 8), match='42'>
    
    In [37]: _.lastgroup,_.group()
    Out[37]: ('NUM', '42')
    #通过生成器函数来转化为代码的形式
    In [40]: from collections import namedtuple
    
    In [41]: token = namedtuple('token',['type','value'])
    
    In [42]: def generate_tokens(pat,text):
        ...:     scanner = pat.scanner(text)
        ...:     for m in iter(scanner.match,None):
        ...:         yield token(m.lastgroup,m.group())
        ...:         
    
    In [43]: for tok in generate_tokens(master_pat,'foo = 42'):
        ...:     print(tok)
        ...:     
    token(type='NAME', value='foo')
    token(type='WS', value=' ')
    token(type='EQ', value='=')
    token(type='WS', value=' ')
    token(type='NUM', value='42')
    #过滤空格标记
    In [45]: tokens = (tok for tok in generate_tokens(master_pat,text) if tok.type != 'WS')
    
    In [46]: for tok in tokens:print(tok)
    token(type='NAME', value='foo')
    token(type='EQ', value='=')
    token(type='NUM', value='23')
    token(type='PLUS', value='+')
    token(type='NUM', value='42')
    token(type='TIMES', value='*')
    token(type='NUM', value='10')
    

    编写一个简单的递归下降解析器

    import re
    import collections
    
    #定义文本分词变量
    NUM = r'(?P<NUM>\d+)'
    PLUS = r'(?P<PLUS>\+)'
    MINUS = r'(?P<MINUS>-)'
    TIMES = r'(?P<TIMES>\*)'
    DIVIDE = r'(?P<DIVIDE>/)'
    LPAREN = r'(?P<LPAREN>\()'
    RPAREN = r'(?P<RPAREN>\))'
    WS = r'(?P<WS>\s+)'
    
    master_pat = re.compile('|'.join([NUM,PLUS,MINUS,TIMES,DIVIDE,LPAREN,RPAREN,WS]))
    Token = collections.namedtuple('Token',['type','value'])
    
    #过滤文本分词
    def generate_tokens(text):
        scanner = master_pat.scanner(text)
        for m in iter(scanner.match,None):
            tok = Token(m.lastgroup,m.group())
            if tok.type != 'WS':
                yield tok
    
    class ExpressionEvaluator:
        def parse(self,text):
            self.tokens = generate_tokens(text)
            self.nexttok = None
            self.tok = None
            self._advance()
            return self.expr()
    
        def _advance(self):
            self.tok,self.nexttok = self.nexttok,next(self.tokens,None)
        def _accept(self,toktype):
            if self.nexttok and self.nexttok.type == toktype:
                self._advance()
                return True
            else:
                return False
        def _expect(self,toktype):
            if not self._accept(toktype):
                raise SyntaxError('Expected' + toktype)
    
        def expr(self):
            exprval = self.term()
            while self._accept('PLUS') or self._accept('MINUS'):
                op = self.tok.type
                right = self.term()
                if op == 'PLUS':
                    exprval += right
                elif op == 'MINUS':
                    exprval -= right
            return exprval
    
        def term(self):
            termval = self.factor()
            while self._accept('TIMES') or self._accept('DIVIDE'):
                op = self.tok.type
                right = self.factor()
                if op == 'TIMES':
                    termval *= right
                elif op == 'DIVIDE':
                    termval /= right
            return termval
    
        def factor(self):
            if self._accept('NUM'):
                return int(self.tok.value)
            elif self._accept('LPAREN'):
                exprval = self.expr()
                self._expect('RPAREN')
                return exprval
            else:
                raise SyntaxError('Expected NUMBER or LPAREN')
    
    
    if __name__ == '__main__':
        e = ExpressionEvaluator()
        print(e.parse('2'))
        print(e.parse('2 + 3'))
        print(e.parse('2 + 3 * 4'))
        print(e.parse('2 + (3 + 4) * 5'))
    

    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)
    
    原文链接:https://blog.csdn.net/weixin_44099558/java/article/details/85775937
    

    下载阿里云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()
    
    

     

    展开全文
  • 一、ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。(提示,使用ps aux 列出所有进程,过滤出RSS那列,然后求和)注:ps -ef 与 ps aux 效果一样使用随意import oslist = []sum = ...

    一、ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。

    (提示,使用ps aux 列出所有进程,过滤出RSS那列,然后求和)

    注:ps -ef 与 ps aux 效果一样使用随意

    import os

    list = []

    sum = 0

    str1 = os.popen("ps aux","r").readlines()

    for i in str1:

    str2 = i.split()

    new_rss = str2[5]

    list.append(new_rss)

    for i in list[1:-1]:

    num = int(i)

    sum = sum + num

    print "%s:%s" %(list[0],sum)

    二、一键部署lvs与keepalived

    注:部署keepalived配置文件,会自动将lvs部署好,不必单独搭建,但是要下载好ipvsadm

    这里单独搭建了lvs

    #提前配置好免密钥登陆,与apache服务

    import pexpect

    import os

    ds_ip = "192.168.102.143"

    rs1_ip = "192.168.102.144"

    rs2_ip = "192.168.102.145"

    vip = "192.168.102.250"

    ds_cmd = ["ipvsadm -C",

    "ipvsadm -A -t {vip}:80 -s rr".format(vip=vip),

    "ipvsadm -a -t {vip}:80 -r {rs1_ip}:80 -g".format(vip=vip, rs1_ip=rs1_ip),

    "ipvsadm -a -t {vip}:80 -r {rs2_ip}:80 -g".format(vip=vip,rs2_ip=rs2_ip),

    "ifconfig ens33:0 {vip} broadcast {vip} netmask 255.255.255.255 up".format(vip=vip),

    "route add -host {vip} dev ens33:0".format(vip=vip)

    ]

    # for ds_cmd in ds_cmd:

    rs1_cmd = [

    "ansible rs1 -m shell -a "ifconfig lo:0 {vip} broadcast {vip} netmask 255.255.255.255 up" &>/dev/null".format(vip=vip),

    "ansible rs1 -m shell -a "route add -host {vip} dev lo:0" &>/dev/null".format(vip=vip),

    "ansible rs1 -m shell -a "echo "1" > /proc/sys/net/ipv4/conf/lo/arp_ignore" &>/dev/null",

    "ansible rs1 -m shell -a "echo "2" > /proc/sys/net/ipv4/conf/lo/arp_announce" &>/dev/null",

    "ansible rs1 -m shell -a "echo "1" > /proc/sys/net/ipv4/conf/all/arp_ignore" &>/dev/null",

    "ansible rs1 -m shell -a "echo "2" > /proc/sys/net/ipv4/conf/all/arp_announce" &>/dev/null",

    "service httpd restart"]

    # for rs_cmd in rs_cmd:

    rs2_cmd = [

    "ansible rs2 -m shell -a "ifconfig lo:0 {vip} broadcast {vip} netmask 255.255.255.255 up" &>/dev/null".format(vip=vip),

    "ansible rs2 -m shell -a "route add -host {vip} dev lo:0" &>/dev/null".format(vip=vip),

    "ansible rs2 -m shell -a "echo "1" > /proc/sys/net/ipv4/conf/lo/arp_ignore" &>/dev/null",

    "ansible rs2 -m shell -a "echo "2" > /proc/sys/net/ipv4/conf/lo/arp_announce" &>/dev/null",

    "ansible rs2 -m shell -a "echo "1" > /proc/sys/net/ipv4/conf/all/arp_ignore" &>/dev/null",

    "ansible rs2 -m shell -a "echo "2" > /proc/sys/net/ipv4/conf/all/arp_announce" &>/dev/null",

    "service httpd restart"]

    ansible="""

    echo "[rs1]" >> /etc/ansible/hosts;

    echo "{rs1_ip}" >> /etc/ansible/hosts;

    echo "[rs2]" >> /etc/ansible/hosts;

    echo "{rs2_ip}" >> /etc/ansible/hosts;

    """.format(rs1_ip=rs1_ip,rs2_ip=rs2_ip)

    def Ansible():

    res = os.system("yum install ansible -y &>/dev/null")

    if res== 0:

    print("ansible安装完成!")

    os.system(ansible)

    def lvs():

    i = os.system("yum -y install ipvsadm &>/dev/null")

    if i == 0:

    print("lvs下载完成")

    for a in ds_cmd:

    res = os.system(a)

    if res == 0:

    print("ok")

    else:

    print("false")

    for b in rs1_cmd:

    res1 = os.system(b)

    if res1 == 0:

    print("ok")

    else:

    print("false")

    for c in rs2_cmd:

    res2 = os.system(c)

    if res2 == 0:

    print("ok")

    else:

    print("false")

    else:

    print("lvs下载失败")

    keepalived = """

    #全局配置

    ! Configuration File for keepalived

    #全局配置

    global_defs {

    notification_email {

    #收件人地址

    }

    #邮件服务器

    }

    VRRP配置DS1

    vrrp_instance VI_1 {

    state MASTER #角色类型MASTER|BACKUP

    interface ens33 #网卡名称

    virtual_router_id 51 #虚拟路由id(需要与BACKUP一致)

    priority 100 #优先级

    advert_int 1 #没1秒检查一次

    #nopreempt #非抢占模式

    authentication {

    auth_type PASS #认证类型 主备之间必须一样

    auth_pass 1111 #认证密码 主备之间必须一样

    }

    virtual_ipaddress {

    192.168.102.250 #虚拟ip(vip)

    }

    }

    #LVS配置

    virtual_server 192.168.102.250 80 {

    delay_loop 3 #健康检查时间间隔

    lb_algo rr #负载均衡调度算法

    lb_kind DR #负载均衡转发规则

    protocol TCP #协议

    real_server 192.168.102.144 80 { #要监控的real_server的ip和端口号

    weight 1 #权重

    TCP_CHECK { #基于tcp协议的检查

    connect_timeout 3 #连接时间超时

    retry 3 #重连次数

    delay_before_retry 3 #重连间隔时间

    }

    }

    real_server 192.168.102.145 80 {

    weight 1

    TCP_CHECK {

    connect_timeout 3

    retry 3

    delay_before_retry 3

    }

    }

    }"""

    def Keepalived():

    d = os.system("yum install keepalived -y &> /dev/null")

    if d == 0:

    print("keeplived下载完成")

    with open(r"/etc/keepalived/keepalived.conf", "w", encoding="utf-8") as f:

    f.write(keepalived)

    e = os.system("systemctl start keepalived")

    if e == 0:

    print("keepalived部署完成!")

    else:

    print("keepalived部署失败")

    else:

    print("keepalived下载失败")

    def main():

    # key()

    Ansible()

    # ssh_copy()

    lvs()

    Keepalived()

    if __name__ == "__main__":

    main()

    三、用python3编写一个监控上面lvs服务状态和系统资源的脚本

    import yagmail

    import paramiko

    import socket

    import re

    import time

    ssh = paramiko.SSHClient()

    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    rs1_ip = "192.168.102.144"

    rs2_ip = "192.168.102.145"

    ds_ip = "192。168.102.143"

    disk_cmd = "df -m | grep /dev/sda1 | awk "{print $4}""

    cpu_cmd = """

    top n 1 d 1 b -p 1 | grep "%Cpu" | awk -F "," "{print $4}" | awk -F "id" "{print $1}" | awk -F "." "{print $1}"

    """

    free_cmd = "free -m | grep Mem |awk "{print $7}""

    def connect1():

    ssh.connect("{rs1_ip}".format(rs1_ip=rs1_ip), 22, "root", "1", timeout=3)

    def connect2():

    ssh.connect("{rs2_ip}".format(rs2_ip=rs1_ip), 22, "root", "1", timeout=3)

    def mail(head, Contents):

    yag = yagmail.SMTP(user="15898297124@163.com", password="zz54605519", host="smtp.163.com")

    yag.send("15898297124@163.com",subject = head, contents = Contents)

    yag.close()

    def http():

    socket.setdefaulttimeout(1)

    server = socket.socket()

    host_list = ["%s:80" % (rs1_ip),"%s:80" % (rs2_ip)]

    for info in host_list:

    ip = re.compile("(.*?):(.*)").search(info).group(1)

    port = re.compile("(.*?):(.*)").search(info).group(2)

    res = server.connect_ex((ip, int(port)))

    if res != 0:

    mail(ip,"%s不通" % port)

    def disk():

    connect1()

    stdin1, stdout1, stderr1 = ssh.exec_command(disk_cmd)

    disk1 = int(stdout1.read().decode("utf-8"))

    print("%s节点disk剩余空间为%sM" % (rs1_ip,disk1))

    if disk1 <= 200:

    mail(rs1_ip,"disk剩余空间为%sM" % disk1)

    connect2()

    stdin2, stdout2, stderr2 = ssh.exec_command(disk_cmd)

    disk2 = int(stdout2.read().decode("utf-8"))

    print("%s节点disk剩余空间为%sM" % (rs2_ip, disk2))

    if disk2 <= 200:

    mail(rs2_ip, "disk剩余空间为%sM" % disk2)

    def cpu():

    connect1()

    stdin1, stdout1, stderr1 = ssh.exec_command(cpu_cmd)

    cpu1 = int(stdout1.read().decode("utf-8"))

    cpu = 100 - cpu1

    print("%s节点cpu使用率为百分之%s" % (rs1_ip, cpu))

    if cpu >= 80:

    mail(rs1_ip, "cpu使用量为%s" % cpu)

    connect2()

    stdin2, stdout2, stderr2 = ssh.exec_command(cpu_cmd)

    cpu2 = int(stdout2.read().decode("utf-8"))

    cpu = 100 - cpu2

    print("%s节点cpu使用率为百分之%s" % (rs2_ip, cpu))

    if cpu >= 80:

    mail(rs2_ip, "cpu使用量为%s" % cpu)

    def free():

    connect1()

    stdin1, stdout1, stderr1 = ssh.exec_command(free_cmd)

    free1 = int(stdout1.read().decode("utf-8"))

    print("%s节点磁盘剩余空间为%sM" % (rs1_ip, free1))

    if free1 <= 200:

    mail(ds_ip, "磁盘剩余空间为%sM" % free1)

    connect2()

    stdin2, stdout2, stderr2 = ssh.exec_command(disk_cmd)

    free2 = int(stdout2.read().decode("utf-8"))

    print("%s节点磁盘剩余空间为%sM" % (rs2_ip, free2))

    if free2 <= 200:

    mail(ds_ip, "磁盘剩余空间为%sM" % free2)

    def main():

    while True:

    http()

    cpu()

    free()

    disk()

    time.sleep(60)

    if __name__ == "__main__":

    main()

    四、用python编写一键部署数据库主从服务

    主服务器

    import pexpect

    import os

    import configparser

    # HOSTNAME_DB1="db1"

    # HOSTNAME_DB2="db2"

    # DB1 = "192.168.254.24"

    # DB2 = "192.168.254.27"

    DBPASSWORD = "1"

    def repo():

    os.system("touch /etc/yum.repos.d/mariadb.repo")

    with open("/etc/yum.repos.d/mariadb.repo","w",encoding="utf8") as f:

    f.write("[mariadb]")

    config = configparser.ConfigParser()

    config.read("/etc/yum.repos.d/mariadb.repo", encoding="utf-8")

    config.set("mariadb", "name", "MariaDB")

    config.set("mariadb", "baseurl", "http://mirrors.ustc.edu.cn/mariadb/yum/10.3/centos7-amd64/")

    config.set("mariadb", "gpgkey", "http://mirrors.ustc.edu.cn/mariadb/yum/RPM-GPG-KEY-MariaDB")

    config.set("mariadb", "gpgcheck", "1")

    config.write(open("/etc/yum.repos.d/mariadb.repo","w"))

    def mariadb():

    a = os.system("yum install MariaDB -y &> /dev/null")

    if a == 0:

    b = os.system("systemctl start mariadb &> /dev/null")

    if b == 0:

    print("mariadb启动成功")

    child = pexpect.spawn("mysql_secure_installation")

    child.expect("enter for none")

    child.sendline("")

    child.expect("Y/n")

    child.sendline("y")

    child.expect("New")

    child.sendline(DBPASSWORD)

    child.expect("Re-enter")

    child.sendline(DBPASSWORD)

    child.expect("successfully")

    child.sendline("")

    child.sendline("")

    child.sendline("")

    child.sendline("")

    child.interact()

    child.close()

    def db1():

    config = configparser.ConfigParser()

    config.read("/etc/my.cnf.d/server.cnf", encoding="utf-8")

    config.set("mysqld", "server-id", "1")

    config.set("mysqld", "log-bin", "mysql-bin")

    config.write(open("/etc/my.cnf.d/server.cnf","w"))

    b = os.system("systemctl restart mariadb")

    if b == 0:

    # os.system("mysql -uroot -p%s" % DBPASSWORD)

    # os.system("CREATE USER "slave"@"%" IDENTIFIED BY "slave";")

    # os.system("GRANT REPLICATION SLAVE ON *.* TO "slave"@"%";")

    # os.system("flush privileges;")

    # os.system("show master status")

    child = pexpect.spawn("mysql -uroot -p1")

    child.expect("none")

    child.sendline("CREATE USER "slave"@"%" IDENTIFIED BY "slave";")

    child.expect("none")

    child.sendline("GRANT REPLICATION SLAVE ON *.* TO "slave"@"%";")

    child.expect("none")

    child.sendline("flush privileges;")

    child.expect("none")

    child.sendline("show master status;")

    child.interact()

    child.close()

    def main():

    repo()

    mariadb()

    db1()

    if __name__ == "__main__":

    main()

    从服务器

    import pexpect

    import os

    import configparser

    # HOSTNAME_DB1="db1"

    # HOSTNAME_DB2="db2"

    DB1 = "192.168.102.143"

    # DB2 = "192.168.254.27"

    DBPASSWORD = "1"

    def repo():

    os.system("touch /etc/yum.repos.d/mariadb.repo")

    with open("/etc/yum.repos.d/mariadb.repo","w",encoding="utf8") as f:

    f.write("[mariadb]")

    config = configparser.ConfigParser()

    config.read("/etc/yum.repos.d/mariadb.repo", encoding="utf-8")

    config.set("mariadb", "name", "MariaDB")

    config.set("mariadb", "baseurl", "http://mirrors.ustc.edu.cn/mariadb/yum/10.3/centos7-amd64/")

    config.set("mariadb", "gpgkey", "http://mirrors.ustc.edu.cn/mariadb/yum/RPM-GPG-KEY-MariaDB")

    config.set("mariadb", "gpgcheck", "1")

    config.write(open("/etc/yum.repos.d/mariadb.repo","w"))

    def mariadb():

    a = os.system("yum install MariaDB -y")

    if a == 0:

    b = os.system("systemctl start mariadb &> /dev/null")

    if b == 0:

    print("mariadb启动成功")

    child = pexpect.spawn("mysql_secure_installation")

    child.expect("enter for none")

    child.sendline("")

    child.expect("Y/n")

    child.sendline("y")

    child.expect("New")

    child.sendline(DBPASSWORD)

    child.expect("Re-enter")

    child.sendline(DBPASSWORD)

    child.expect("successfully")

    child.sendline("")

    child.sendline("")

    child.sendline("")

    child.sendline("")

    def db2():

    config = configparser.ConfigParser()

    config.read("/etc/my.cnf.d/server.cnf", encoding="utf-8")

    config.set("mysqld", "server-id", "2")

    config.write(open("/etc/my.cnf.d/server.cnf","w"))

    b = os.system("systemctl restart mariadb")

    if b == 0:

    bin = "mysql-bin.000001"

    pos = 765

    # os.system("mysql -uroot -p%s" % DBPASSWORD)

    # os.system("""mysql -uroot -p%s -e "CHANGE MASTER TO MASTER_HOST="%s", MASTER_USER="slave", MASTER_PASSWORD="slave", MASTER_LOG_FILE="%s", MASTER_LOG_POS=%s;"""" % (DBPASSWORD,DB1,bin,pos))

    # os.system("mysql -uroot -p%s -e "start slave;"" % DBPASSWORD)

    child = pexpect.spawn("mysql -uroot -p%s" % DBPASSWORD)

    child.expect("none")

    child.sendline("CHANGE MASTER TO MASTER_HOST="%s", MASTER_USER="slave", MASTER_PASSWORD="slave", MASTER_LOG_FILE="%s", MASTER_LOG_POS=%s;" % (DB1,bin,pos))

    child.expect("none")

    child.sendline( "start slave;" )

    child.interact()

    child.close()

    def main():

    repo()

    mariadb()

    db2()

    if __name__ == "__main__":

    main()

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    展开全文
  • 背景 最近在Windows 10上使用Linux子系统,发现它有一个非常坑爹的特点:Linux子系统是没有开机关机状态的,...Python脚本还是比shell脚本好写很多啊。 转载于:https://my.oschina.net/yixian/blog/740182
  • 背景 最近在Windows 10上使用Linux子系统,发现它有一个非常坑爹的特点:Linux子系统是没有开机关机状态的,每次进入Bash shell就自动载入,退出后Linux子系统的...Python脚本还是比shell脚本好写很多啊。
  • Python运维脚本整理

    千次阅读 2019-01-01 17:26:00
    Python 批量遍历目录文件,并修改访问时间 >>> path="D:/UASM64/include/" >>> dirs = os.listdir(path) >>> for file in dirs: ... print(os.path.join(path,file)) import os path = ...
  • 说明:dnspython模块 实现DNS的工具包,几乎支持所有的记录类型,可用于查询,传输并动态更新zone信息 系统管理方面,可以利用其查询功能实现DNS服务监控以及解析结果的校验 功能:最常用的是域名查询,dnspython...
  • 几个python运维脚本

    2017-11-08 16:34:00
    这是我以前写过的一个清除备份文件的小程序,本来想用批处理来做,但批处理的语法又复杂有怪异,最终还是拿python写了一个 因为我们的游戏每隔一小时就会自动产生一个备份,这个程序的作用是跳过最新的7*24个备份,...
  • 删除和清空文件,用shell的话一条命令就够了,Python要一堆命令。 但是为了学习Python,所以用于实战,就得这么干了。...# 该脚本用于清空文件和删除文件 import os, sys import time def truncate_fi...
  • 1.通过netmiko模块登录交换机,协议ssh,执行收集信息命令,保存至txt文件2.过滤txt文件中的内容,保存到excel,使用xlwt模块实现。.../usr/bin/python3#H3c交换机import timefrom netmiko import ConnectHandler...
  • /usr/bin/python3 from flask import Flask,request import time import os app = Flask(__name__) #app.debug = True @app.route('/delete_pic',methods=['POST']) def deletePic(): file_path = '/data/pic/snap'...
  • 概述Pexpect 是 Don Libes 的 Expect 语言的一个 Python 实现,是一个用来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的 Python 模块。 Pexpect 的使用范围很广,可以用来实现与 ssh...
  • 下面列举五大python运维脚本面试题,让你在职场加分。python常用的运维脚本面试题有哪些?file是一个类,使用file('file_name', 'r+')这种方式打开文件,返回一个file对象,以写模式打开文件不存在则会被创建。但是...
  • /usr/bin/env python3# -*- coding: utf-8 -*-# @Time : 2018-12-18 15:16# @Author : opsonly# @Site :# @File : opsUse.py# @Software: PyCharmimport osdir = "/var/www/html/EnjoyCarApi/”if os...
  • 原标题:五个python常用运维脚本面试题实例一、用Python写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径#!/usr/bin/envpythonimport osfor root,dirs,files in os.walk('/tmp'):for name in files:...
  • 原文链接:https://bbs.huaweicloud.com/blogs/16f870b109a911e9bd5a7ca23e93a891github地址:https://github.com/opsonly, 上面是一个基于python3.7和django2.1的多人博客.../usr/bin/env python3# -*- coding: u...
  • #提前配置好免密钥登陆,与apache服务import pexpectimport osds_ip= '192.168.102.143'rs1_ip= '192.168.102.144'rs2_ip= '192.168.102.145'vip= '192.168.102.250'ds_cmd= ['ipvsadm -C','ipvsadm -A -t {vip}:80 ...
  • 1.列举当前目录以及所有子目录下的文件,并打印出绝对.../usr/bin/python# coding=utf8import osimport sys if len(sys.argv) ;."else: filepath=sys.argv[1]for root,dirs,files in os.walk(filepath): for fi...
  • 一、ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。(提示,使用ps aux 列出所有进程,过滤出RSS那列,然后求和)注:ps -ef 与 ps aux 效果一样使用随意import oslist = []sum = ...
  • 题主明明在问怎么用python运维,为何要争论python和shell到底谁强呢?要比的话,我来引用下神仙们的看法Guido van Rossum:"All you can do with a shell script is make it worse. But since this is Python, ...
  • /usr/bin/python3# -*- coding:UTF-8-*-# Author: zhuhongqiangfrom urllib import requestimport jsonfrom sys import argvaccess_token = "xxx"def send_msg(mobile, item_name):""&qu...
  • 主要介绍了python常用运维脚本实例小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • Python运维常用脚本

    2020-03-29 19:38:51
    /usr/bin/env python3 import redis #选择连接的数据库 db = input(‘输入数据库:’) r = redis.Redis(host=‘127.0.0.1’,port=6379,db=0) #输入要匹配的键名 id = input(‘请输入要执匹配的字段:’) arg = ‘’ +...
  • python运维常用脚本

    2019-11-07 15:07:29
    /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.isd...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,532
精华内容 612
关键字:

python运维脚本

python 订阅