pyhon项目之后pexpect使用

pyhon项目之后pexpect使用
1.安装
pip3.6 install pexpect

实例1 ssh 登陆linux 服务器,并且执行命令

#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time : 2019/10/24 17:33
# @Author : zoulixiang
# @Site :
# @File : ssh_login_password.py
# @Software: PyCharm
import pexpect

def login_ssh_passwd(port="",user="",host="",passwd="",command=""):
'''函数:用于实现pexepect实现ssh的自动化用户密码登陆'''

#print 'ssh -p %s %s@%s' %(port, user, host)
if port and user and host and passwd and command:
ssh = pexpect.spawn('ssh -p %s %s@%s %s' %(port, user, host, command))
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0:
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes ')
ssh.expect('password: ')
ssh.sendline(passwd)

index = ssh.expect(["#",pexpect.EOF, pexpect.TIMEOUT])

if index == 0:
print("logging in as root!")
#执行命令
ssh.before,ssh.after
elif index == 1:
print("logging in as non-root!")
print(ssh.before)
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="", command=""):
'''函数:用于实现pexepect实现ssh的自动化密钥登陆'''
if port and user and host and keyfile and command:
ssh = pexpect.spawn('ssh -i %s -p %s %s@%s %s '% (keyfile,port,user,host,command))
i = ssh.expect([pexpect.TIMEOUT,'continue connecting (yes/no)?'], timeout=5)
print("-"*10)
print(i)
if i == 0:
ssh.sendline('yes ')
index = ssh.expect(["#", pexpect.EOF, pexpect.TIMEOUT])
else:
index = ssh.expect(["#", pexpect.EOF, pexpect.TIMEOUT])
print(index)

if index == 0:
#执行命令
ssh.before,ssh.after
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():
'''主函数:实现两种f方法分别登陆'''
#command = "hostname"
#login_ssh_passwd(port='22', user='root',host='192.168.3.201',passwd='matrix@178',command='pwd')
login_ssh_key(keyfile="/root/.ssh/id_rsa",port='22',user='root',host='192.168.3.201', command="mkdir -p /root/test2222")

if __name__ == '__main__':
main()

原文地址:https://www.cnblogs.com/zoulixiang/p/11737026.html