Python Shellexecute windows api with Ctypes over TCP/IP
<p>I have question about running windows API's over TCP/IP protocol.
For example, I want to bring remote machine's cmd.exe to other machine (Like Netcat, fully simulating cmd.exe over TCP/IP) . I searched online for doing it with python but couldn't find anything helpful. I can do this using subprocess and other python capabilities but it lacks user-interface problem. I used this kind of code:</p>

<pre><code>import socket
import subprocess
import ctypes

HOST = '192.168.1.22'
PORT = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while 1:
    #send initial cmd.exe banner to remote machine 
    s.send(ctypes.windll.Shell32.ShellExecuteA(None,"open","cmd.exe",None,None,0))
    #accept user input
    data = s.recv(1024)
    #pass it again to Shellexecute api to execute and return output to remote machine, fully simulating original CMD over TCP/IP


s.close()
</code></pre>

<p>Look at to this picture:
<a href="http://i.stack.imgur.com/qI48a.jpg" rel="nofollow">Running CMD over TCP/IP using NetCat tool</a></p>

<p>I'm not sure what your need is based on your description is, but I'll try to help you :).   </p>

<p>If all you want is to activate the CMD.exe on a remote machine with a port being open, you would maybe like to look into a "server script" that will execute any command passed to it.
i.e.</p>

<pre><code>class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        error_code = os.system(self.data.decode('UTF-8'))
        # just send back the error code so we know if it executed correctly
        self.request.sendall(error_code)

if __file__ is '__main__':
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
</code></pre>

<p>*ref :<a href="https://docs.python.org/3.4/library/socketserver.html" rel="nofollow">https://docs.python.org/3.4/library/socketserver.html</a>
I don't need to mention that this is really not secure...</p>

<p>if you really want to pass it to python on the server side, I think I would put everything received on the socket in a tmp file and execute python over it.  Like Ansible do.</p>

<p>Let me know if that helped you!</p>

python windows network-programming tcp-ip netcat