end_flag1
= ']$'end_flag2
= ']#'stdout
= ''#
存放每次执行读取的内容for
item in prompt_input_list:prompt
= list(item.keys())[0]input
= item[prompt]flag
= Falsewhile
stdout.find(prompt) == -1:try:stdout
+= channel.recv(65535).decode('utf-8')#.decode('utf-8')flag
= Trueexcept
Exception as e:print('通过堡垒机:%s
访问目标机:%s
失败:%s' % (hostname, host_via_by_bastion, e))flag
= Falsebreakif
flag:channel.send(input)else:
# 未找到了对应提示return
[False,
'通过堡垒机:%s
访问目标机:%s
失败,可能是读取命令返回结果超时,或者没找到对应输入提示'%
(hostname, host_via_by_bastion)]flag
= Falsewhile
not (stdout.rstrip().endswith(end_flag1) or stdout.rstrip().endswith(end_flag2)):try:stdout
= channel.recv(2048).decode('utf-8')flag
= Trueexcept
Exception as e:print('通过堡垒机:%s
访问目标机:%s
失败:%s' % (hostname, host_via_by_bastion, e))flag
= Falsebreakif
flag:return
[True,
'']else:
# 未找到了对应提示return
[False,
'没出现成功登录提示符 ]$
或 ]#
']channel.close()return[True,
'']except
Exception as e:return
[False,
'%s' % e]#
远程执行命令def
exec_command(self,
command, target_host, bastion_host):try:channel
= self.ssh_client.invoke_shell()channel.settimeout(30)
# 读、写操作超时时间,30秒end_flag1
= ']$'end_flag2
= ']#'################
定制化开发 ##############################if
bastion_host != '':print('正在通过堡垒机:%s
访问目标机:%s' % (bastion_host, target_host))target_host_input
= target_host + '\n'prompt_input_list
= [{'Please
enter your ID':'01367599\n'},
{'Please
enter your password':
'Huozhe2020\n'},
{'Please
select your app ip':target_host_input},
{'select
your user for login':'1\n'}]stdout
= ''#
存放每次执行读取的内容for
item in prompt_input_list:prompt
= list(item.keys())[0]input
= item[prompt]flag
= Falsewhile
stdout.find(prompt) == -1:try:stdout
+= channel.recv(65535).decode('utf-8')#.decode('utf-8')flag
= Trueexcept
Exception as e:print('通过堡垒机:%s
访问目标机:%s
失败:%s' % (bastion_host, target_host,
e))flag
= Falsebreakif
flag:channel.send(input)else:
# 未找到了对应提示print('通过堡垒机:%s
访问目标机:%s
失败,可能是读取命令返回结果超时,或者没找到对应输入提示'%
(bastion_host, target_host))#
return [False, '通过堡垒机:%s 访问目标机:%s 失败,可能是读取命令返回结果超时,或者没找到对应输入提示'
% (bastion_host,
target_host)]returnwhile
not (stdout.rstrip().endswith(end_flag1) or stdout.rstrip().endswith(end_flag2)):try:stdout
= channel.recv(2048).decode('utf-8')except
Exception as e:print('通过堡垒机:%s
访问目标机:%s
失败:没出现成功登录提示符 ]$ 或 ]#' % (bastion_host, target_host))returnchannel.send(command+'\n')command_res
= ''#
存放每次执行读取的内容while
not (command_res.endswith(end_flag1) or command_res.endswith(end_flag2)):try:command_res
= channel.recv(2048).decode('utf-8').strip()except
Exception as e:print('在目标机(IP:
%s)上进行读取操作超时' % target_host)breakchannel.close()except
Exception as e:print('针对目标机:%s
执行命令: %s
出错 %s' % (target_host, command, e))