python expect模块pexpect简单应用

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

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

如果你对expect还不太了解,那么可以参考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://www.pythonclub.org'
    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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值