fdfdfwe 发表于 2015-5-8 08:54:04

python脚本监控磁盘空间

写了个python小程序,监控磁盘空间,前面部分网上也有很多,写博客的目的是记录下来,已供自己后面使用,思路就是用pexpect 这个模块,ssh到不同的机器上,查到磁盘空间,最后对查到的结果进行处理,然后存到mysql数据中。以下是代码:
1
<br>




#coding=utf8
import pexpect
import getpass,os,sys
import re,datetime, time

def ssh_command (user, host, password, command):
    ssh_newkey = 'Are you sure you want to continue connecting'
    child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
    i = child.expect()
    if i == 0: # Timeout
      print child.before, child.after
      return None
    # 如果 ssh 没有 public key,接受它.
    if i == 1: # SSH does not have the public key. Just accept it.
      child.sendline ('yes')
      child.expect ('password: ')
      i = child.expect()
      if i == 0: # Timeout
            print child.before, child.after
            return None
    # 输入密码.
    child.sendline(password)
    return child

def main (date):

    base='ip文件'
    wbase='保存文件名'
    file=open(base)
    f=open(wbase,"w")
    #raw_command = raw_input("输入命令: ")
    while 1:
        lines = file.readlines(10000)
        if not lines:
                break
        for line in lines:
                serverM=line.split(',')
                       child = ssh_command (serverM,serverM,serverM, 'df -h')
                # 匹配 pexpect.EOF
                    child.expect(pexpect.EOF)
                # 输出命令结果.
                #print serverM+" 磁盘空间如下:"
                    #print child.before
                f.write(serverM)
                f.write(child.before)
    f.close()
    file.close()
    readLine(wbase,date)
def readLine(base,date):
    file = open(base)
    a=[]
    while 1:
      lines = file.readlines(10000)
      if not lines:
            break
      for line in lines:
            ob=re.search('\d*[.]\d*[.]\d*[.]\d*',line)
            oe=re.search('/export',line)
            if ob:
                a.append(ob.group(0))
            if oe:
                a.append(line)
                a.append(line)
                a.append(line)


    file.close()
    mysql=""" " """ %date
    os.system(mysql)
    i= len(a)/4
    while i>0:
         i=i-1
         mysql1=""" mysql-hip -P3358 -u用户名-p密码 -D数据库 -e "insert into 表名 values(%s,'%s','%s','%s','%s')" """ %(date,a,a,a,a)
         #print a
         #print a
         #print a
         #print mysql

         os.system(mysql1)


if __name__ == '__main__':
    if (len(sys.argv) > 1):
         y_date = sys.argv
    else:
         y_date = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d")
    try:
      main(y_date)
    except Exception, e:
      print str(e)
      traceback.print_exc()
      os._exit(1)

页: [1]
查看完整版本: python脚本监控磁盘空间