Script and Command Making for Jumper Logon Server

I. Purpose

Logging on to the server from the stepping board is an operation every time you log on to the server on the line. If you log on to the stepping board manually with ssh username@ip every time, it is inefficient and cumbersome. If you log on to the stepping board, you automatically execute a command to show the system you have the right to log on. When you select the system, you will list all the nodes of the system ip, and then you will automatically log on to the corresponding machine after you select ip.The machine is very convenient.This idea led to the python script for this article.

2. Code implementation

2.1, python code

File name: smart_ssh, run environment: python 2.7

#!/usr/bin/python

from optparse import OptionParser

import  pexpect
import  getpass
import  requests
import  json

def connect_to_server(ip):
    if(ip == None):
		return None
    ssh_cmd = "ssh iwill@{}".format(ip)
    child = pexpect.spawn(ssh_cmd)
    child.interact()

def list_authorized_apps(username, part_app_name):
    try:
		url = "http://localhost:8080/cmdb/list-app?username=%s&app=%s" % (username ,part_app_name)
		if part_app_name == None:
			url = "http://localhost:8080/cmdb/list-app?username=%s" % (username)
		resp = requests.get(url)
		if(resp.status_code != 200):
			print("request app list from cmdb fail !")
			return None
		resp_content = json.loads(resp.text)
		if(resp_content['success'] =='true'):
			result = resp_content['data']
			return result
		else:
			print("request app list from cmdb fail !")
			return None
    except:
		print("cmdb service is not available !")
		return None

def list_authorized_ips(username, app_name):
    if app_name == None:
		return None
    try:
		url = "http://localhost:8080/cmdb/list-ip?username=%s&artifact_id=%s" % (username, app_name)    
		resp = requests.get(url)
		if(resp.status_code != 200):
			print("request server ip list from cmdb fail !")
			return None
		resp_content = json.loads(resp.text)
		if(resp_content['success']=='true'):	
			result = resp_content['data']
			return result
		else:
			print("request ip list from cmdb fail !")
			return None
    except:
		print("cmdb service is not available !")
		return None

def show_app_list(part_app_name, app_name_list):
    if(app_name_list == None):
		return None
    print("all application like %s list below" %(part_app_name))
    index = 0 
    for app_name in app_name_list:
        print("  %d : %s " %(index ,app_name)) 
        index = index + 1
    show_msg = 'please select app (0...%d) : '%(index-1)
    try:
		app_index = input(show_msg)
		if(app_index < 0 or app_index > index):
			print("you input wrong number ! ")
			return None
		selected_app = app_name_list[app_index]
		return selected_app 
    except:
		print("you input wrong number ! ")
		return None

def show_ip_list(app_name, app_ip_list):
    if(app_ip_list == None):
		return None
    print("all ips of the application %s list below" %(app_name))
    index = 0 
    for app_ip in app_ip_list:
    	index = index + 1
        print("  %d : %s " %(index ,app_ip)) 
    show_msg = 'please select ip (1...%d) : '%index
    try:
		id_index = input(show_msg)
		if(id_index <= 0 or id_index > index):
			print("you input wrong number ! ")
			return None
		selected_ip = app_ip_list[id_index-1]
		return selected_ip   
    except:
		print("you input wrong number ! ")
		return None

def main():
    parser = OptionParser()
    parser.add_option('-a', '--app', dest='app', action='store', type='string', help='the application id in the auv')
    (options, args) = parser.parse_args()
    
    username = getpass.getuser()
    app_name_list = list_authorized_apps(username, options.app)

    if app_name_list == None:
		exit()
    elif (len(app_name_list) == 0 and options.app == None):
		print("you are not authorized to any app ,use jumper directly")
		exit()
    elif len(app_name_list) == 0 :
    	print("no app name like %s, use jumper directly" %(options.app))
    	exit()
    elif (len(app_name_list) == 1 and app_name_list[0] == options.app):
    	app_ip_list = list_authorized_ips(username, options.app)
    	selected_ip = show_ip_list(options.app, app_ip_list)
    	connect_to_server(selected_ip)
    else :
        jumper_name = 'no thanks ,I will use jumper'
        app_name_list.insert(0,jumper_name)
    	selected_app = show_app_list(options.app, app_name_list)
        if(selected_app == jumper_name) :
            exit()
    	app_ip_list = list_authorized_ips(username, selected_app)
    	selected_ip = show_ip_list(selected_app, app_ip_list)
    	connect_to_server(selected_ip)
    exit()
if __name__== '__main__':
   main()

cmdb interface code for 2.2, mock

@RestController
@RequestMapping("cmdb")
public class CmdbController {

    @GetMapping("list-app")
    public String listApp(@RequestParam(value = "username") String username, @RequestParam(value = "app", required = false) String app) {
        Result result = new Result("true");
        List<String> partApps = new ArrayList<>();
        partApps.add("axx-app");
        partApps.add("bxx-app");
        partApps.add("cxx-app");
        result.setData(partApps);
        return new Gson().toJson(result);

    }

    @GetMapping("list-ip")
    public String listIp(@RequestParam(value = "username") String username, @RequestParam(value = "artifact_id", required = false) String artifact_id) {
        Result result = new Result("true");
        List<String> partApps = new ArrayList<>();
        partApps.add("192.168.0.101");
        partApps.add("192.168.0.102");
        partApps.add("192.168.0.103");
        result.setData(partApps);
        return new Gson().toJson(result);
    }
}

2.3. System Command Making

Place the file smart_ssh under /usr/local/bin, suorce it once/etc/profile, and you can run smart_ssh from the command line

2.4. Operation effect

3. Feelings

1. There are many ways to be very efficient in your work, among which the complete tools are one.

2. Many things are not done when you see hope, but when you do, there is hope.

Tags: Python JSON ssh

Posted on Sat, 11 Jan 2020 11:08:37 -0500 by troublemaker