Last active
December 17, 2020 12:22
-
-
Save xingkaixin/3b1c4bc28668dc16bd9e to your computer and use it in GitHub Desktop.
Python pexpect sftp sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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') | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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 |
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:')
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
You have a bug in line 40 of pysftp.py. You should change that to:
print ("passwd")