標籤:python j監控伺服器磁碟空間
寫了個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)
python指令碼監控磁碟空間