`
gqh36gqh
  • 浏览: 16065 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

python 实现多台UNIX服务器自动巡检

 
阅读更多

python 实现多台UNIX服务器自动巡检
2012年01月06日
  工作需要,每天要对系统内的多台LINUX服务器做巡检,主要检查的内容有CPU,内存,进程,硬盘空间等。
  想来想去觉得还是用PYTHON来实现比较容易。平台移植性比较好。
  查了很多关于PYTHON SSH联接的文档。需要用到pexpect 或paramiko  中的一个包,后来发现这两个包安装到WINDOW下比较麻烦。
  经过多次偿试未成功。(实在没办法,很好的东西,哪位高手用成功了,可以交流交流。)最终选定用TELENET来实现,还好平台内网都支持TELNET。
  进入正题:
  思路如下:每天自动联接到服务器上运行服务器的命令。然后把结果存储到文件中,最后把结果发邮件出来。
  主程序:autoMonitor.py
  import ConfigParser
  import base64,time,telnetlib,os,struct,smtplib
  from email.MIMEText import MIMEText
  from email.MIMEMultipart import MIMEMultipart
  def WriteLog(filename,tmpstr):
  time_str = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
  logstr = str(tmpstr) + '\n'
  f = open(filename,"a")
  f.write(logstr)
  f.close()
  def getConfigFile(configFile):
  iconfs=[]
  Config = ConfigParser.ConfigParser()
  Config.read(configFile)
  confFiles=Config.items("Config")
  for conf in confFiles:
  iconfs.append(conf[1])
  return iconfs
  def readConfig(configFile):
  coms=[]
  Config = ConfigParser.ConfigParser()
  Config.read(configFile)
  host = Config.get("BASEINFO","HOST")
  user = Config.get("BASEINFO","USERNAME")
  pwd = base64.b64decode(Config.get("BASEINFO","PASSWORD"))
  poi = Config.get("BASEINFO","POINTING")
  commands = Config.items("COMMANDS")
  for com in commands:
  coms.append(com[1])
  return host,user,pwd,poi,coms
  def TelNet(host,user,pwd,poi,coms,outprintFile):
  time_str = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
  WriteLog(outprintFile,host+"       \n" + time_str)
  tn=telnetlib.Telnet(host)
  tn.read_until("login:")
  tn.write(user+"\n")
  if pwd:
  tn.read_until("Password:")
  tn.write(pwd + "\n")
  #    print "tn.pwd\n"
  tn.write("vt100\n")
  tn.read_until(poi)
  for com in coms:
  #        if poi=="$":
  print poi
  tn.write(com + "\n")
  abc = tn.read_until(poi)
  print abc
  WriteLog(outprintFile,abc)
  #        time.sleep(1)
  tn.write("exit\n")
  #    print "exit\n"
  #    print "test\n"
  #print tn.read_all()
  #    tn.interact()
  WriteLog(outprintFile,tn.read_all())  
  tn.close
  WriteLog(outprintFile,"======================================================================================\n")
  print "host=" + host + "checked OK!"
  def getMailConfig(configFile):
  coms=[]
  Config = ConfigParser.ConfigParser()
  Config.read(configFile)
  host = Config.get("FROM","HOST")
  user = Config.get("FROM","USERNAME")
  subject = Config.get("FROM","SUBJECT")
  pwd = base64.b64decode(Config.get("FROM","PASSWORD"))
  commands = Config.items("TO")
  for com in commands:
  coms.append(com[1])
  return host,user,pwd,subject,coms
  def SendMail(configFile,sendfile):
  host,user,pwd,subject,coms=getMailConfig(configFile)
  _tos=""
  for _to in coms:
  _tos = _tos + _to + ";"
  msg = MIMEMultipart()
  # att = MIMEText("test mail")
  att = MIMEText(open(sendfile,'rb').read(),'base64','gb2312')
  att["Content-Type"] ='application/octet-stream'
  att["Content-Disposition"]='attachment;filename="'+sendfile+'"'
  #    msg.attach(att)
  #    msg['to']=coms
  msg['from']=user
  msg['to']=_tos
  msg['subject']=subject
  msg.attach(att)
  try:
  smtp_svr=smtplib.SMTP()
  smtp_svr.connect(host,"25")
  except (smtplib.SMTPConnectError,socket.error):
  print "connect error"
  try:
  smtp_svr.login(user,pwd)
  except smtplib.SMTPAuthenticationError:
  print "authentication error\n"
  try:
  smtp_svr.sendmail(user,coms,msg.as_string())
  except (smtplib.SMTPRecipientsRefused,smtplib.SMTPDataError,smtplib.SMTPServerDisconnected):
  print "send mail error"
  smtp_svr.close
  if __name__=='__main__':
  iconfs=getConfigFile("ini/auto.ini")
  logfile = "log/" + time.strftime("%Y-%m-%d",time.localtime())+"_log.txt"
  for iconf in iconfs:
  host,user,pwd,poi,coms = readConfig("ini/" + iconf)
  #        print host,user,pwd
  TelNet(host,user,pwd,poi,coms,logfile)
  time.sleep(5)
  SendMail("ini/Mail.ini",logfile)
  print "send mail ok"
  #print base64.b64encode("ff")
  配置文件:
  auto.ini:需要巡检的服务器
  ;基本的配置信息
  [Config]
  machines1=1.ini
  machines2=2.ini
  machines3=3.ini
  machines4=4.ini
  machines5=5.ini
  machines6=6.ini
  Mail.ini:发邮件设置
  ;基本的配置信息
  [FROM]
  ;主机IP
  HOST = 163.com
  ;远程ssh主机用户名
  USERNAME = XXX@163.com
  ;远程ssh主机密码,做base64加密处理
  PASSWORD = aahhefdnaA==
  ;邮件标题
  SUBJECT = 邮件标题
  ;命令列表
  [TO]
  1:aaa@163.com
  2:aaa1@163.com
  3:aaa2@163.com
  最后建auto.ini里面配置的具体服务器配置
  ;基本的配置信息
  [BASEINFO]
  ;主机IP
  HOST = 192.168.1.119
  ;远程ssh主机用户名
  USERNAME = oracle
  ;远程ssh主机密码,做base64加密处理
  PASSWORD = ZaZjc3ekYlAdMjAxMM8=
  ;远程ssh主机端口
  PORT = 22
  ;SH提示符
  POINTING = $
  ;命令列表
  [COMMANDS]
  1:./shell/checksys.sh
  ;1:/usr/sbin/swapinfo -a | grep memory |awk '{print $5}'
  ;2:bdf
  ;3:ps -ef |grep java | grep -v grep|wc -l
  ;4:ps -ef |grep agent| grep -v grep|wc -l
  注:命令列表里写的是你想要查的内容。
  建议还是把所有的内容写在服务器的一个SH里。。这里只调用一个sh即可。
  我的checksys.sh
  echo "***********CPU***********"
  vmstat | sed -n 3p |awk '{print "CPU_ider="$18"%\nCPU_System_Use="$17"%\nCPU_User_Use="$16"%\n"}'
  echo "**********Memory*********"
  /usr/sbin/swapinfo -a | grep memory |awk '{print "Memory_used="$5"\n"}'
  echo "***********disk**********"
  bdf
  echo "**********agent**********"
  ps -ef |grep agent|grep -v grep |wc -l|awk '{print "agentCount="$1}'
  所有事情都完成后,用py2exe把成exe包。就可以在window平台上用了。
  其实应用的地方挺广的。还有很大的改进空间。欢迎交流。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics