Skip to content

Instantly share code, notes, and snippets.

@ismailakkila
Created August 27, 2017 12:10
Show Gist options
  • Save ismailakkila/461bd094a8ac78171798962ef991034b to your computer and use it in GitHub Desktop.
Save ismailakkila/461bd094a8ac78171798962ef991034b to your computer and use it in GitHub Desktop.
ch2_tcpservertools_example.py
#tcp server tools
import socket
import getopt
import threading
import subprocess
import sys
global target
global port
global file_destination
global execute
global command
target = ""
port = 0
file_destination = ""
execute = ""
command = False
def usage():
print(" ")
print("***************** Python TCP Server Tools *****************")
print("Usage: python3 ch2_tcpservertools_example.py --command ")
print("-t --target= target destination")
print("-p --port= target port")
print("-w --write= target file destination on server")
print("-e --execute= execute command on server")
print("-c --command command shell mode")
print("-h --help this help menu")
print(" ")
sys.exit(0)
def client_handler(client_socket):
#run command function
def run_command(command):
#strip any newlines or trailing spaces
command = command.rstrip()
#use subprocess to execute the command and get output
try:
output_command = subprocess.run(
command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
if len(output_command.stderr.decode('utf-8')):
output = output_command.stderr.decode('utf-8')
else:
output = output_command.stdout.decode('utf-8')
except subprocess.CalledProcessError as err:
print(f"[*] Error executing command: {command}")
print(str(err))
print(f"[*] Success executing command: {command}")
return output
#write to file path
if len(file_destination):
print("[*] Running write-to-file mode")
#receive the 1st chunk of 1024 bytes
data = client_socket.recv(1024)
file_buffer = data
#receive the additional chunks until no data
while data:
data = client_socket.recv(1024)
file_buffer += data
#write the file buffer to the provided file path and close the client socket
try:
file_descriptor = open(file_destination, "wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
print(f"[*] Success writing to file path: {file_destination}")
client_socket.send("Success writing to file path: {}".format(file_destination).encode())
except:
print(f"[*] Error writing to file path: {file_destination}")
client_socket.send("Error writing to file path: {}".format(file_destination).encode())
#execute a command on the server
if len(execute):
print(f"[*] Running execute mode: {execute}")
response = run_command(execute)
client_socket.send(response.encode())
#open a shell on the server
if command:
print("[*] Running command shell mode")
while True:
client_socket.send(b"<TCPToolsShell:#>")
command_buffer = b""
#When a command is executed with return
while "\r\n" not in command_buffer.decode('utf-8'):
data = client_socket.recv(1024)
command_buffer += data
response = run_command(command_buffer.decode('utf-8'))
client_socket.send(response.encode())
if not len(sys.argv[1:]):
usage()
try:
opts, args = getopt.getopt(sys.argv[1:], "t:p:w:e:ch", [
"target=",
"port=",
"write=",
"execute=",
"command",
"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"):
target = a
elif o in ("-p", "--port") and int(a) in range(1, 65536):
port = int(a)
elif o in ("-w", "--write") and len(a):
file_destination = a
elif o in ("-e", "--execute") and len(a):
execute = a
elif o in ("-c", "--command"):
command = True
else:
print("Invalid Arguments")
usage()
#create the server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#if target is not provided, listen on all interfaces
if not len(target):
target = "0.0.0.0"
#bind and listen for incoming tcp connections
server_socket.bind((target, port))
server_socket.listen(5)
print(f"[*] TCP server listening on {target}:{server_socket.getsockname()[1]}")
while True:
#Accept TCP Connections
client_socket, addr = server_socket.accept()
print(f"[*] Received a tcp connection from {addr[0]}:{addr[1]}")
#Spawn a client handler thread
client_thread = threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment