Python利用Paramiko实现堡垒机跳板机远程命令执行

沈知远
沈知远
发布时间:2026-10-13 | 4人浏览过
原创

本文介绍如何使用Python的Paramiko库通过堡垒机(跳板机)执行远程服务器命令。核心原理是先连接堡垒机建立会话,再通过invoke_shell发起新的SSH连接至目标业务服务器。文中提供了完整的Python代码示例及执行输出结果,展示了从登录堡垒机、跳转至目标主机到执行ifconfig命令的全过程,适用于需要提升运维安全级别的场景。

Python堡垒机远程命令执行概述

本文详细介绍如何使用Python实现通过堡垒机模式执行远程命令的操作方法,供读者参考学习。

一、背景说明

部署堡垒机虽然提升了运营安全等级,但也增加了日常运维成本。作为管理流量的中转节点,所有针对业务服务器的管理请求(如SSH协议)均需经过该节点。典型流程为:运维人员先通过SSH登录堡垒机,再由堡垒机SSH跳转至各业务服务器进行维护。

利用Paramiko库的invoke_shell机制,可实现经由堡垒机对服务器进行操作。其原理是:先通过SSHClient.connect连接至堡垒机,随后开启一个新的SSH会话(session),并通过该新会话执行“ssh user@IP”命令,从而实现远程命令的执行。

二、代码实现

Paramiko实现堡垒机跳板代码示例


#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 相关产品和应用

全部下载

专题列表