您的位置:首页 > 编程语言 > Python开发

python脚本监控磁盘空间

2015-05-07 15:30 399 查看
写了个python小程序,监控磁盘空间,前面部分网上也有很多,写博客的目的是记录下来,已供自己后面使用,思路就是用pexpect 这个模块,ssh到不同的机器上,查到磁盘空间,最后对查到的结果进行处理,然后存到mysql数据中。以下是代码:
#coding=utf8import pexpectimport getpass,os,sysimport re,datetime, timedef 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([pexpect.TIMEOUT, ssh_newkey, 'password: '])if i == 0: # Timeoutprint child.before, child.afterreturn 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([pexpect.TIMEOUT, 'password: '])if i == 0: # Timeoutprint child.before, child.afterreturn None# 输入密码.child.sendline(password)return childdef 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:breakfor line in lines:serverM=line.split(',')child = ssh_command (serverM[0],serverM[1],serverM[2], 'df -h')# 匹配 pexpect.EOFchild.expect(pexpect.EOF)# 输出命令结果.#print serverM[1]+" 磁盘空间如下:"#print child.beforef.write(serverM[1])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:breakfor 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[len(line)-13:len(line)-10])a.append(line[len(line)-19:len(line)-14])a.append(line[len(line)-25:len(line)-20])file.close()mysql=""" " """ %dateos.system(mysql)i= len(a)/4while i>0:i=i-1mysql1=""" mysql  -hip -P3358 -u用户名-p密码 -D数据库 -e "insert into 表名 values(%s,'%s','%s','%s','%s')" """ %(date,a[0+4*i],a[3+4*i],a[2+4*i],a[1+4*i])#print a[0+4*i]#print a[1+4*i]#print a[2+4*i]#print mysqlos.system(mysql1)if __name__ == '__main__':if (len(sys.argv) > 1):y_date = sys.argv[1]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)
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: