1. 概述
需要通过页面进行远程启停程序,目前通过ansible部署应用,这里通过调用部署机器的ansible命令来实现,ansible api 2.0后比较复杂且不好用,所以采用了这种简单方式,记录下。页面部分未加入,后续需要可以添加。
2. 代码实现
1 #!/usr/bin/python 2 # _*_coding:utf-8_*_ 3 # @Time : 2019/5/29 上午9:36 4 # @Author : blackysy 5 # @File : RemoteExec.py 6 # @Software : PyCharm 7 8 import sys 9 import paramiko 10 11 12 # 连接构建服务器 13 def ssh_connect(): 14 hostname = '192.168.250.2' 15 username = 'jenkins' 16 password = '123456' 17 try: 18 ssh_fd = paramiko.SSHClient() 19 ssh_fd.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 20 ssh_fd.connect(hostname, username=username, password=password) 21 return ssh_fd 22 except Exception as e: 23 print('ssh %s@%s: %s' % (username, hostname, e)) 24 exit() 25 26 27 # 远程执行命令方法 28 def ssh_exec_cmd(ssh_fd, cmd): 29 return ssh_fd.exec_command(cmd) 30 31 32 # 关闭ssh连接 33 def ssh_close(ssh_fd): 34 ssh_fd.close() 35 36 37 # 启动应用 38 def app_start(ip, user, app_type, exec_cmd): 39 if app_type == 'jdk': 40 cmd = "ansible %s -u %s -m shell -a 'source ~/.bash_profile && cd $BIN_HOME && sh %s'" \ 41 % (ip, user, exec_cmd) 42 elif app_type == 'tomcat': 43 cmd = "ansible %s -u %s -m shell -a 'source ~/.bash_profile && cd $BIN_HOME/.. && nohup ./bin/startup.sh'" \ 44 % (ip, user) 45 else: 46 sys.exit(0) 47 48 sshd = ssh_connect() 49 stdin, stdout, stderr = ssh_exec_cmd(sshd, cmd) 50 err_list = stderr.readlines() 51 52 if len(err_list) > 0: 53 print('Start Failed:' + err_list[0]) 54 sys.exit(0) 55 else: 56 print('Start success.') 57 58 for item in stdout.readlines(): 59 print item 60 61 ssh_close(sshd) 62 63 64 # 停止应用 65 def app_stop(ip, user): 66 cmd = """ansible %s -u %s -m shell -a 'ps x|grep java|grep -v grep|cut -d " " -f 1|xargs kill -9'""" \ 67 % (ip, user) 68 sshd = ssh_connect() 69 stdin, stdout, stderr = ssh_exec_cmd(sshd, cmd) 70 err_list = stderr.readlines() 71 72 if len(err_list) > 0: 73 print('Stop Failed: ' + err_list[0]) 74 sys.exit(0) 75 else: 76 print('Stop success.') 77 78 for item in stdout.readlines(): 79 print item 80 81 ssh_close(sshd) 82 83 84 # 测试1 netty或者spring非tomcat的应用启动方法 85 # app_start(ip='192.168.250.103', user='pay_str', app_type='jdk', exec_cmd='start.sh 172.28.250.242 172.28.250.142') 86 87 # 测试2 tomcat的应用启动方法 88 # app_start(ip='192.168.250.103', user='client_str', app_type='tomcat', exec_cmd='') 89 90 # 测试3 停止应用的方法 91 # app_stop(ip='192.168.250.103', user='client_str')View Code
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。