使用python-pexpect登录linux系统并发送命令

0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# filename: pexpect_test.py

import pexpect,time,sys
def sendCommt():
    demo = open("result.txt", "ab")
    demo.write('==========Log Tile: demo==========\n')
    print user
    child = pexpect.spawn('ssh %s@%s' % (user,ip))
    while True:
        i = child.expect(patterns)
        if i == CONTINUES:
            child.sendline(flag)
        elif i == PASSWD:
            child.sendline(passwd)
        elif i == OPFLAG:
            break
    for cmd in cmds:
        time.sleep(2)
        p = pexpect.spawn(cmd)
        p.logfile = demo
        p.write('=====================\n')
        p.expect(pexpect.EOF)
        print cmd
    demo.close()
    child.close()

if __name__ == '__main__':
    user = 'demo'
    ip = 'x.x.x.x'
    passwd = '1'
    cmds = ['ps','ls','pwd','ifconfig','date']
    patterns = ['Are you sure you want to continue connecting (yes/no)?','[Pp]assword:','#']
    CONTINUES,PASSWD,OPFLAG = range(len(patterns))
    flag = 'yes'
    group = '1'
    try:
        sendCommt()
    except pexpect.TIMEOUT:  
        print "TIMEOUT" 
    except pexpect.EOF:
        print "EOF"

参考文档:
http://www.ibm.com/developerworks/cn/lin...

你可能感兴趣的

载入中...