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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With