File Receiver Python Script
/ 2 min read
Table of Contents
Overview
In restricted network topologies, moving files between machines is occasionally constrained by one-way firewall rules, NAT gateways, or missing reverse routes. When a target server cannot establish outbound connections back to the local development machine—or when SSH SFTP/SCP access is unavailable—spawning a temporary HTTP POST listener on an open inbound port provides a pragmatic mechanism for transferring binaries or logs using nothing more than curl.
What follows is my notes on running a lightweight standard-library Python file receiver for ad-hoc, isolated transfers.
The Receiver Script
The script subclasses http.server.BaseHTTPRequestHandler to stream chunks from incoming POST bodies directly to disk using standard libraries without external dependencies:
import http.serverimport socketserverimport os
PORT = 8080CHUNK_SIZE = 1024 * 1024 # 1MB buffer
class FileUploadHandler(http.server.BaseHTTPRequestHandler): def do_POST(self): try: content_length = int(self.headers.get('Content-Length', 0)) # Sanitize filename from URL path file_name = os.path.basename(self.path.lstrip('/')) or "uploaded_file"
with open(file_name, 'wb') as file: remaining = content_length while remaining > 0: chunk = self.rfile.read(min(CHUNK_SIZE, remaining)) if not chunk: break file.write(chunk) remaining -= len(chunk)
self.send_response(200) self.end_headers() self.wfile.write(b'File uploaded successfully\n') except Exception as e: self.send_response(500) self.end_headers() self.wfile.write(f'Upload failed: {str(e)}\n'.encode())
with socketserver.TCPServer(("", PORT), FileUploadHandler) as httpd: print(f"Listening for file uploads on port {PORT}...") httpd.serve_forever()Starting the receiver on an unprivileged port (e.g. 8080) avoids requiring root privileges:
python3 file-receiver.pyTransferring Files via curl
From the client machine, files are streamed to the endpoint via a standard HTTP POST request using curl:
curl -X POST --upload-file archive.tar.gz http://192.168.1.50:8080/archive.tar.gzUpon completion, curl outputs the response:
File uploaded successfullyVerifying Integrity on the Receiver
The Python listener logs incoming POST transactions:
192.168.1.10 - - [24/Feb/2024 10:22:38] "POST /archive.tar.gz HTTP/1.1" 200 -After terminating the server with Ctrl+C, I verify file sizes and checksums against the client origin:
sha256sum archive.tar.gz