conta's diary

思ったこと、やったことを書いてます。 twitter: @conta_

pythonのpexpectでsftp

ログファイルに”this is a pen”と書き込んでアップしてみる

import sys
import os
import subprocess
import pexpect
import pxssh


def time_instrument(func):
    '''
        time instrument
        時間計測用
    '''
    import functools
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print '%15s: %15s' % (func.__name__, end - start)
        return result
    return wrapper

@time_instrument
def create_file(outputFileName):
    cwd = "./"
    args = ['echo','this is a pen']
    logfilename = { "stdout" : "./capturestdout.log", "stderr" : "./capturestderr.log" }
    logfileobj = {}
    mode = "w"
    
    for stream, log in logfilename.iteritems():
        try:
            logfileobj[stream] = file(log, mode)
        except IOError:
            print "Cannot open logfile: %s" % log
            raise
    
    subproc_args = {'stdin'     : None,
                    'stdout'    : logfileobj['stdout'],
                    'stderr'    : logfileobj['stderr'],
                    'cwd'       : cwd,
                    }

    try:
        p = subprocess.Popen(args, **subproc_args)
    except OSError:
        print "Failed to execute command: %s" % args[0]
        sys.exit(1)
    ret = p.wait()
    if ret != 0:
        print "Return code: %d" %ret

@time_instrument
def main():
    # create testfile
    local_path = 'temp'
    filename = 'capturestdout.log'
    if not os.path.exists(local_path):
        os.mkdir(local_path)
    os.chdir(local_path)
    create_file(filename)
    
    # upload
    hostname = 'ホスト'
    username = 'ユーザー'
    password = 'パス'
    
    child = pexpect.spawn('sftp %s@%s' % (username, hostname) )
    child.expect('sword: ', 10)
    child.sendline(password)
    child.expect('sftp> ')
    
    child.sendline('cd temp')
    child.expect('sftp> ')
    
    child.sendline('ls')
    child.expect('sftp> ')
    print child.before
    
    child.sendline('lls')
    child.expect('sftp> ')
    print child.before
    
    #child.sendline('put %s/%s'% (local_path, filename))
    child.sendline('put %s'% filename)
    child.expect('sftp> ')
    print child.before
    
    child.sendline('ls')
    child.expect('sftp> ')
    print child.before
    
    child.sendline ('bye')

if __name__ == '__main__':
    print "-- main --"
    main()
    print "-- end --"