Last active
March 26, 2019 20:46
-
-
Save righthandabacus/1c66bb740d63327f1ccda788f2cb34d6 to your computer and use it in GitHub Desktop.
netcat in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import socketserver | |
import threading | |
def sender(hostname, port, content): | |
"""Connect to a TCP port and send content, then wait for reply | |
""" | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: | |
sock.connect((hostname, port)) | |
sock.sendall(content) | |
print("Sent {}".format(content)) | |
sock.shutdown(socket.SHUT_WR) | |
while 1: | |
data = sock.recv(1024) | |
if data == "": | |
break | |
print("Received:", repr(data)) | |
print("Connection closed.") | |
class ServerHandler(socketserver.StreamRequestHandler): | |
"""Syntax sugar to avoid socket.bind, socket.listen, and socket.accept calls | |
""" | |
def handle(self): | |
"""Deal with the TCP socket at self.request once a client has connected. Echo back what is received in uppercase""" | |
data = self.rfile.readline().strip() | |
print("{}: {}".format(self.client_address[0], repr(data))) | |
self.wfile.write(data.upper()) | |
def main(host, port): | |
try: | |
with socketserver.TCPServer((host, port), ServerHandler) as server: | |
server.serve_forever() | |
except KeyboardInterrupt: | |
print("Server shutdown") | |
if __name__ == "__main__": | |
import sys | |
import random | |
if sys.argv[1:2] == ["server"]: | |
main("", 9999) | |
elif sys.argv[1:2] == ["client"]: | |
N = 30 | |
data = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + " " + string.digits, k=N)) | |
sender("localhost", 9999, data.encode("utf-8")) | |
else: | |
print("need command line argument 'server' or 'client'") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment