Skip to content

Instantly share code, notes, and snippets.

@suryadana
Created September 28, 2018 10:48
Show Gist options
  • Save suryadana/5d21338b731fff0875c91efd9018a9b0 to your computer and use it in GitHub Desktop.
Save suryadana/5d21338b731fff0875c91efd9018a9b0 to your computer and use it in GitHub Desktop.
# requirements.txt
# flask
# python-magic
import magic, io
from flask import Flask, jsonify, request, send_file
from ftplib import FTP
app = Flask(__name__)
main_path = '/home/ftp'
def get_type(name):
name_split = name.split('.')
if len(name_split) < 2:
return None
return name_split[len(name_split)-1]
def get_size(ftp, name):
try:
return ftp.size(name)
except:
return None
def call_download(data):
print(data)
def get_result(ftp, main_folter=None):
result = []
nlst = ftp.nlst()
if len(nlst) == 0:
return result
for item in nlst:
data = {
'name': '',
'type': 'dir',
'size': 0,
'link': '',
'sub': []
}
data['name'] = item
if get_type(item):
data['type'] = get_type(item)
if get_size(ftp, item):
data['size'] = get_size(ftp, item)
else:
ftp.cwd('..')
data['size'] = get_size(ftp, item)
pwd = ftp.pwd()
pwd = pwd.replace(main_path, '')
data['link'] = request.host_url + 'download/?file={}'.format(pwd + '/' +item)
else:
if main_folter:
ftp.cwd(main_folter)
pwd = ftp.pwd()
current_foder = pwd + '/' + item
ftp.cwd(current_foder)
data['sub'] = get_result(ftp, current_foder)
data['type'] = 'dir'
result.append(data)
return result
@app.route('/')
def index():
ftp = FTP('192.168.5.38')
ftp.login(user='', passwd='')
result = get_result(ftp)
return jsonify(result)
@app.route('/download/')
def download():
ftp = FTP('192.168.5.38')
ftp.login(user='', passwd='')
file = request.args.get('file')
try:
# LFI protection
file = file.replace('..', '')
download_file = io.BytesIO()
file_path = main_path + file
ftp.retrbinary('RETR {}'.format(file_path), download_file.write, 1024)
download_file.seek(0)
mime = magic.Magic(mime=True)
mime_file = mime.from_buffer(download_file.read())
return send_file(
download_file,
mimetype=mime_file,
as_attachment=True,
attachment_filename=file
)
except:
return 'File not found'
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment