Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SFTP using pexpect python module

I am trying to SFTP a file using the pexpect module.

sftp_opts = ['-o', 'Port=%s' % port,
                 '-o', 'UserKnownHostsFile=%s' % known_hosts_file,
                 '-o', 'PasswordAuthentication=yes',
                 '%s@%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

It looks like I am able to connect & get authenticated thru SSH, but the retval is always 1 (exit status) and the file doesnt get sftp'ed.

Am I missing something here?

If I try to wait on p (p.wait() instead of p.close()) - it never returns.

like image 977
user1082044 Avatar asked Mar 19 '26 00:03

user1082044


1 Answers

To summarize as an answer:

  • turn on debug logging to get a better idea of what is going wrong; from David K. Hess

  • Use pexpect but automate scp instead of sftp; even better use ssh keys; from jornam

  • use sftp function from paramiko ssh lib; from ephemient

like image 126
Lars Nordin Avatar answered Mar 20 '26 12:03

Lars Nordin