python調用ansible遠程執行命令


1. 概述

    需要通過頁面進行遠程啟停程序,目前通過ansible部署應用,調用部署機器的ansible命令來實現,ansible api 2.0后比較復雜且不好用,所以采用了這種簡單方式,記錄下。頁面部分未加入,后續需要可以添加。

2. 代碼實現

  前端頁面調用可以使用django或flask等等,只要把下面方法加入進去就能完成通過頁面啟動和停止應用。

#!/usr/bin/python
# _*_coding:utf-8_*_
# @Time     : 2019/5/29 上午9:36
# @Author   : blackysy
# @File     : RemoteExec.py
# @Software : PyCharm

import sys
import paramiko


# 連接構建服務器
def ssh_connect():
    hostname = '192.168.250.2'
    username = 'jenkins'
    password = '123456'
    try:
        ssh_fd = paramiko.SSHClient()
        ssh_fd.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_fd.connect(hostname, username=username, password=password)
        return ssh_fd
    except Exception as e:
        print('ssh %s@%s: %s' % (username, hostname, e))
        exit()


# 遠程執行命令方法
def ssh_exec_cmd(ssh_fd, cmd):
    return ssh_fd.exec_command(cmd)


# 關閉ssh連接
def ssh_close(ssh_fd):
    ssh_fd.close()


# 啟動應用
def app_start(ip, user, app_type, exec_cmd):
    if app_type == 'jdk':
        cmd = "ansible %s -u %s -m shell -a 'source ~/.bash_profile && cd $BIN_HOME && sh %s'" \
              % (ip, user, exec_cmd)
    elif app_type == 'tomcat':
        cmd = "ansible %s -u %s -m shell -a 'source ~/.bash_profile && cd $BIN_HOME/.. && nohup ./bin/startup.sh'" \
              % (ip, user)
    else:
        sys.exit(0)

    sshd = ssh_connect()
    stdin, stdout, stderr = ssh_exec_cmd(sshd, cmd)
    err_list = stderr.readlines()

    if len(err_list) > 0:
        print('Start failed:' + err_list[0])
        sys.exit(0)
    else:
        print('Start success.')

    for item in stdout.readlines():
        print item

    ssh_close(sshd)


# 停止應用
def app_stop(ip, user):
    cmd = """ansible %s -u %s -m shell -a 'ps x|grep java|grep -v grep|cut -d " " -f 1|xargs kill -9'""" \
          % (ip, user)
    sshd = ssh_connect()
    stdin, stdout, stderr = ssh_exec_cmd(sshd, cmd)
    err_list = stderr.readlines()

    if len(err_list) > 0:
        print('Stop failed: ' + err_list[0])
        sys.exit(0)
    else:
        print('Stop success.')

    for item in stdout.readlines():
        print item

    ssh_close(sshd)


# 測試1 netty或者spring非tomcat的應用啟動方法
# 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')

# 測試2 tomcat的應用啟動方法
# app_start(ip='192.168.250.103', user='client_str', app_type='tomcat', exec_cmd='')

# 測試3 停止應用的方法
# app_stop(ip='192.168.250.103', user='client_str')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM