jenkins 自动化部署执行shell

# -*- coding:utf-8 _*-
"""
@author:Administrator
@file: new_app_publish.py
@time: 2018/08/29
"""

import paramiko
import sys


class AppPush(object):
def __init__(self, project, ip="", user="devroot", pwd="", port=22, ):
self.ip = ip
self.port = port
self.user = user
self.pwd = pwd
self.project = project
# self.connect_server()

def connect_server(self):
paramiko.util.log_to_file('ssh.log') # 使用paramiko记录日志
self.s = paramiko.SSHClient() # 绑定一个实例
self.s.load_system_host_keys() # 加载known_hosts文件
self.s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 远程连接如果提示yes/no时,默认为yes
self.s.connect(self.ip, self.port, self.user, self.pwd, timeout=5)
return True

def get_projetct_name(self):
pro_list = ["applicationRouter",
"businessService",
"customerApp",
"transferService",
"memberService",
"pushCenter",
"configServer"]
assert self.project in pro_list, "project must be applicationRouter,businessService,customerApp," \
"transferService,memberService,pushCenter,configServer"
path = "/usr/local/{0}/{0}.jar".format(self.project)
cmd = "sh /usr/local/{0}/{0}.sh %s".format(self.project)
return (path, cmd)

def exce_server(self, action):
ret = self.connect_server()
if action == "stop":
# get the command
cmd = self.get_projetct_name()[1] % action
print(cmd)
# 执行远程脚本
elif action == "start":
appname = self.get_projetct_name()[0]
cmd = 'nohup /usr/local/java/bin/java -Dspring.cloud.config.uri=' \
'"http://" -jar {app_name} > /dev/null 2>&1 &'. \
format(
app_name=appname)
print(cmd)
# check clinet connectec to server
if ret:
"""
stdin = chan.makefile('wb', bufsize)
stdout = chan.makefile('r', bufsize)
stderr = chan.makefile_stderr('r', bufsize)
"""
stdin, stdout, stderr = self.s.exec_command(cmd)
print(stdout.read())
# sti = stdin.read()
sto = stdout.read()
ste = stderr.read()
for i in [sto, ste]:
try:
if not i:
print(i.decode("utf-8"))
except:
raise UnicodeDecodeError("decode error")
else:
raise ConnectionError("connection server error")
self.disconnect_server()
return True

def disconnect_server(self):
self.s.close()


if __name__ == '__main__':
# AppPush("pushCenter").exce_server("stop")
AppPush(sys.argv[1]).exce_server(sys.argv[2])

posted @ 2018-09-13 14:22  tny_leyon  阅读(597)  评论(0编辑  收藏  举报