Python实现堡垒机模式下远程命令执行操作示例


Posted in Python onMay 09, 2019

本文实例讲述了Python实现堡垒机模式下远程命令执行操作。分享给大家供大家参考,具体如下:

一 点睛

堡垒机环境在一定程度上提升了运营安全级别,但同时也提高了日常运营成本,作为管理的中转设备,任何针对业务服务器的管理请求都会经过此节点,比如SSH协议,首先运维人员在办公电脑通过SSH协议登录堡垒机,再通过堡垒机SSH跳转到所有的业务服务器进行维护操作。

Python实现堡垒机模式下远程命令执行操作示例

我们可以利用paramiko的invoke_shell机制来实现通过堡垒机实现服务器操作,原理是SSHClient.connect到堡垒机后开启一个新的SSH会话 (session),通过新的会话运行“ssh user@IP”去实现远程执行命令的操作。

二 代码

#coding=utf-8
#!/usr/bin/env python
import paramiko
import os,sys,time
hostname="192.168.0.120"      # 定义业务服务器
username="root"
password="123456"
blip="192.168.0.101"        # 定义业务堡垒机
bluser="root"
blpasswd="123456"
port=22
passinfo='\'s password: '      # 输入服务器密码的前标志串
paramiko.util.log_to_file('syslogin.log')
ssh=paramiko.SSHClient()      # ssh登录堡垒机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=blip,username=bluser,password=blpasswd)
#new session
channel=ssh.invoke_shell()     # 创建会话,开启命令调用
channel.settimeout(10)       # 会话命令执行超时时间,单位为秒
buff = ''
resp = ''
channel.send('ssh '+username+'@'+hostname+'\n')    # 执行ssh登录业务主机
while not buff.endswith(passinfo):           # ssh登录的提示信息判断,输出串尾含有"\'s password:"时退出while循环
  try:
    resp = channel.recv(9999)
  except Exception,e:
    print 'Error info:%s connection time.' % (str(e))
    channel.close()
    ssh.close()
    sys.exit()
  buff += resp
  if not buff.find('yes/no')==-1:          # 输出串尾含有"yes/no"时发送"yes"并回车
    channel.send('yes\n')
print(buff)
print("*************************************************************************************")
channel.send(password+'\n')              # 发送业务主机密码
buff=''
while not buff.endswith('# '):             # 输出串尾为"# "时说明校验通过并退出while循环
  resp = channel.recv(9999)
  if not resp.find(passinfo)==-1:          # 输出串尾含有"\'s password: "时说明 密码不正确,要求重新输入
    print 'Error info: Authentication failed.'
    channel.close()                # 关闭连接对象后退出
    ssh.close()
    sys.exit()
  buff += resp
channel.send('ifconfig\n')               # 认证通过后发送ifconfig命令来查看结果
buff=''
try:
  while buff.find('# ')==-1:
    resp = channel.recv(9999)
    buff += resp
except Exception, e:
  print "error info:"+str(e)
print buff                       # 打印输出串
channel.close()
ssh.close()

三 输出结果

E:\Python\python_auto_maintain\venv\Scripts\python.exe E:/Python/python_auto_maintain/6_3_2.py
Last login: Thu Feb 28 22:00:07 2019 from 192.168.0.106
hello cakin24!
ssh root@192.168.0.120
[root@slave2 ~]# ssh root@192.168.0.120
root@192.168.0.120's password:
*************************************************************************************
ifconfig
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.120  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 fe80::a00:27ff:fe0a:6e8a  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:0a:6e:8a  txqueuelen 1000  (Ethernet)
        RX packets 2046  bytes 179711 (175.4 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1408  bytes 148744 (145.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 404117  bytes 68752333 (65.5 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 404117  bytes 68752333 (65.5 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
qbr07d54630-64: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1450
        ether 42:76:47:57:b2:75  txqueuelen 1000  (Ethernet)
        RX packets 11  bytes 572 (572.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
qvb07d54630-64: flags=4419<UP,BROADCAST,RUNNING,PROMISC,MULTICAST>  mtu 1450
        inet6 fe80::4076:47ff:fe57:b275  prefixlen 64  scopeid 0x20<link>
        ether 42:76:47:57:b2:75  txqueuelen 1000  (Ethernet)
        RX packets 12  bytes 816 (816.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 8  bytes 648 (648.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
qvo07d54630-64: flags=4419<UP,BROADCAST,RUNNING,PROMISC,MULTICAST>  mtu 1450
        inet6 fe80::dcbe:efff:feb7:5d52  prefixlen 64  scopeid 0x20<link>
        ether de:be:ef:b7:5d:52  txqueuelen 1000  (Ethernet)
        RX packets 8  bytes 648 (648.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 12  bytes 816 (816.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
[root@localhost ~]#

更多关于Python相关内容可查看本站专题:《Python字符串操作技巧汇总》、《Python常用遍历技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
基于Python实现通过微信搜索功能查看谁把你删除了
Jan 27 Python
Python中set与frozenset方法和区别详解
May 23 Python
python导入csv文件出现SyntaxError问题分析
Dec 15 Python
用TensorFlow实现戴明回归算法的示例
May 02 Python
Python设计模式之职责链模式原理与用法实例分析
Jan 11 Python
Python3日期与时间戳转换的几种方法详解
Jun 04 Python
PIL对上传到Django的图片进行处理并保存的实例
Aug 07 Python
Python实现非正太分布的异常值检测方式
Dec 09 Python
如何使用Python发送HTML格式的邮件
Feb 11 Python
python3注册全局热键的实现
Mar 22 Python
解决Pycharm 运行后没有输出的问题
Feb 05 Python
PySwarms(Python粒子群优化工具包)的使用:GlobalBestPSO例子解析
Apr 05 Python
python3.6使用tkinter实现弹跳小球游戏
May 09 #Python
使用GitHub和Python实现持续部署的方法
May 09 #Python
在win10和linux上分别安装Python虚拟环境的方法步骤
May 09 #Python
Python Excel处理库openpyxl使用详解
May 09 #Python
python3实现小球转动抽奖小游戏
Apr 15 #Python
Django保护敏感信息的方法示例
May 09 #Python
Python基于scipy实现信号滤波功能
May 08 #Python
You might like
php合并js请求的例子
2013/11/01 PHP
php操作redis中的hash和zset类型数据的方法和代码例子
2014/07/05 PHP
PHP函数http_build_query使用详解
2014/08/20 PHP
讲解WordPress开发中一些常用的debug技巧
2015/12/18 PHP
一个简单的php MVC留言本实例代码(必看篇)
2016/09/22 PHP
jquery 添加节点的几种方法介绍
2013/09/04 Javascript
jQuery中bind()方法用法实例
2015/01/19 Javascript
JavaScript实现重置表单(reset)的方法
2015/04/02 Javascript
Node.js实现Excel转JSON
2015/04/24 Javascript
javascript创建函数的20种方式汇总
2015/06/23 Javascript
Bootstrap网格系统详解
2016/04/26 Javascript
jquery radio的取值_radio的选中_radio的重置方法
2016/09/20 Javascript
JS实用的带停顿的逐行文本循环滚动效果实例
2016/11/23 Javascript
微信小程序 获取当前地理位置和经纬度实例代码
2016/12/05 Javascript
JS和canvas实现俄罗斯方块
2017/03/14 Javascript
jQuery实现火车票买票城市选择切换功能
2017/09/15 jQuery
vue项目中用cdn优化的方法
2018/01/03 Javascript
如何封装了一个vue移动端下拉加载下一页数据的组件
2019/01/06 Javascript
小程序多图列表实现性能优化的方法步骤
2019/05/28 Javascript
从零撸一个pc端vue的ui组件库( 计数器组件 )
2019/08/08 Javascript
JS获取当前时间戳方法解析
2020/08/29 Javascript
haskell实现多线程服务器实例代码
2013/11/26 Python
python中xrange用法分析
2015/04/15 Python
Python加密方法小结【md5,base64,sha1】
2017/07/13 Python
python表格存取的方法
2018/03/07 Python
python中的单引号双引号区别知识点总结
2019/06/23 Python
python 子类调用父类的构造函数实例
2020/03/12 Python
python进度条显示之tqmd模块
2020/08/22 Python
浅谈Python描述数据结构之KMP篇
2020/09/06 Python
Python 爬虫批量爬取网页图片保存到本地的实现代码
2020/12/24 Python
美国受欢迎的女性牛仔裤品牌:DL1961
2016/11/12 全球购物
Aquatalia官网:意大利著名鞋履品牌
2019/09/26 全球购物
大学生大二自我鉴定
2013/10/28 职场文书
公司员工离职证明书
2014/10/04 职场文书
干部年终考核评语
2015/01/04 职场文书
Python实现滑雪小游戏
2021/09/25 Python