编程语言
首页 > 编程语言> > Pexpect简单的测试——一个 expect的python实现

Pexpect简单的测试——一个 expect的python实现

作者:互联网

Pexpect简单的测试——一个 expect的python实现

 

@for & ever 2010-07-03

 

Pexpect 是一个自动控制的 Python 模块,可以用来ssh、ftp、passwd、telnet 等命令行进行自动交互。
官方网站是 http://www.noah.org/
通过它,可以实现类似 expect 的操作。
例如我们可以用它来写python脚本,实现批量对一系列(大量的、配置相同的)的linux服务器进行操作。

 

一、安装方式
以root用户依次执行如下命令:
 wget http://pexpect.sourceforge.net/pexpect-2.3.tar.gz
 tar xzf pexpect-2.3.tar.gz
 cd pexpect-2.3
 sudo python ./setup.py install


二、简单测试

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_test.py
'''
Created on 2010-7-2

@author: forever
'''
import pexpect

if __name__ == '__main__':
    user = 'forever'
    ip = '192.168.0.200'
    mypassword = 'forever'
    
    print user
    child = pexpect.spawn('ssh %s@%s' % (user,ip))
    child.expect ('password:')
    child.sendline (mypassword)
    
    child.expect('$')
    child.sendline('sudo -s')
    child.expect (':')
    child.sendline (mypassword)
    child.expect('#')
    child.sendline('ls -la')
    child.expect('#')
    print child.before   # Print the result of the ls command.
    child.sendline("echo '112' >> /home/forever/1.txt ")
    child.interact()     # Give control of the child to the user.

    pass


原文:https://blog.csdn.net/forandever/article/details/5711270 
版权声明:本文为博主原创文章,转载请附上博文链接!

标签:__,pexpect,python,sendline,expect,child,Pexpect
来源: https://blog.csdn.net/bang152101/article/details/88759699