python pexpect模块

通过pexpect模块登录到远程主机,
1,从远程主机复制文件到本地服务器
2,从本地服务器复制文件到远程主机
3,查看远程主机IP地址并写入到create.txt文件中
4,查看远程主机docker信息并写入到create1.txt文件中
5,定义一个选择函数

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pexpect
password = "111111"
"""
定义函数:判断输出
"""
def yn(password):
    index = sp.expect(["yes/no", "assword"])
    print(index)
    if index == 0:
        sp.sendline("yes")
        sp.expect('password')
        sp.sendline(password)
    elif index == 1:
        sp.sendline(password)



sp = pexpect.spawn('/usr/bin/ssh root@192.168.124.150')      #远程登录主机
yn(password)
sp.expect('#')
sp.sendline('ip add >  /root/create.txt')              #获取网卡信息,并保存到create.txt文件中
sp.expect('#')

sp.sendline('scp /root/create.txt root@192.168.124.151:/tmp')   #复制本地文件到远程主机
yn(password)
sp.expect('#')
sp.sendline('scp root@192.168.124.151:/root/create /root/')     #复制远程主机文件到本地服务
yn(password)
sp.expect(pexpect.EOF)
sp.close()

  

原文地址:https://www.cnblogs.com/fanlong0212/p/13378262.html