python 交互shell pexpect

python真是个好东西,能够批量处理单纯的重复性工作。

本文推荐的python库:pexpect

在找到这个库之前,我曾用os.system来执行shell,缺乏交互,难以操作。

本文是个批量使用ssh管理服务器的例子,可以衍生出更多批量操作的工具。

————————————————————–

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import pexpect

def ssh_cmd(ip, passwd, cmd):

    ret = -1

    ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))

    try:

        i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)

        if i == 0 :

            ssh.sendline(passwd)

        elif i == 1:

            ssh.sendline('yes\n')

            ssh.expect('password: ')

            ssh.sendline(passwd)

        ssh.sendline(cmd)

        r = ssh.read()

        print r

        ret = 0

    except pexpect.EOF:

        print "EOF"

        ssh.close()

        ret = -1

    except pexpect.TIMEOUT:

        print "TIMEOUT"

        ssh.close()

        ret = -2
    return ret

———————————————————————

原文作者:

http://www.cnblogs.com/ma6174/archive/2012/05/25/2508378.html

转载随意~:陶醉seo » python 交互shell pexpect

赞 (37)
分享到:更多 ()