Skip to content

Instantly share code, notes, and snippets.

@pwighton
Last active July 22, 2021 17:25
Show Gist options
  • Save pwighton/21241eae20e7f036a7314c336acb5d85 to your computer and use it in GitHub Desktop.
Save pwighton/21241eae20e7f036a7314c336acb5d85 to your computer and use it in GitHub Desktop.
Reads from a socket and writes to file
#!/usr/bin/env python3
import argparse
import socket
import traceback
parser = argparse.ArgumentParser(description="Parse command line options")
parser.add_argument("port")
parser.add_argument("outfile")
args = parser.parse_args()
host = "0.0.0.0"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, int(args.port)))
s.listen(1)
print("Listening on: ", (host, int(args.port)) )
conn, addr = s.accept()
conn.settimeout(5.0)
print("Connected to ", addr)
bytes_read_from_socket = b''
num_bytes_read = 0
while True:
data = conn.recv(2048)
if not data or len(data)==0: break
num_bytes_read += len(data)
bytes_read_from_socket += data
print("Read a total of "+str(num_bytes_read)+" bytes")
print("Writing bytestring to file:", args.outfile)
f = open(args.outfile, 'wb')
f.write(bytes_read_from_socket)
f.close()
except Exception as e:
print("!!!!! Caught an exception:", e)
traceback.print_exc()
if 'f' not in locals():
print("Trying to write a binary file anyway..")
f = open(args.outfile, 'wb')
f.write(bytes_read_from_socket)
f.close()
finally:
if 'conn' in locals():
print("Closing Connection")
conn.close()
if 's' in locals():
print("Closing Socket")
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment