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

 

by:授客 QQ:1033553122 欢迎加入全国软件测试交流群:7156436

实现功能 1

测试环境 1

代码实践 2

注意 5

 

实现功能

远程登录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:\Program Files\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'


from

paramiko.client
import

AutoAddPolicy
from

paramiko.client
import

SSHClient

class

MySSHClient:

def

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

#
连接登录

    def

connect(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
=
''  
#
存放每次执行读取的内容

            for

item
in

prompt_input_list:
                prompt
=
list(item.keys())[0]
                input
= item[prompt]

flag
=
False

                while

stdout.find(prompt) == -1:
                    try:
                        stdout
+= channel.recv(65535).decode('utf-8')#.decode('utf-8')
                        flag
=
True

                    except

Exception
as

e:
                        print('通过堡垒机:%s
访问目标机:%s
失败:%s'

% (hostname, host_via_by_bastion, e))
                        flag
=
False

                        break
                if

flag:
                    channel.send(input)
                else:

# 未找到了对应提示

                    return

[False,

'通过堡垒机:%s
访问目标机:%s
失败,可能是读取命令返回结果超时,或者没找到对应输入提示'  
%
(hostname, host_via_by_bastion)]

flag
=
False

            while
not

(stdout.rstrip().endswith(end_flag1)
or

stdout.rstrip().endswith(end_flag2)):
                try:
                    stdout
= channel.recv(2048).decode('utf-8')
                    flag
=
True

                except

Exception
as

e:
                    print('通过堡垒机:%s
访问目标机:%s
失败:%s'

% (hostname, host_via_by_bastion, e))
                    flag
=
False

                    break
            if

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
=
False

                    while

stdout.find(prompt) == -1:
                        try:
                            stdout
+= channel.recv(65535).decode('utf-8')#.decode('utf-8')
                            flag
=
True

                        except

Exception
as

e:
                            print('通过堡垒机:%s
访问目标机:%s
失败:%s'

%  (bastion_host, target_host,
e))
                            flag
=
False

                            break
                    if

flag:
                        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)
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))
                        return

            channel.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)
                    break
            channel.close()
        except

Exception
as

e:
           print('针对目标机:%s
执行命令: %s
出错 %s'

% (target_host, command, e))

Python_基于Python同Linux进行交互式操作实现通过堡垒机访问目标机的更多相关文章

  1. Python之路,Day12 - 那就做个堡垒机吧

    Python之路,Day12 - 那就做个堡垒机吧   本节内容 项目实战:运维堡垒机开发 前景介绍 到目前为止,很多公司对堡垒机依然不太感冒,其实是没有充分认识到堡垒机在IT管理中的重要作用的,很多 ...

  2. Python成长笔记 - 基础篇 (十三)--堡垒机

    堡垒机架构 堡垒机的主要作用权限控制和用户行为审计,堡垒机就像一个城堡的大门,城堡里的所有建筑就是你不同的业务系统 , 每个想进入城堡的人都必须经过城堡大门并经过大门守卫的授权,每个进入城堡的人必须且 ...

  3. python之实现批量远程执行命令(堡垒机)

    python远程批量执行 我并不是一个专业的开发,我一直在学习linux运维,对于python也是接触不久,所以代码写的并不是很规范简洁. 前段时间一个同学找我一起做一个自动化运维平台,我对pytho ...

  4. 基于python实现Oracle数据库连接查询操作

    使用python语言连接Oracle数据库配置 #coding:utf-8 import cx_Oracle as oracle db=oracle.connect('root/123456@192. ...

  5. python第七十一天---堡垒机

    堡垒机的表结构图:

  6. 性能测试 基于Python结合InfluxDB及Grafana图表实时采集Linux多主机性能数据

    基于Python结合InfluxDB及Grafana图表实时采集Linux多主机性能数据   by:授客 QQ:1033553122 实现功能 测试环境 环境搭建 使用前提 使用方法 运行程序 效果展 ...

  7. 性能测试 基于Python结合InfluxDB及Grafana图表实时采集Linux多主机或Docker容器性能数据

    基于Python结合InfluxDB及Grafana图表实时采集Linux多主机性能数据   by:授客 QQ:1033553122 实现功能 1 测试环境 1 环境搭建 3 使用前提 3 使用方法 ...

  8. 基于python的堡垒机

    一 堡垒机的架构 堡垒机的核心架构通常如下图所示: 二.堡垒机的一般执行流程 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码) 用户登陆堡垒机,输入堡垒机用户名密码,显示当前用户 ...

  9. Python之路——堡垒机原理及其简单实现

    1 堡垒机基本概述 其从功能上讲,它综合了核心系统运维和安全审计管控两大主干功能,从技术实现上讲,通过切断终端计算机对网络和服务器资源的直接访问,而采用协议代理的方式,接管了终端计算机对网络和服务器的 ...

随机推荐

  1. stc15f104w模拟串口使用

    stc15f104w单片机体积小,全8个引脚完全够一般的控制使用,最小系统也就是个电路滤波----加上一个47uf电容和一个103电容即可,但因为其是一个5V单片机,供电需要使用5V左右电源. 该款单 ...

  2. python(leetcode)-重复元素算法题

    leetcode初级算法 问题描述 给定一个整数数组,判断是否存在重复元素. 如果任何值在数组中出现至少两次,函数返回 true.如果数组中每个元素都不相同,则返回 false. 该问题表述非常简单 ...

  3. java提高(1)---异常

    异常 一.异常与错误的区别 再讲异常之前我们就应该要知道异常和错误的区别 Error类和Exception类的父类都是throwable类,他们的区别是: Error类一般是指与虚拟机相关的问题,如系 ...

  4. Linux编程 16 文件权限(组管理 groupadd, groupmod,文件权限介绍)

    一.用户组 前面章节知道用户账户在控制单个用户安全性方面很好,但涉及到共享资源或把用户类型分组时,组概念就出来了. 组权限允许多个用户对系统中的对象(比如文件,目录,设备等)共享一组共用的权限. 在c ...

  5. AndroidStudio项目提交(更新)到github最详细步骤

    在使用studio开发的项目过程中有时候我们想将项目发布到github上,以前都是用一种比较麻烦的方式(cmd)进行提交,最近发现studio其实是自带这种功能的,终于可以摆脱命令行了. 因为自己也没 ...

  6. 【EF6学习笔记】(四)弹性连接及命令拦截调试

    本章原文地址:Connection Resiliency and Command Interception 原文有些地方讲的比较细,个人根据实际理解做些缩减,或者加入一些个人理解: 第1部分 弹性连接 ...

  7. python干掉pycache

    当第一次运行 python 脚本时,解释器会将 *.py 脚本进行编译并保存到 __pycache__ 目录 下次执行脚本时,若解释器发现你的 *.py 脚本没有变更,便会跳过编译一步,直接运行保存在 ...

  8. 【Go】优雅的读取http请求或响应的数据-续

    原文链接:https://blog.thinkeridea.com/201902/go/you_ya_de_du_qu_http_qing_qiu_huo_xiang_ying_de_shu_ju_2 ...

  9. ZOOKEEPER典型应用场景解析

    zookeeper实现了主动通知节点变化,原子创建节点,临时节点,按序创建节点等功能.通过以上功能的组合,zookeeper能够在分布式系统中组合出很多上层功能.下面就看几个常用到的场景,及使用方式和 ...

  10. meterpreter持久后门

    meterpreter持久后门 背景:meterpreter好是好,但有个大问题,只要目标和本机连接断开一次后就再也连不上了,需要再次用exploit打才行!!! 解决方案:在与目标设备的meterp ...