2011-12-05 85 views
1

我想使用pexpect模塊來SFTP文件。使用pexpect python模塊的SFTP

sftp_opts = ['-o', 'Port=%s' % port, 
       '-o', 'UserKnownHostsFile=%s' % known_hosts_file, 
       '-o', 'PasswordAuthentication=yes', 
       '%[email protected]%s' % (user, host)] 
    p = pexpect.spawn('sftp', sftp_opts) 

    try: 
     p.expect('(?i)password:') 
     x = p.sendline(password) 
     x = p.expect('sftp>') 
     x = p.sendline('cd ' + remote_dir) 
     x = p.expect('sftp>') 
     x = p.sendline('put ' + filename) 
     x = p.expect('sftp>') 
     x = p.isalive() 
     x = p.close() 
     retval = p.exitstatus 
    except pexpect.EOF: 
     print('SFTP file transfer failed due to premature end of file.') 
     return False 
    except pexpect.TIMEOUT: 
     print('SFTP file transfer failed due to timeout.') 
     return False 

它看起來像我能夠連接&得到驗證通SSH,但RETVAL始終爲1(退出狀態)和文件犯規得到sftp'ed。

我在這裏錯過了什麼嗎?

如果我嘗試等待p(p.wait()而不是p.close()) - 它永遠不會返回。

+2

[paramiko](http://www.lag.net/paramiko/)支持[SFTP](http://www.lag.net/paramiko/docs/paramiko.SFTP-class。 HTML)。 – ephemient

+0

@ephemient - paramiko比pexpect更好的選擇嗎? – user1082044

+0

你可以使用SSH公鑰與scp,這不需要pexepect。 – jordanm

回答

1

總結作爲一個答案:

  • 打開調試日誌得到了什麼錯誤的一個更好的想法;來自David K. Hess

  • 使用pexpect,但自動化scp而不是sftp;更好的使用SSH密鑰; from jornam

  • 使用sramp函數從paramiko ssh lib;來自ephemient