Python expect模块pexpect简单应用

发布时间: 更新时间: 总字数:403 阅读时间:1m 作者: 分享 复制网址

Python pexpect命令与ssh、ftp、passwd、telnet 等命令行进行自动交互介绍。

简介

Pexpect 是一个自动控制的 Python 模块,可以用来ssh、ftp、passwd、telnet 等命令行进行自动交互。 官方网站是 http://www.noah.org/。通过它,可以实现类似 expect 的操作。

例如我们可以用它来写python脚本,实现批量对一系列(大量的、配置相同的)的linux服务器进行操作。

如果你对expect还不太了解,那么可以参考Linux expect 介绍与用法:http://xiexianbin_cn/linux/expect。

pexpect 安装方式

以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

简单测试

编写一个简单的脚本pexpect_test.py测试一下:

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

@author: forever
'''
import pexpect

if __name__ == '__main__':
    user = 'http://xiexianbin_cn'
    ip = 'aliyun.xiexianbin.cn'
    mypassword = 'xiexianbin'

    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/1.txt ")
    child.interact()     # Give control of the child to the user.

    pass
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数