资讯专栏INFORMATION COLUMN

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

lijy91 / 1704人阅读

#!/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==========
")
    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("=====================
")
        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...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/37855.html

相关文章

  • linux文件系统和日志分析

    摘要:通常情况下不需要关注单个的大小,而是需要重点关注的总数,的总字节在格式化的时候就给定了,执行命令即可查看每个硬盘分区对应的总数和已经使用的数量。 inode和block概述一:1、文件数据包括源信息与实际数据文件存储在硬盘上,硬盘最小存储单位是扇区。每个扇区存储512字节block (块):连续的八个扇区组成一...

    waruqi 评论0 收藏0

发表评论

0条评论

lijy91

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<