写了个python小程序,监控磁盘空间,前面部分网上也有很多,写博客的目的是记录下来,已供自己后面使用,思路就是用pexpect 这个模块,ssh到不同的机器上,查到磁盘空间,最后对查到的结果进行处理,然后存到mysql数据中。以下是代码:
#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([pexpect.TIMEOUT, ssh_newkey, ‘password: ‘])
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([pexpect.TIMEOUT, ‘password: ‘])
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[0],serverM[1],serverM[2], ‘df -h‘)
# 匹配 pexpect.EOF
child.expect(pexpect.EOF)
# 输出命令结果.
#print serverM[1]+" 磁盘空间如下:"
#print child.before
f.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:
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[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=""" " """ %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[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 mysql
os.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)
原文地址:http://itsoar.blog.51cto.com/8915220/1643883