Chinaunix首页 | 论坛 | 博客
  • 博客访问: 57116
  • 博文数量: 11
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 164
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-15 09:42
文章分类

全部博文(11)

文章存档

2015年(1)

2014年(10)

我的朋友

分类: Python/Ruby

2015-02-03 09:45:15

准备条件:
1、安装python、paramiko
2、如果可以联网可以忽略,不能联网需要自己制作epel源
本脚本用来部署安装salt minion,如果有多台机器,可以用一个for循环解决。理论上需要提供密码,但是如果已经配置公钥,可以不传入密码参数就可以了。
log.py

点击(此处)折叠或打开

  1. # -*- coding: utf-8 -*-
  2. '''
  3. Created on 2015-2-2

  4. @author: yaoyf
  5. '''

  6. import logging
  7. import os
  8. import time
  9. import sys
  10. reload(sys)
  11. sys.setdefaultencoding('utf8')

  12. rq = time.strftime('%Y%m%d',time.localtime(time.time()))
  13. logsetting = {
  14.            'logpath':'./logs/',
  15.            'level':'info',
  16.            'filename':rq+'.log'
  17.            }

  18. class Log(object):
  19.     ''' '''
  20.     def __init__(self,fn=""):
  21.         self.path = logsetting['logpath']
  22.         self.filename = fn+logsetting['filename']
  23.         self.level = logsetting['level']
  24.     def set_Name(self,name):
  25.         self.name = name
  26.     def set_Level(self,level):
  27.         self.level = level
  28.     def set_Path(self,path):
  29.         self.path = path
  30.     def set_Filename(self,filename):
  31.         self.filename = filename
  32.     def add_Msg(self,msg):
  33.         logger = logging.getLogger(self.name)
  34.         logger.setLevel(logging.DEBUG)
  35.         if os.path.exists(self.path):
  36.             logfile = self.path+self.filename
  37.             fh = logging.FileHandler(logfile)
  38.         else:
  39.             fh = logging.FileHandler(self.filename)
  40.         fh.setLevel(logging.DEBUG)
  41.         formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
  42.         fh.setFormatter(formatter)
  43.         logger.addHandler(fh)
  44.         if self.level.upper() == "INFO":
  45.             logger.info(msg)
  46.         elif self.level.upper() == "WARNING":
  47.             logger.warning(msg)
  48.         elif self.level.upper() == "ERROR":
  49.             logger.error(msg)
  50.         else:
  51.             logger.debug(msg)
  52.         fh.close()
  53.         logger.removeHandler(fh)
installsalt.py

点击(此处)折叠或打开

  1. # -*- coding: utf-8 -*-
  2. '''
  3. Created on 2015-2-2

  4. @author: yaoyf
  5. '''
  6. import paramiko
  7. import log

  8. class SSH(object):
  9.     
  10.     def __init__(self, ip, user, password="", timeout=5):
  11.         self.ip = ip
  12.         self.user = user
  13.         self.password = password
  14.         self.timeout = timeout
  15.         
  16.     def run(self, cmd):
  17.         import socket
  18.         try:
  19.             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  20.             s.settimeout(2)
  21.             s.connect((self.ip, 22))
  22.             s.close()
  23.             restlt = "connect"
  24.         except Exception, e:
  25.             restlt = "N-connect"
  26.         if restlt == "connect":
  27.             try:
  28.                 # paramiko.util.log_to_file('paramiko.log')
  29.                 ssh = paramiko.SSHClient()
  30.                 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  31.                 ssh.connect(self.ip, 22, self.user, self.password, timeout=self.timeout)
  32.                 stdin, stdout, stderr = ssh.exec_command(cmd)
  33.                 stdin = "y"
  34.                 out = stdout.readlines()
  35.                 if len(str(out)) == 2:
  36.                     out = "NULL"
  37.                 else:
  38.                     out = out
  39.             except Exception, e:
  40.                 if str(e) == "Authentication failed.":
  41.                     out = "A"
  42.                 else:
  43.                     out = "U"
  44.             finally:
  45.                 ssh.close()
  46.         else:
  47.             out = "C"
  48.         return out
  49.     
  50. class InstallSalt(object):

  51.     def __init__(self, ip, user, pwd):
  52.         self.ip = ip
  53.         self.user = user
  54.         self.pwd = pwd
  55.         self.logger = log.Log()
  56.         self.logger.set_Name("installsalt")
  57.     def system_release(self):
  58.         cmd = "cat /etc/redhat-release"
  59.         ssh = SSH(self.ip,self.user,self.pwd)
  60.         out = ssh.run(cmd)
  61.         if out not in ["A","C","U","NULL"]:
  62.             return out[0].strip('\r\n')
  63.         elif out == "A":
  64.             return "%s密码错误" % self.ip
  65.         elif out == "C":
  66.             return "%sSSH无法连接" % self.ip
  67.         elif out == "U":
  68.             return "%s发生未获知的异常" % self.ip
  69.         
  70.     def checknet(self):
  71.         cmd = """ curl -I -s "http://baidu.com"|grep 'HTTP/1' """
  72.         ssh = SSH(self.ip,self.user,self.pwd)
  73.         out = ssh.run(cmd)
  74.         if out not in ["A","C","U","NULL"]:
  75.             import re
  76.             if re.search('200 OK', out[0]):
  77.                 return True
  78.             else:
  79.                 return False
  80.         else:
  81.             return False
  82.         
  83.     def installwithnet(self):
  84.         cmd = """ yum install epel-release.noarch -y;yum install salt-minion -y """
  85.         ssh = SSH(self.ip,self.user,self.pwd)
  86.         ssh.run(cmd)
  87.         
  88.     def installwithoutnet(self):
  89.         cmd = """ cd /etc/yum.repos.d;mv CentOS-Base.repo CentOS-Base.repo.bak;\
  90.         echo -e "[base]\nname=ai\nbaseurl=http://10.11.20.127/aiPackages\nenabled=1\ngpgcheck=0" > ai.repo;\
  91.         yum clean all;yum install salt-minion -y """
  92.         ssh = SSH(self.ip,self.user,self.pwd)
  93.         ssh.run(cmd)
  94.         
  95.     def checkinstall(self):
  96.         cmd = """ ls /etc/init.d/|grep salt-minion|wc -l """
  97.         ssh = SSH(self.ip,self.user,self.pwd)
  98.         out = ssh.run(cmd)[0].strip('\r\n')
  99.         if int(out) == 1:
  100.             return True
  101.         else:
  102.             return False
  103.     
  104.     def modifyconf(self):
  105.         cmd = """ sed -i 's/#master: salt/master: 10.11.20.127/' /etc/salt/minion;\
  106.                 sed -i 's/#id:/id: %s/' /etc/salt/minion """ % self.ip
  107.         ssh = SSH(self.ip,self.user,self.pwd)
  108.         ssh.run(cmd)
  109.         
  110.     def startminion(self):
  111.         cmd = """ /etc/init.d/salt-minion start"""
  112.         ssh = SSH(self.ip,self.user,self.pwd)
  113.         ssh.run(cmd)
  114.         
  115.     def main(self):
  116.         if not self.checkinstall():
  117.             if self.system_release() in ["CentOS release 6.5 (Final)",]:
  118.                 if self.checknet():
  119.                     self.installwithnet()
  120.                 else:
  121.                     self.installwithoutnet()
  122.                 if self.checkinstall():
  123.                     msg = "%s安装minion成功" % self.ip
  124.                     self.logger.set_Level("info")
  125.                     self.logger.add_Msg(msg)
  126.                     self.modifyconf()
  127.                     msg = "%s修改配置文件成功" % self.ip
  128.                     self.logger.set_Level("info")
  129.                     self.logger.add_Msg(msg)
  130.                     self.startminion()
  131.                 else:
  132.                     msg = "%s安装minion失败" % self.ip
  133.                     self.logger.set_Level("error")
  134.                     self.logger.add_Msg(msg)
  135.             else:
  136.                 msg = self.system_release()
  137.                 self.logger.set_Level("error")
  138.                 self.logger.add_Msg(msg)
  139.         else:
  140.             msg = "%s已安装minion" % self.ip
  141.             self.logger.set_Level("WARNING")
  142.             self.logger.add_Msg(msg)
  143.             
  144. ins = InstallSalt("10.11.24.8","root","yaoyunfei")
  145. ins.main()

阅读(1472) | 评论(0) | 转发(0) |
0

上一篇:saltstack自开发WebUI

下一篇:没有了

给主人留下些什么吧!~~