zoukankan      html  css  js  c++  java
  • python pexpect模块

    import pexpect
     pexpect.run("ls /tmp", withexitstatus=1)
    
    chk = pexpect.spawn("ls -l /tmp/")
    chk = pexpect.spawn("ls", ['-l', '/tmp/'])
    
    ssh_k = pexpect.spawn('ssh root@192.168.1.245 -p22')
    ssh_k.expect("password:")
    ssh_k.expect("[p,P]assword:")
    #匹配多种结果
    ssh_k.expect([pexpect.TIMEOUT, pexpect.EOF, "password"])

    pexpect向子程序发送指令

    def login_ssh_passwd(port="",user="",host="",passwd=""):
        '''函数:用于实现pexepect实现ssh的自动化用户密码登录'''
    
        # print 'ssh -p %s %s@%s' % (port,user, host)
        if  port and user and host and passwd:
            ssh = pexpect.spawn('ssh -p %s %s@%s' % (port,user, host))
            i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
            if i == 0 :
                ssh.sendline(passwd)
            elif i == 1:
                ssh.sendline('yes
    ')
                ssh.expect('password: ')
                ssh.sendline(passwd)
            index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
    
            if index == 0:
                print "logging in as root!"
                ssh.interact()
            elif index == 1:
                print "logging process exit!"
            elif index == 2:
                print "logging timeout exit"
        else:
            print "Parameter error!"
    def login_ssh_key(keyfile="",user="",host="",port=""):
        '''函数:用于实现pexepect实现ssh的自动化密钥登录'''
    
        if  port and user and host and keyfile:
            ssh = pexpect.spawn('ssh -i %s -p %s %s@%s' % (keyfile,port,user, host))
            i = ssh.expect( [pexpect.TIMEOUT,'continue connecting (yes/no)?'], timeout=2)
            # print '...................................',0
            if i == 1:
                ssh.sendline('yes
    ')
                index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
            else:
                index = ssh.expect (["#", pexpect.EOF, pexpect.TIMEOUT])
            if index == 0:
                print "logging in as root!"
                ssh.interact()
            elif index == 1:
                print "logging process exit!"
            elif index == 2:
                print "logging timeout exit"
        else:
            print "Parameter error!"
  • 相关阅读:
    i++与++i
    acm语录
    c# SQL2000 access 远程连接操作
    C# 四舍五入函数
    WINDOWS 2003 远程桌面记录登陆IP
    jquery 资源
    php google baidu 分页
    Solutions to place plus or minus signs to a nonzero digits sequence 123456789 so that result of thus described arithmetic opera
    VB获取网页下文字的链接地址
    php cache 缓存方法类一
  • 原文地址:https://www.cnblogs.com/majianyu/p/12696514.html
Copyright © 2011-2022 走看看