Created
August 27, 2017 12:09
-
-
Save ismailakkila/b534fa4e8887b49ae3e233a5987c78af to your computer and use it in GitHub Desktop.
ch2_netcat_example.py
This file contains 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
#netcat example | |
import sys | |
import socket | |
import getopt | |
global target | |
global port | |
target = "" | |
port = 0 | |
def usage(): | |
print(" ") | |
print("********************** Python Netcat **********************") | |
print("Usage: python3 ch2_netcat_example.py -t 192.168.0.1 -p 9999") | |
print("-t --target= target destination") | |
print("-p --port= target port") | |
print("-h --help this help menu") | |
print(" ") | |
sys.exit(0) | |
if not len(sys.argv[1:]): | |
usage() | |
try: | |
opts, args = getopt.getopt(sys.argv[1:], "t:p:h", ["target=", "port=", "help"]) | |
except getopt.GetoptError as err: | |
print(str(err)) | |
sys.exit(1) | |
#check options and arguments | |
for o, a in opts: | |
if o in ("-h", "--help"): | |
usage() | |
elif o in ("-t", "--target") and len(a): | |
target = a | |
elif o in ("-p", "--port") and int(a) in range(1, 65536): | |
port = int(a) | |
else: | |
print("Invalid Arguments") | |
usage() | |
#read buffer from stdin | |
print("Enter buffer data (CTRL-D to send/ CTRL-C to quit)") | |
buffer = sys.stdin.read() | |
#create the tcp client socket, connect and send buffer data | |
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
client_socket.connect((target, port)) | |
#CTRL-C to stop python netcat | |
while True: | |
#send buffer data | |
client_socket.send(buffer.encode()) | |
#get 4096 bytes from destination | |
response = client_socket.recv(4096) | |
bytes = len(response) | |
total_bytes = bytes | |
#get all remaining bytes from destination | |
while bytes == 4096: | |
data = client_socket.recv(4096) | |
response += data | |
bytes = len(data) | |
total_bytes += bytes | |
#Show the full response | |
print(f"Response ({total_bytes} Bytes):") | |
print(response) | |
#read buffer from stdin | |
print("Enter buffer data (CTRL-D to send/ CTRL-C to quit)") | |
buffer = sys.stdin.read() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment