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

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 [email protected] 

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()
 

猜你喜欢

转载自blog.csdn.net/maibm/article/details/83111868