Advertisement
dubtrotters

netcat.py [ALPHA]

Jan 20th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.14 KB | None | 0 0
  1. #
  2. # Netcat
  3. # Brett Stroud
  4. # 01/20/2019
  5. # v1.0
  6. # netcat.py
  7. #
  8.  
  9. import sys
  10. import socket
  11. import getopt
  12. import threading
  13. import subprocess
  14.  
  15. # Define global variables
  16. listen          = False
  17. command         = False
  18. upload          = False
  19. execute         = ""
  20. target          = ""
  21. upload_destination  = ""
  22. port            = 0
  23.  
  24. def usage():
  25.     print "BHP Net Tool"
  26.     print
  27.     print "Usage: bhpnet.py -t target_host -p port"
  28.     print """-l --listen            - listen on [host]:[port] for
  29.                         incoming connections"""
  30.     print """-e --execute=file_to_run   - execute the given file upon
  31.                         receiving a connection"""
  32.     print """-c --command           - initialize a command shell"""
  33.     print """-u --upload=destination    - upon receiving connection upload a
  34.                         file and write to [destination]"""
  35.     print
  36.     print
  37.     print "Examples: "
  38.     print "bhpnet.py -t 192.169.0.1 -p 5555 -1 -c"
  39.     print "bhpnet.py -t 192.168.0.1 -p 5555 -1 -u=c:\\target.exe"
  40.     print "bhpnet.py -t 192.168.0.1 -p 5555 -1 -e=\"cat /etc/passwd\""
  41.     print "echo 'ABCDEFGHI' | ./bhpnet.py -t 192.168.11.12 -p 135"
  42.     sys.exit(0)
  43.  
  44. def client_sender(buffer):
  45.  
  46.     client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  47.  
  48.     try:
  49.         # Attempt to establish connection with targeted host
  50.         client.connect((target, port))
  51.  
  52.         if len(buffer):
  53.             client.send(buffer)
  54.  
  55.         while True:
  56.  
  57.             # Await response
  58.             recv_len = 1
  59.             response = ""
  60.  
  61.             while recv_len:
  62.                 data     = client.recv(4096)
  63.                 recv_len = len(data)
  64.                 response+= data
  65.  
  66.                 if recv_len < 4096:
  67.                     break
  68.  
  69.         print response,
  70.  
  71.         # Await further input
  72.         buffer = raw input("")
  73.         buffer += "\n"
  74.  
  75.         # Send data
  76.         client.send(buffer)
  77.  
  78.     except:
  79.  
  80.         print "[*] Exception detected! Exiting IMMEDIATELY."
  81.  
  82.         # Terminate the connection
  83.         client.close()
  84.  
  85. def server_loop():
  86.     global target
  87.     # If a target is not specified LISTEN ON ALL INTERFACES
  88.     if not len(target):
  89.         target = "0.0.0.0"
  90.  
  91.     server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  92.     server.bind((target, port))
  93.     server.listen(5)
  94.  
  95.     while True:
  96.         client_socket, addr = server.accept()
  97.  
  98.         # Create a new thread to process the incoming client
  99.         client_thread = threading.Thread(target=client_handler,args=(client_socket,))
  100.         client_thread.start()
  101.  
  102. def run_command(command):
  103.  
  104.     # Trim newline [newline = \n]
  105.     command = command.rstrip()
  106.  
  107.     # Get output from STDOUT resulting from executing command
  108.     try:
  109.         ouput = subprocess.check_output(command,stderr=subprocess.STDOUT, shell=True)
  110.     except:
  111.         output = "[*]Command Failed to Execute!\r\n"
  112.  
  113.     # Return resulting output to the client
  114.     return output
  115.  
  116. def client_handler(client_socket):
  117.     global upload
  118.     global execute
  119.     global command
  120.  
  121.     # Run upload check
  122.     if len(upload_destination):
  123.  
  124.         # Read in all bytes to memory and write to destination
  125.         file_buffer = ""
  126.  
  127.         # Read data until nothing else is available
  128.         while True:
  129.             data = client_socket.recv(1024)
  130.  
  131.         if not data:
  132.             break
  133.         else:
  134.             file_buffer += data
  135.  
  136.         # Attempt to write out the following bytes of data
  137.         try:
  138.             file_descriptor = open(upload_destination,"wb")
  139.             file_descriptor.write(file_buffer)
  140.             file_descriptor.close()
  141.  
  142.             # Confirm file was written out successfully
  143.             client_socket.send("FILE WRITTEN TO: %s\r\n" % upload_destination)
  144.         except:
  145.             client_socket.send("FILE NOT WRITTEN TO: %s\r\n" % upload_destination)
  146.  
  147.  
  148.     # Check for command execution
  149.     if len(execute):
  150.  
  151.         # Run command
  152.         output = run_command(execute)
  153.  
  154.         client_socket.send(output)
  155.  
  156.  
  157.     # Enter secondary loop if command shell requested
  158.     if command:
  159.  
  160.         while True:
  161.             # Draw a simple prompt
  162.             client_socket.send("<BHP:#> ")
  163.  
  164.                 # Continue receiving until linefeed
  165.                 # is displayed (enter key)
  166.             cmd_buffer = ""
  167.             while "\n" not in cmd_buffer:
  168.                 cmd_buffer += client_socket.recv(1024)
  169.  
  170.  
  171.             # Return the command output
  172.             response = run_command(cmd_buffer)
  173.  
  174.             # Return the response
  175.             client_socket.send(response)
  176.  
  177. def main():
  178.     global listen
  179.     global port
  180.     global execute
  181.     global command
  182.     global upload_destination
  183.     global target
  184.  
  185.     if not len(sys,argv[1:]):
  186.         usage()
  187.  
  188.     # Read the commandline options
  189.     try:
  190.         opts,args = getopt.getopt(sys,argv[1:],"hle:t:p:cu:",["help","listen","execute","target","port","command","upload"])
  191.     except getopt.GetoptError as err:
  192.         print str(err)
  193.         usage()
  194.  
  195.     for o,a in opts:
  196.         if o in ("-h", "--help"):
  197.             usage()
  198.         elif o in ("-l", "--listen"):
  199.             listen = True
  200.         elif o in ("-e", "--execute"):
  201.             execute = a
  202.         elif o in ("-c", "--commandshell"):
  203.             command = True
  204.         elif o in ("-u", "--upload"):
  205.             upload_destination = a
  206.         elif o in ("-t", "--target"):
  207.             target = a
  208.         elif o in ("-p", "--port"):
  209.             port = int(a)
  210.         else:
  211.             assert False, "Unhandled Option"
  212.  
  213.     # Are we going to listen or just send data from stdin?
  214.     if not listen and len(target) and port > 0:
  215.  
  216.         # Read in the buffer from the commandline
  217.         # this will block, so send CTRL-D if not
  218.         # sending input to stdin
  219.         buffer = sys.stdin.read()
  220.  
  221.         # Send data off
  222.         client_sender(buffer)
  223.  
  224.     # We are going to listen and potentially
  225.     # upload things, execute commands, and drop a shell back
  226.     # depending on our command line options above
  227.     if listen:
  228.         server_loop()
  229.  
  230. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement