准备条件:
1、安装python、paramiko
2、如果可以联网可以忽略,不能联网需要自己制作epel源
本脚本用来部署安装salt minion,如果有多台机器,可以用一个for循环解决。理论上需要提供密码,但是如果已经配置公钥,可以不传入密码参数就可以了。
log.py
-
# -*- coding: utf-8 -*-
-
'''
-
Created on 2015-2-2
-
-
@author: yaoyf
-
'''
-
-
import logging
-
import os
-
import time
-
import sys
-
reload(sys)
-
sys.setdefaultencoding('utf8')
-
-
rq = time.strftime('%Y%m%d',time.localtime(time.time()))
-
logsetting = {
-
'logpath':'./logs/',
-
'level':'info',
-
'filename':rq+'.log'
-
}
-
-
class Log(object):
-
''' '''
-
def __init__(self,fn=""):
-
self.path = logsetting['logpath']
-
self.filename = fn+logsetting['filename']
-
self.level = logsetting['level']
-
def set_Name(self,name):
-
self.name = name
-
def set_Level(self,level):
-
self.level = level
-
def set_Path(self,path):
-
self.path = path
-
def set_Filename(self,filename):
-
self.filename = filename
-
def add_Msg(self,msg):
-
logger = logging.getLogger(self.name)
-
logger.setLevel(logging.DEBUG)
-
if os.path.exists(self.path):
-
logfile = self.path+self.filename
-
fh = logging.FileHandler(logfile)
-
else:
-
fh = logging.FileHandler(self.filename)
-
fh.setLevel(logging.DEBUG)
-
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
-
fh.setFormatter(formatter)
-
logger.addHandler(fh)
-
if self.level.upper() == "INFO":
-
logger.info(msg)
-
elif self.level.upper() == "WARNING":
-
logger.warning(msg)
-
elif self.level.upper() == "ERROR":
-
logger.error(msg)
-
else:
-
logger.debug(msg)
-
fh.close()
-
logger.removeHandler(fh)
installsalt.py
-
# -*- coding: utf-8 -*-
-
'''
-
Created on 2015-2-2
-
-
@author: yaoyf
-
'''
-
import paramiko
-
import log
-
-
class SSH(object):
-
-
def __init__(self, ip, user, password="", timeout=5):
-
self.ip = ip
-
self.user = user
-
self.password = password
-
self.timeout = timeout
-
-
def run(self, cmd):
-
import socket
-
try:
-
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
s.settimeout(2)
-
s.connect((self.ip, 22))
-
s.close()
-
restlt = "connect"
-
except Exception, e:
-
restlt = "N-connect"
-
if restlt == "connect":
-
try:
-
# paramiko.util.log_to_file('paramiko.log')
-
ssh = paramiko.SSHClient()
-
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-
ssh.connect(self.ip, 22, self.user, self.password, timeout=self.timeout)
-
stdin, stdout, stderr = ssh.exec_command(cmd)
-
stdin = "y"
-
out = stdout.readlines()
-
if len(str(out)) == 2:
-
out = "NULL"
-
else:
-
out = out
-
except Exception, e:
-
if str(e) == "Authentication failed.":
-
out = "A"
-
else:
-
out = "U"
-
finally:
-
ssh.close()
-
else:
-
out = "C"
-
return out
-
-
class InstallSalt(object):
-
-
def __init__(self, ip, user, pwd):
-
self.ip = ip
-
self.user = user
-
self.pwd = pwd
-
self.logger = log.Log()
-
self.logger.set_Name("installsalt")
-
def system_release(self):
-
cmd = "cat /etc/redhat-release"
-
ssh = SSH(self.ip,self.user,self.pwd)
-
out = ssh.run(cmd)
-
if out not in ["A","C","U","NULL"]:
-
return out[0].strip('\r\n')
-
elif out == "A":
-
return "%s密码错误" % self.ip
-
elif out == "C":
-
return "%sSSH无法连接" % self.ip
-
elif out == "U":
-
return "%s发生未获知的异常" % self.ip
-
-
def checknet(self):
-
cmd = """ curl -I -s "http://baidu.com"|grep 'HTTP/1' """
-
ssh = SSH(self.ip,self.user,self.pwd)
-
out = ssh.run(cmd)
-
if out not in ["A","C","U","NULL"]:
-
import re
-
if re.search('200 OK', out[0]):
-
return True
-
else:
-
return False
-
else:
-
return False
-
-
def installwithnet(self):
-
cmd = """ yum install epel-release.noarch -y;yum install salt-minion -y """
-
ssh = SSH(self.ip,self.user,self.pwd)
-
ssh.run(cmd)
-
-
def installwithoutnet(self):
-
cmd = """ cd /etc/yum.repos.d;mv CentOS-Base.repo CentOS-Base.repo.bak;\
-
echo -e "[base]\nname=ai\nbaseurl=http://10.11.20.127/aiPackages\nenabled=1\ngpgcheck=0" > ai.repo;\
-
yum clean all;yum install salt-minion -y """
-
ssh = SSH(self.ip,self.user,self.pwd)
-
ssh.run(cmd)
-
-
def checkinstall(self):
-
cmd = """ ls /etc/init.d/|grep salt-minion|wc -l """
-
ssh = SSH(self.ip,self.user,self.pwd)
-
out = ssh.run(cmd)[0].strip('\r\n')
-
if int(out) == 1:
-
return True
-
else:
-
return False
-
-
def modifyconf(self):
-
cmd = """ sed -i 's/#master: salt/master: 10.11.20.127/' /etc/salt/minion;\
-
sed -i 's/#id:/id: %s/' /etc/salt/minion """ % self.ip
-
ssh = SSH(self.ip,self.user,self.pwd)
-
ssh.run(cmd)
-
-
def startminion(self):
-
cmd = """ /etc/init.d/salt-minion start"""
-
ssh = SSH(self.ip,self.user,self.pwd)
-
ssh.run(cmd)
-
-
def main(self):
-
if not self.checkinstall():
-
if self.system_release() in ["CentOS release 6.5 (Final)",]:
-
if self.checknet():
-
self.installwithnet()
-
else:
-
self.installwithoutnet()
-
if self.checkinstall():
-
msg = "%s安装minion成功" % self.ip
-
self.logger.set_Level("info")
-
self.logger.add_Msg(msg)
-
self.modifyconf()
-
msg = "%s修改配置文件成功" % self.ip
-
self.logger.set_Level("info")
-
self.logger.add_Msg(msg)
-
self.startminion()
-
else:
-
msg = "%s安装minion失败" % self.ip
-
self.logger.set_Level("error")
-
self.logger.add_Msg(msg)
-
else:
-
msg = self.system_release()
-
self.logger.set_Level("error")
-
self.logger.add_Msg(msg)
-
else:
-
msg = "%s已安装minion" % self.ip
-
self.logger.set_Level("WARNING")
-
self.logger.add_Msg(msg)
-
-
ins = InstallSalt("10.11.24.8","root","yaoyunfei")
-
ins.main()
阅读(1483) | 评论(0) | 转发(0) |