[Level 2] Pexpect of Python.

#!/bin/env python
import os, sys
import StringIO


class AuthorizedKeyError(Exception):
    def __init__(self, host):
        self.value = 'Did not be authorized by remote server(%s)!!!' % host
    def __str__(self):
        return repr(self.value)

class FileSyncManager:
    def fileSync(self, user, host, file):
        output = StringIO.StringIO()
        sCmd = 'scp %s %s@%s:%s' % (file, user, host, file)
        self.debug(sCmd)
        
        scp = pexpect.spawn(sCmd)
        scp.logfile = output
        
        while True:
            index = scp.expect(["Are you sure you want to continue connecting (yes/no)?", "password:" ,pexpect.TIMEOUT, pexpect.EOF]) 
            if index == 0: 
                scp.sendline('yes')
            elif index == 1:
                raise AuthorizedKeyError(host)
            else:
                break
            
        if scp.exitstatus:
            error_message = output.getvalue().rstrip()
            self.debug(error_message)
            print error_message
            
        scp.close(True)
Wish this helps.  regards, Stanley Huang

Comments

Popular posts from this blog

[Level 2] Shell Interactive With Zenity Episode 5 -- list

[Level 2] iif in Python