最近需要看几台服务器的信息,懒得ssh登录和从网页进行查看。写了个小脚本定期向自己的邮箱发送统计状态。
# -*- coding:utf-8 -*-
#__author__ = 'ecaoyng'
# date : 20170601
import paramiko
import commands
import datetime
import time
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
class ITKMonitor:
def __init__(self):
# nwids name
self.nwids=['te2se','tlise']
# rnc pm status
self.pmRNC={'te2se':'',
'tlise':''}
# web server info
self.web={'IP':'131.160.56.xx',
'User':'itk',
'Pwd':'itkuser'}
# te2se's Process server info
self.te2seProc={'IP':'131.160.56.xx',
'User':'itk',
'Pwd':'itkuser'}
# te2se's DB server info
self.te2seDB={'IP':'131.160.56.xx',
'User':'itk',
'Pwd':'itkuser'}
# tlise's Process server info
self.tliseProc={'IP':'131.160.56.xx',
'User':'root',
'Pwd':'itk10R2014'}
# tlise's Db server info
self.tliseDB={'IP':'131.160.56.xx',
'User':'root',
'Pwd':'itk11R2014'}
# server list
self.severList=[self.web,self.te2seProc,self.te2seDB,self.tliseProc,self.tliseDB]
# Time of 2 hours ago
self.last2Hour=''
# smtp mail infor
self.stmpServer='smtp.eapac.ericsson.se'
self.sender = 'young.yang@ericsson.com'
self.receiver = 'young.yang@ericsson.com'
self.mailContent = []
# get time of 2 hours ago
def get_last2hours(self):
self.last2Hour=((datetime.datetime.now() - datetime.timedelta(minutes=120)).strftime("%Y-%m-%d %H:%M"))
# check pm status
def te2se_check_pm(self):
for nwid in self.nwids:
cmd='itkadmin pmstatus -nwid ' + nwid +' -starttime '+'\''+self.last2Hour+'\'' +' -resolution q -timeagg qhr -node allrnc'
(status, output) = commands.getstatusoutput(cmd)
if status == 0:
self.pmRNC[nwid]=output
else:
print('Errors during exec itkadmin pmstatus... for' + nwid)
# show pm status of rnc
def show_rnc_pm(self):
for key in self.pmRNC.keys():
print('%s => %s' % (key, self.pmRNC[key]))
self.mailContent.append('%s => %s' % (key, self.pmRNC[key]))
self.mailContent.append('\r\n')
print('-'*60)
self.mailContent.append('='*100)
self.mailContent.append('\r\n')
# analyis pm status of rnc
# def analysis_rnc_pm(self):
# for key in self.pmRNC.keys():
# result=self.pmRNC[key][self.pmRNC[key].rfind('Object'):]
# awkCmd='result | awk \'print \$2\''
# (awkStat, awkOut) = commands.getstatusoutput(awkCmd)
# print(awkOut)
def sshclient_execmd(self, execmd):
paramiko.util.log_to_file("paramiko.log")
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for server in self.severList:
print('%s hardware information' % server)
self.mailContent.append('%s hardware information' % server)
self.mailContent.append('\r\n')
s.connect(hostname= server['IP'], port=22, username=server['User'], password=server['Pwd'])
stdin, stdout, stderr = s.exec_command(execmd)
stdin.write("Y") # The first connection, need a simple interaction.
cmdOutput=stdout.read()
print(cmdOutput)
self.mailContent.append(cmdOutput)
self.mailContent.append('\r\n')
print('='*60)
self.mailContent.append('='*100)
self.mailContent.append('\r\n')
time.sleep(2)
print ('mail content is %s' % self.mailContent)
s.close()
# send email
def send_mail(self):
resp= True
try:
msg = MIMEText(''.join(self.mailContent), 'plain', 'utf-8')
msg['Subject'] = 'RECA ITK information'
smtp = smtplib.SMTP(self.stmpServer, 25)
smtp.sendmail(self.sender, [self.receiver,‘xxx@xx.com’], msg.as_string())
smtp.quit()
print('Succeed to send email.')
except Exception as e:
print (e)
resp = False
return resp
if __name__== '__main__':
monitor=ITKMonitor()
monitor.sshclient_execmd('df -h')
monitor.get_last2hours()
monitor.te2se_check_pm()
monitor.show_rnc_pm()
monitor.send_mail()
# monitor.analysis_rnc_pm()
需要注意的是需要安装一些依赖包
yum install python-devel.x86_64
yum install openssl-devel
yum install libffi-devel
#安装paramiko
tar -xzvf paramiko-2.0.2.tar.gz
cd paramiko-2.0.2
python setup.py install
如果缺少其他包,请自行安装