python自动部署war包到linux(Centos)服务器代码案例

最近使用jenkins自动部署应用到服务器去,最开始使用执行conmand插件去部署,好不稳定而且配置也不好配置(因为有多
个project无法,每个project的路径又不好确定),最终失败而告终,后面又使用jenkins插件 join job +deploy
war,配置了多个job去实现,终于可以将多个项目成功部署到远程linux(centos)服务器中,这时又发现,部署时间太久了,而且很不稳定,经常性的失败,最终又是以失败告终,经过再三考察和咨询,最终自己写了下面的部署代码,使用
python plus插件完美解决问题。O(∩_∩)O哈哈~庆祝一下把


部署环境
Server:Centos7.4
client : Win7
tomcat: apache-tomcat8.5
python: 2.7


#!/usr/bin/python
# -*-coding:utf-8 -*-

import paramiko
import datetime
import urllib2
import time

class SSH(object):
    def __init__(self,projectName,host,username,password,port=22):
        print("★"*20+"start deploy project "+projectName +"★"*20)
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            self.ssh.connect(host, port, username, password)
            print '❤ server ssh create succesful'
        except Exception as e:
            print '❤ server ssh create failed', e

        self.resftp = paramiko.Transport(host, port)
        try:
            self.resftp.connect(username=username,password=password)
            self.sftpssh = paramiko.SFTPClient.from_transport(self.resftp)
            print '❤ server sftp connection succesful'
        except Exception as e:
            print '❤ server sftp connection failed', e

    # 获取当前时间的时间字符串可用于创建文件
    def getCurrentDateString(self):
        i = datetime.datetime.now()
        month = str(i.month) if i.month > 9 else "0" + str(i.month)
        day = str(i.day) if i.day > 9 else "0" + str(i.day)
        hour = str(i.hour) if i.hour > 9 else "0" + str(i.hour)
        minute = str(i.minute) if i.minute > 9 else "0" + str(i.minute)
        second = str(i.second) if i.second > 9 else "0" + str(i.second)
        cuurentDate = "{0}{1}{2}{3}{4}{5}".format(i.year, month,day,hour,minute,second)
        return cuurentDate

    # 移动文件,给文件名后面加时间戳
    def moveFile(self, filepath, fileName):
        filepath = filepath + 'webapps/' + fileName + '.war'
        if self.existFile(filepath).strip() != '':
            errInfo = '❤ the file'+fileName+"is not found"
        else:
            date = self.getCurrentDateString()
            command = 'mv ' + filepath + ' ' + filepath + date
            stdin, stdout, stderr = self.ssh.exec_command(command)
            errInfo = stderr.read()
        print '❤ mv and rename file succesful'
        return errInfo

    # 杀服务进程
    def killProcess(self, processName):
        command = "kill -9 $(ps -ef|grep " + processName + "|gawk '$0 !~/grep/ {print $2}' |tr -s '\\n' ' ')"
        stdin, stdout, stderr = self.ssh.exec_command(command)
        print "❤ kill "+ processName +" process succesfull"
        return stderr.read()

    # 执行linux命令
    def delOldFile(self, command):
        command = 'rm -rf ' + command
        stdin, stdout, stderr = self.ssh.exec_command(command)
        print '❤ Exec Command', command, 'successful'
        return stderr.read()

    # 连接服务器将文件上传至服务器
    def putFileToServer(self,originalFilePath, targetFilePath, targetFileName):
        targetPath = targetFilePath + 'webapps/' + targetFileName + '.war'
        self.sftpssh.put(originalFilePath, targetPath)
        print '❤ put war package to server succesful'

    # 启动Tomcat
    def startTomcat(self, command):
        command = command + 'bin/startup.sh'
        stdin, stdout, stderr = self.ssh.exec_command(command)
        print '❤ Exec Command', command, 'successful'
        return stderr.read()

    # 判断文件是否存在
    def existFile(self, filepath):
        command = 'ls ' + filepath
        stdin, stdout, stderr = self.ssh.exec_command(command)
        return stderr.read()

    # 验证是否部署成功
    def openPage(self, url):
        print '❤ request check url is == ' + url
        times = 1
        while times<=60:
            try:
                urllib2.urlopen(url, timeout=1)
                break
            except Exception as e:
                times += 1
                time.sleep(1)
        else:
            print("▉"*50)
            raise ValueError

    #释放资源
    def __del__(self):
        self.ssh.close()
        self.sftpssh.close()

class Deploy(object):

    def __init__(self,host,username,password,projectName):
        self.host = host
        self.projectName = projectName
        self.ssh = SSH(projectName, host, username, password)

    def deploy(self,serverTomcatPath,clientWarPath,appprot):
        self.serverTomcatPath=serverTomcatPath
        self.clientWarPath=clientWarPath
        self.jenkinsBasePath = clientWarPath + projectName + "/target/" + projectName + ".war"  # 本地war地址
        self.serverProjectPath = serverTomcatPath + "webapps/" + projectName
        self.projectURl = "http://"+host+":"+appprot+"/" + projectName

        self.ssh.killProcess(self.serverTomcatPath)  #删除tomcat进程
        self.ssh.moveFile(self.serverTomcatPath, self.projectName) #备份服务器war包
        self.ssh.delOldFile(self.serverProjectPath)#删除工程解压文件
        self.ssh.putFileToServer(self.jenkinsBasePath, serverTomcatPath, projectName) #上传war包到服务器
        self.ssh.startTomcat(self.serverTomcatPath) #启动tomcat
        self.ssh.openPage(self.projectURl) #打开project工程首页



if __name__ == '__main__':
    host = '服务器地址'
    username = '用户名'
    password = '密码'
    #clientWarPath = u"D:/Jenkins_workspace/jenkins编译路径/" #windows专用
    clientWarPath = "D:/Jenkins_workspace/jenkins编译路径/"
    errrorList=[]
    #部署toms
    projectName= 'taxi-toms'
    serverTomcatPath = '/usr/local/software/tomcat1路径/' #需要到bin级别
    apport = '8084'
    deploy = Deploy(host,username,password,projectName)
    try:
        deploy.deploy(serverTomcatPath,clientWarPath,apport)
    except:
        errrorList.append(projectName)
    #部署client
    projectName= 'taxi-client'
    serverTomcatPath = '/usr/local/software/tomcat2路径/' #需要到bin级别
    apport = '8083'
    try:
        deploy.deploy(serverTomcatPath,clientWarPath,apport)
    except:
        errrorList.append(projectName)
    try:
        deploy.deploy(serverTomcatPath,clientWarPath,apport)
    except:
        errrorList.append(projectName)

英语不好,中间有好多错别字,请见谅。。。。

猜你喜欢

转载自blog.csdn.net/cjh365047871/article/details/80388109