设为首页 收藏本站
查看: 2358|回复: 0

[经验分享] python 实现多台UNIX服务器自动巡检

[复制链接]

尚未签到

发表于 2017-5-6 10:46:08 | 显示全部楼层 |阅读模式
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平台上用了。
  其实应用的地方挺广的。还有很大的改进空间。欢迎交流。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-373711-1-1.html 上篇帖子: 深入 GalCon:Python、游戏开发和人工智能 下篇帖子: 整理网上python解析xml文件相关资料汇总
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表