Python_基于Python同Linux进行交互式操作实现通过堡垒机访问目标机

简介: Python_基于Python同Linux进行交互式操作实现通过堡垒机访问目标机

基于PythonLinux进行交互式操作实现通过堡垒机访问目标机

 


 

实现功能

远程登录Linux堡垒机,同Linux进行交互式操作,访问目标机

 

测试环境

Win7 64

 

Python 3.3.4

 

paramiko 1.15.2

下载地址:

https://pypi.python.org/pypi/paramiko/1.15.2

https://pan.baidu.com/s/1i4SJ1CL

 

cryptography-1.0-cp34-none-win_amd64.whl

(如果paramiko可以正常安装完,则不需要安装该类库)

下载地址:

https://pypi.python.org/pypi/cryptography/1.0

https://pan.baidu.com/s/1jIRBJvg

 

安装好后,找到nt.py(本例中路径为:

Lib\site-packages\pycrypto-2.6.1-py3.4-win-amd64.egg\Crypto\Random\OSRNG\nt.py),修改

import winrandom

from Crypto.Random.OSRNG import winrandom

如下

#import winrandom

from Crypto.Random.OSRNG import winrandom

 

以解决ImportError: No module named 'winrandom'错误

 

说明:具体文件路径可能还得根据实际报错情况来确定,如下

............()

"D:\ProgramFiles\python33\lib\site-packages\Crypto\Random\OSRNG\nt.py", line 28, in

   import winrandom

ImportError: No module named 'winrandom'

 

 

 

VS2010

因操作系统而异,可能需要安装VS2010,以解决包依赖问题

 

需求

SSH登录堡垒机后,根据提示输入相关信息,进入到目标机,如下


 

代码实践

 

#!/usr/bin/env/ python
# -*- coding:utf-8 -*-

__author__ ='shouke'


fromparamiko.clientimportAutoAddPolicy
fromparamiko.clientimportSSHClient

classMySSHClient:

   def__init__(self):
       self.ssh_client = SSHClient()

   # 连接登录
   defconnect(self, hostname, port, username, password, host_via_by_bastion):
       try:
           self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
           self.ssh_client.connect(hostname=hostname,port=port,username=username,password=password,timeout=30)
           channel =self.ssh_client.invoke_shell()
           channel.settimeout(10)# 读、写操作超时时间,10

           ###################### 定制化开发###########

           print('正在通过堡垒机:%s访问目标机:%s'% (hostname, host_via_by_bastion))
           host_via_by_bastion = host_via_by_bastion +'\n'

           prompt_input_list = [{'Please enter your ID':'xxx255222\n'}, {'Please enter your password':'passwd123\n'}, {'Please select your app ip':host_via_by_bastion}, {'select your user for login':'1\n'}]


           end_flag1 =']$'
           end_flag2 =']#'

           stdout =''  # 存放每次执行读取的内容
           foriteminprompt_input_list:
               prompt =list(item.keys())[0]
               input = item[prompt]

               flag =False
               whilestdout.find(prompt) == -1:
                   try:
                       stdout += channel.recv(65535).decode('utf-8')#.decode('utf-8')
                       flag =True
                   exceptExceptionase:
                       print('通过堡垒机:%s访问目标机:%s失败:%s'% (hostname, host_via_by_bastion, e))
                       flag =False
                       break
               ifflag:
                   channel.send(input)
               else:# 未找到了对应提示
                   return[False,'通过堡垒机:%s访问目标机:%s失败,可能是读取命令返回结果超时,或者没找到对应输入提示'  % (hostname, host_via_by_bastion)]

           flag =False
           while not(stdout.rstrip().endswith(end_flag1)orstdout.rstrip().endswith(end_flag2)):
               try:
                   stdout = channel.recv(2048).decode('utf-8')
                   flag =True
               exceptExceptionase:
                   print('通过堡垒机:%s访问目标机:%s失败:%s'% (hostname, host_via_by_bastion, e))
                   flag =False
                   break
           ifflag:
               return[True,'']
           else:# 未找到了对应提示
               return[False,'没出现成功登录提示符]$]# ']
           channel.close()
           return  [True,'']
       exceptExceptionase:
           return[False,'%s'% e]

   # 远程执行命令
   defexec_command(self, command, target_host, bastion_host):
       try:
           channel =self.ssh_client.invoke_shell()
           channel.settimeout(30)# 读、写操作超时时间,30

           end_flag1 =']$'
           end_flag2 =']#'
           ################ 定制化开发##############################
           ifbastion_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 =''  # 存放每次执行读取的内容
               foriteminprompt_input_list:
                   prompt =list(item.keys())[0]
                   input = item[prompt]

                   flag =False
                   whilestdout.find(prompt) == -1:
                       try:
                           stdout += channel.recv(65535).decode('utf-8')#.decode('utf-8')
                           flag =True
                       exceptExceptionase:
                           print('通过堡垒机:%s访问目标机:%s失败:%s'%  (bastion_host, target_host, e))
                           flag =False
                           break
                   ifflag:
                       channel.send(input)
                   else:# 未找到了对应提示
                       print('通过堡垒机:%s访问目标机:%s失败,可能是读取命令返回结果超时,或者没找到对应输入提示'  %  (bastion_host, target_host))
                       # return [False, '通过堡垒机:%s访问目标机:%s失败,可能是读取命令返回结果超时,或者没找到对应输入提示'  %  (bastion_host, target_host)]
                       return


               while not(stdout.rstrip().endswith(end_flag1)orstdout.rstrip().endswith(end_flag2)):
                   try:
                       stdout = channel.recv(2048).decode('utf-8')
                   exceptExceptionase:
                       print('通过堡垒机:%s访问目标机:%s失败:没出现成功登录提示符]$]#'% (bastion_host, target_host))
                       return

           channel.send(command+'\n')

           command_res =''  # 存放每次执行读取的内容
           while not(command_res.endswith(end_flag1)orcommand_res.endswith(end_flag2)):
               try:
                   command_res = channel.recv(2048).decode('utf-8').strip()
               exceptExceptionase:
                   print('在目标机(IP: %s)上进行读取操作超时'% target_host)
                   break
           channel.close()
       exceptExceptionase:
          print('针对目标机:%s执行命令: %s出错%s'% (target_host, command, e))

目录
相关文章
|
2月前
|
数据采集 Web App开发 iOS开发
解决Python爬虫访问HTTPS资源时Cookie超时问题
解决Python爬虫访问HTTPS资源时Cookie超时问题
|
9月前
|
Linux Python
Linux 安装python3.7.6
本教程介绍在Linux系统上安装Python 3.7.6的步骤。首先使用`yum`安装依赖环境,包括zlib、openssl等开发库。接着通过`wget`下载Python 3.7.6源码包并解压。创建目标文件夹`/usr/local/python3`后,进入解压目录执行配置、编译和安装命令。最后设置软链接,使`python3`和`pip3`命令生效。
|
9月前
|
存储 应用服务中间件 开发工具
对象存储OSS-Python设置代理访问请求
通过 Python SDK 配置 nginx 代理地址请求阿里云 OSS 存储桶服务。示例代码展示了如何使用 RAM 账号进行身份验证,并通过代理下载指定对象到本地文件。
404 15
|
11月前
|
安全 Linux 开发者
|
12月前
|
Java Linux Python
Linux环境下 代码java调用python出错
Linux环境下 代码java调用python出错
241 4
|
12月前
|
NoSQL Linux Redis
linux安装单机版redis详细步骤,及python连接redis案例
这篇文章提供了在Linux系统中安装单机版Redis的详细步骤,并展示了如何配置Redis为systemctl启动,以及使用Python连接Redis进行数据操作的案例。
292 3
WK
|
12月前
|
存储 安全 索引
如何在Python中访问字典中的值
在Python中,访问字典(Dictionary)中的值非常简单。字典是一种无序的集合,它存储了键值对(key-value pairs),其中每个键都是唯一的,并映射到一个值上。要访问字典中的值,你需要使用键作为索引。
WK
304 0
|
12月前
|
Linux Python
linux 封装 python
linux 封装 python
79 0
|
12月前
|
Linux Python
Linux 下封装 Python
Linux 下封装 Python
92 0
|
12月前
|
Linux Python
Linux之centos安装clinkhouse以及python如何连接
Linux之centos安装clinkhouse以及python如何连接

热门文章

最新文章