python之pexpect用法及scp

发布时间:2019-09-02 07:49:32编辑:auto阅读(2707)

     import pexpect

    def scp_cmd():
        passwd='*******'
        passwd1='*******'
        ssh = pexpect.spawn('scp -rp root@192.168.1.107:/backup root@192.168.1.102:/data')
        r = ''
        try:
            i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
            if i == 0 :
                ssh.sendline(passwd)
            elif i == 1:
                ssh.sendline('yes')
                ssh.expect('password:')
                ssh.sendline(passwd)
            b=ssh.expect(['password: ','continue connecting (yes/no)?'])
            if b==0:
                ssh.sendline(passwd1)
            elif b==1:
                ssh.sendline('yes')
                ssh.expect('password:')
                ssh.sendline(passwd1)
        except pexpect.EOF:
            ssh.close()
        else:
            r = ssh.read()
            ssh.expect(pexpect.EOF)
            ssh.close()
        return r
    scp_cmd()

关键字