我们知道pexpect是一个Python用于很多的开发或者自动化场景中的常见模块,它是一个用来通过启动子程序,
使用正则表达式对程序输出做出特定响应,并作相应的响应。
之前几篇文章有给大家聊了下pexpect和核心类方法,大家如果对pexpect还不太了解,可以关注我,查看
幕客之前写的文章,都有介绍。
接下来我介绍一个具体场景实现ssh的用户密码登录,和ssh的公钥私钥登录。
功能实现的脚本如下:
# -*- coding: utf-8 -*-
#!/usr/bin/python
#########################################################################
# File Name: ssh_pexpect.py
# Program function:
# Author:Jeson
# Created Time: Sun Dec 3 10:05:05 2017
#========================================================================
import pexpect
def login_ssh_passwd(port="",user="",host="",passwd=""):
'''函数:用于实现pexepect实现ssh的自动化用户密码登录'''
# print 'ssh -p %s %s@%s' % (port,user, host)
if port and user and host and passwd:
ssh = pexpect.spawn('ssh -p %s %s@%s' % (port,user, host))
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password: ')
ssh.sendline(passwd)
index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
print "logging in as root!"
elif index == 1:
print "logging in as non-root!"
elif index == 2:
print "logging process exit!"
elif index == 3:
print "logging timeout exit"
else:
print "Parameter error!"
def login_ssh_key(keyfile="",user="",host="",port=""):
'''函数:用于实现pexepect实现ssh的自动化密钥登录'''
if port and user and host and keyfile:
ssh = pexpect.spawn('ssh -i %s -p %s %s@%s' % (keyfile,port,user, host))
i = ssh.expect( [pexpect.TIMEOUT,'continue connecting (yes/no)?'], timeout=2)
# print '...................................',0
if i == 1:
ssh.sendline('yes\n')
index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
else:
index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
print "logging in as root!"
elif index == 1:
print "logging in as non-root!"
elif index == 2:
print "logging process exit!"
elif index == 3:
print "logging timeout exit"
else:
print "Parameter error!"
def main():
'''主函数:实现两种方式分别的登录'''
# login_ssh_passwd(port='22',user='root',host='192.168.1.102',passwd='imoocc')
login_ssh_key(keyfile="/tmp/id_rsa2",port='22',user='root',host='192.168.1.102')
if __name__ == "__main__":
main()
是否感兴趣,大家可以用自己的环境,尝试使用。