I am using Paramiko to connect to the SFTP server from my local machine and download txt files from remote path. I am able to make successful connection and can also print the remote path and the files but i cannot get the files locally. I can print the file_path
and file_name
but not able to download all the files. Below is the code I am using:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password, port=port)
remotepath = '/home/blahblah'
pattern = '"*.txt"'
stdin,stdout,stderr = ssh.exec_command("find {remotepath} -name {pattern}".format(remotepath=remotepath, pattern=pattern))
ftp = ssh.open_sftp()
for file_path in stdout.readlines():
file_name = file_path.split('/')[-1]
print(file_path)
print(file_name)
ftp.get(file_path, "/home/mylocalpath/{file_name}".format(file_name=file_name))
I can see the file_path
and file_name
like below from print
statement but get error while using ftp.get for multiple files. I can copy a single file by hardcoding the name on source and destination.
file_path = '/home/blahblah/abc.txt'
file_name = 'abc.txt'
file_path = '/home/blahblah/def.txt'
file_name = 'def.txt'
I see one file is downloaded and then i get the following error:
FileNotFoundErrorTraceback (most recent call last)
Error trace:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "...anaconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 769, in get
with open(localpath, 'wb') as fl:
FileNotFoundError: [Errno 2] No such file or directory: 'localpath/abc.txt\n'
shlex.quote()
in Python 3 orpipes.quote()
in Python 2 to get strings that are safe to substitute intossh.exec_command()
; otherwise, someone asking this program to retrieve files from/tmp/$(rm -rf ~)
could cause you to have a really bad day. – Charles Duffyd=/home/blahblah/$'\n'/etc/passwd$'\n'; mkdir "$d" && touch "$d/foo"
, then yourfind
would return/etc/passwd
as a result, and your code would copy it over despite not being under/home/blahblah
. – Charles Duffy-print0
on thefind
command, and iterate overstdout.read().split('\0')[:-1]
instead of usingstdout.readlines()
. There's probably a more efficient way to fix that too. – Charles Duffyfind
to only look for types of things thatsftp.get()
will work with). – Charles Duffy