python学习笔记 --paramiko 实现堡垒机登陆

本文介绍了一个使用Python的Paramiko库进行SSH连接的示例代码,演示了如何通过堡垒机跳转到目标主机并执行命令的过程,适用于自动化运维场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

paramiko 可以实现ssh安全连接,ansible 工具底层也是使用的paramiko  ,参考刘天斯python自动化运维第六章

[root@localhost ~]# cat  paramiko3.py 
#!/usr/bin/env python
import paramiko
import os,sys,time

hostname="192.168.1.20"     #业务主机ip
username="root"
password="root"

blip="192.168.0.21"   #堡垒机ip
bluser="root"
blpasswd="waihai"

port=22
passinfo='\'s password: '                #ssh 登陆输入密码时的前缀
paramiko.util.log_to_file('syslogin.log')

ssh=paramiko.SSHClient()
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 root@192.168.1.20 

while not buff.endswith(passinfo):               #是否以字符串 's password 结尾            
    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:       #模拟ssh登陆是输入yes 
        channel.send('yes\n')
    buff=''

channel.send(password+'\n')       #发送密码

buff=''
while not buff.endswith('# '):
    resp = channel.recv(9999)
    if not resp.find(passinfo)==-1:
        print 'Error info: Authentication failed.'
        channel.close()
        ssh.close()
        sys.exit() 
    buff += resp

channel.send('ping www.qq.com -c 4\n')             发送测试命令 ping  
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()
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值