summaryrefslogtreecommitdiff
path: root/FlaskService.py
blob: b3f7c2b5ac861cffffee58ec19e33f3edbc5d11f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from flask import Flask, request, send_file, after_this_request
import os
import subprocess
import socket

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MODIFIED_FOLDER'] = 'modified'

# Make sure the uploaded and modified folders exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['MODIFIED_FOLDER'], exist_ok=True)

@app.route('/api/v1/pcap/comment', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return "No file part", 400

    file = request.files['file']
    if file.filename == '':
        return "No selected file", 400

    if file:
        # Save uploaded files
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)

        appsketch_api = request.form.get('url', 'default_value')
        pcap_file_id = request.form.get('id', 'default_value')

        # Use PcapNGFormatAnalys.py
        modified_filepath = modify_file_with_script(filepath, appsketch_api, pcap_file_id)

        # Delete uploaded and modified files after response

        @after_this_request
        def remove_file(response):
            try:
                os.remove(filepath)  # 删除上传的文件
                os.remove(modified_filepath)  # 删除修改后的文件
            except Exception as e:
                app.logger.error(f'Error deleting file: {e}')
            return response

        # Provide modified file download
        return send_file(modified_filepath, as_attachment=True)

def modify_file_with_script(input_filepath, appsketch_api, pcap_file_id):
    modified_filepath = os.path.join(app.config['MODIFIED_FOLDER'], os.path.basename(input_filepath))
    # Use PcapNGFormatAnalys.py to add Remark
    script_path = 'PcapNGFormatAnalys.py'
    subprocess.run(['python3', script_path, input_filepath, modified_filepath, appsketch_api, pcap_file_id])
    return modified_filepath

if __name__ == '__main__':
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    app.run(host=local_ip, port=5000, debug=True)