Skip to content

Instantly share code, notes, and snippets.

@xingkaixin
Last active December 17, 2020 12:22
Show Gist options
  • Save xingkaixin/3b1c4bc28668dc16bd9e to your computer and use it in GitHub Desktop.
Save xingkaixin/3b1c4bc28668dc16bd9e to your computer and use it in GitHub Desktop.
Python pexpect sftp sample
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pexpect import *
#import pexpect
import sys
import os
def initFile(*filenames):
for filename in filenames:
if os.path.exists(filename):
os.remove(filename)
else:
pass
def newFile(filename):
with open(filename,'w') as f:
f.write('')
host = '*******'
user = '*******'
passwd = '*******'
remotepath = '/root/tmp'
filename1 = 'testfile'
filename2 = 'a'
initFile('succ','fail')
p = spawn('sftp %s@%s' %(user,host))
p.logfile = sys.stdout
try:
p.expect('(?i)password:')
x = p.sendline(passwd)
x = p.expect(['Permission denied','sftp>'])
if x == 0:
print 'Permission denied for password:'
print password
p.kill(0)
else:
x = p.sendline('cd ' + remotepath)
x = p.expect('sftp>')
x = p.sendline('put ' + filename1)
x = p.expect('sftp>')
x = p.sendline('put ' + filename2)
x = p.expect('sftp>')
x = p.isalive()
x = p.close()
retval = p.exitstatus
newFile('succ')
except EOF:
print str(p)
print 'SFTP file transfer failed due to premature end of file.'
newFile('fail')
except TIMEOUT:
print str(p)
print 'SFTP file transfer failed due to timeout.'
newFile('fail')
#! /bin/sh
succ="succ"
fail="fail"
for i in `seq 1 3`;do
echo $i
if [ $i -eq 3 ]
then break
elif [ -f $succ ]
then break
elif [ -f $fail ]
then sleep 5s
else break
fi
done
@jdeltoft
Copy link

jdeltoft commented Jul 6, 2017

Also, you might want to show people how to use raw_input to get the password rather than hardcode.

So change it to

passwd = raw_input('Type in your password:')

@pghole
Copy link

pghole commented Dec 17, 2020

Thanks for the script. However, I am getting

Are you sure you want to continue connecting (yes/no)? string when logging into sftp server the first time. After that I use p.interact(), so that user can type yes/no. But I want to send the password like you have sent (from the script), not the user entering it. Can you pls. help how can I switch back to my script after, taking yes/no from user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment