Eureka命令行管理脚本,查看、上线、下线服务

Eureka命令行管理脚本

效果

[root@local-vm ~]# 【1.查看服务】
[root@local-vm ~]# python3.6 eurekaAdmin.py -a test-app
[2021-06-16 11:35:29] - param[appID=test-app,instance=,do=]
————————————————————————————————————————————————http://192.168.1.10:8600—————————————————————————————————————————
| application          | instance                                          | ip               | status               | lastTime   |
| test-app   | 192.168.1.100:test-app:8001           | 192.168.1.100       | UP          | 2021-06-16 11:35:38 |
| test-app   | 192.168.1.101:test-app:8001           | 192.168.1.101       | UP          | 2021-06-16 11:35:35 |
[root@local-vm ~]# 
[root@local-vm ~]# 【2.下线服务】
[root@local-vm ~]# python3.6 eurekaAdmin.py -a test-app -i 192.168.1.100:test-app:8001 -d down
[2021-06-16 11:35:46] - param[appID=test-app,instance=192.168.1.100:test-app:8001,do=down]
request: http://192.168.1.10:8600/eureka/apps/test-app/192.168.1.100:test-app:8001/status?value=DOWN
————————————————————————————————————————————————http://192.168.1.10:8600—————————————————————————————————————————
| application          | instance                                          | ip               | status               | lastTime   |
| test-app   | 192.168.1.100:test-app:8001           | 192.168.1.100       | DOWN        | 2021-06-16 11:35:56 |
| test-app   | 192.168.1.101:test-app:8001           | 192.168.1.101       | UP          | 2021-06-16 11:35:56 |
[root@local-vm ~]# 
[root@local-vm ~]# 
[root@local-vm ~]# 【3.上线服务】
[root@local-vm ~]# python3.6 eurekaAdmin.py -a test-app -i 192.168.1.100:test-app:8001 -d up
[2021-06-16 11:36:07] - param[appID=test-app,instance=192.168.1.100:test-app:8001,do=up]
request: http://192.168.1.10:8600/eureka/apps/test-app/192.168.1.100:test-app:8001/status?value=UP
————————————————————————————————————————————————http://192.168.1.10:8600—————————————————————————————————————————
| application          | instance                                          | ip               | status               | lastTime   |
| test-app   | 192.168.1.100:test-app:8001           | 192.168.1.100       | UP          | 2021-06-16 11:36:18 |
| test-app   | 192.168.1.101:test-app:8001           | 192.168.1.101       | UP          | 2021-06-16 11:36:16 |

源码

# -*- coding: utf-8 -*-
# author by Jamin

'''
1. 查看服务
python3.6 eurekaAdmin.py -a test-app

2. 下线服务
python3.6 eurekaAdmin.py -a test-app -i (1步骤中查到的Instance) -d down

3. 上线服务
python3.6 eurekaAdmin.py -a test-app -i (1步骤中查到的Instance) -d up
'''

import requests
import json
import sys
import getopt
import time

def usage():
    """show help"""
    f = sys.argv[0].split('/')
    print ("Usage: ",f[len(f)-1]," -a <eurekaAppId> -i <eurenaInstanceId> -d <[down | up]>")

class eureka():
    """
    Eureka CLI Admin
    支持CLI查看和上下线服务
    """
    def __init__(self, eurekaHost = []):
        self.appId = ''
        self.instance = ''
        self.action = ''
        self.eurekaHost = eurekaHost
        self.RED = '\033[91m'
        self.GREEN = '\033[92m'
        self.END = '\033[0m'
        self.TEMPLATE = '| %-20s | %-45s | %-16s | %-20s | %-10s |'
        

    def getPath(self, host, path):
        return "%s/eureka/apps/%s" % (host, path)

    def getEruekaConfig(self, host):
        url = self.getPath(host,self.appId)

        payload="{}"
        headers = {
            'Accept': 'application/json'
        }
        try:
            response = requests.request("GET", url, headers=headers, data=payload)

            if response.ok is False:
                print(self.RED,"error:",self.END,response)
                return
            data = json.loads(response.text)
            print (self.TEMPLATE % ("application","instance","ip","status","lastTime")) 

            for _ in data['application']['instance']:
                color = self.GREEN if _['status'] == 'UP' else self.RED
                dateymd = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_['leaseInfo']['lastRenewalTimestamp']/1000))
                print (self.TEMPLATE % (_['app'],_['instanceId'],_['ipAddr'],(color + _['status'] + self.END), dateymd)) 

        except Exception:
            print(self.RED,"error:",self.END,url)
            return



    def setEruekaConfig(self, host):
        self.action = self.action.upper()
        if self.action == 'DOWN' or self.action == 'UP':
            url = self.getPath(host,"%s/%s/status?value=%s" % (self.appId,self.instance,self.action))
            payload="{}"
            headers = {
                'Accept': 'application/json'
            }
            response = requests.request("PUT", url, headers=headers, data=payload)
            print("request:",url)
            if response.ok is False:
                print(self.RED,"error:",self.END,response)

            time.sleep(1.5)
            self.getAllEurekaConfig()
        else:
            print("param error:",self.action)
            usage()

    def main(self, argv):
        try:
            opts, args = getopt.getopt(argv,"ha:i:d:",["app=","instance=","do="])
        except getopt.GetoptError:
            usage()
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h' or opt == '--help':
                usage()
                sys.exit()
            elif opt in ("-a", "--app"):
                self.appId = arg
            elif opt in ("-d", "--do"):
                self.action = arg
            elif opt in ("-i", "--instance"):
                self.instance = arg
        
        print('[%s] - param[appID=%s,instance=%s,do=%s]' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), self.appId,self.instance,self.action))

        if self.appId != '' and self.action!='' and self.instance!='':
            self.setEruekaConfig(self.eurekaHost[0])
        elif self.appId!='':
            self.getAllEurekaConfig()
    
    def getAllEurekaConfig(self):
        for _ in self.eurekaHost:
            print("————————————————————————————————————————————————%s—————————————————————————————————————————" % _)
            self.getEruekaConfig(_)

if __name__ == '__main__':
    """eureka 命令行管理程序"""
    if len(sys.argv) < 2:
        usage()
        sys.exit()
    else:
        eurekaHost = ["192.168.1.10:8600"]
        eureka(eurekaHost).main(sys.argv[1:])

posted @ 2021-06-16 11:44  JaminX86  阅读(1137)  评论(0编辑  收藏  举报