获取网络设备返回值

获取网络设备返回值

# !/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import contextlib
from io import StringIO


@contextlib.contextmanager
def stdoutIO(stdout=None):
	old = sys.stdout
	if stdout is None:
		stdout = StringIO()
	sys.stdout = stdout
	yield stdout
	sys.stdout = old


code_str = """
import sys
import paramiko
import time

try:
	# python2
	reload(sys)
	sys.setdefaultencoding("utf-8")
except:
	# python3
	import importlib

	importlib.reload(sys)


def pa_invoke_shell(ip, port, username, password, commands):
	ssh = paramiko.SSHClient()
	ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
	ssh.connect(ip, port, username, password)
	channel = ssh.invoke_shell(width=1000)

	result_list = []
	for cmd in commands:
		channel.send(cmd)
		time.sleep(0.1)
		result = channel.recv(65535)
		while True:
			channel.send(" ")
			time.sleep(0.1)
			results = channel.recv(65535)
			if results == b‘ ‘:
				break
			result += results
		result_list.append(result.decode(‘utf-8‘))

	channel.close()
	ssh.close()
	return result_list
result = pa_invoke_shell(ip=ip, port=22, username=username, password=password,
						 commands=["terminal length 0\n", "show config\n"])
"""

local_vars = None
kwargs = {
	"ip": "10.12.32.49",
	"port": 22,
	"username": "hillstone",
	"password": "hillstone",
	"commands1": [
		"terminal length 0\n",
		"show ip route\n"
	],
	"commands2": [
		"terminal length 0\n",
		"show config\n"
	],
}
with stdoutIO() as s:
	try:
		code_obj = compile(source=code_str, filename=‘‘, mode=‘exec‘)
		exec(code_obj, kwargs, local_vars)
		# print(locals())
		# print(locals().get(‘shell_output‘))
		# print(globals().keys())
		res = locals().get("kwargs")
	except Exception as e:
		raise e

print(res.get("result"))

获取网络设备返回值

上一篇:制作谷歌图标


下一篇:SAPUI5 Walkthrough Step 32: Routing with Parameters