robotframework/lib/ap/connect_cli.py

57 lines
2.3 KiB
Python

import paramiko
import os
import sys
from robot.api import logger
class BackSAP:
def __init__(self):
self.host = ""
self.loginUsr = ""
self.loginPwd = ""
self.prompt = r"]#|~#"
self.timeout = 120
self.publickey = ""
self.port = 17555
self.ssh = ""
def open_BackSAP_connection(self, host, loginUsr = '', loginPwd = '', port=None, publickey=""):
self.host = host
self.loginUsr = loginUsr
self.loginPwd = loginPwd
self.publickey = publickey
self.port = port
#判断AP连接是否需要key文件
if self.publickey == 'need':
try:
key_file = os.path.split(os.path.realpath(__file__))[0]+'/apkey/quanwifi.key'
private_key = paramiko.RSAKey.from_private_key_file('{}'.format(key_file),password=self.loginPwd)
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.host, port=self.port, username=self.loginUsr, pkey=private_key, timeout=15)
logger.info('connect {} successful,the ap need key'.format(self.host))
except Exception as e:
raise 'connect AP fail the Reason is {}'.format(e)
else:
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.host,port=self.port,username=self.loginUsr,password=self.loginPwd,timeout=15)
logger.info('connect {} successful,the ap not need key'.format(self.host))
except Exception as e:
raise 'connect AP fail the Reason is {}'.format(e)
def SendCmd_ap(self, cmd, timeout = None):
try:
stdin, stdout, stderr = self.ssh.exec_command(cmd,timeout=20)
res,err = stdout.read(),stderr.read()
if err:
raise Exception('input command is error,the error :{}!'.format(err))
else:
logger.info(res)
return res
except Exception as e:
return 'ssh.exec_command(cmd) is error:{}'.format(e)
def close_linuxAP(self):
if self.ssh:
self.ssh.close()