Python Shellexecute通过TCP / IP使用Ctypes的windows api

时间:2016-09-03 12:32:52

标签: python windows network-programming tcp-ip netcat

我对通过TCP / IP协议运行Windows API有疑问。 例如,我想将远程计算机的cmd.exe带到其他计算机(如Netcat,通过TCP / IP完全模拟cmd.exe)。我在网上搜索用python做的但是找不到任何有用的东西。我可以使用子进程和其他python功能来做到这一点,但它缺乏用户界面问题。我用过这种代码:

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()

看看这张照片: Running CMD over TCP/IP using NetCat tool

1 个答案:

答案 0 :(得分:0)

根据您的说明,我不确定您的需求是什么,但我会尽力帮助您:)。

如果您想要的是在端口打开的远程计算机上激活CMD.exe,您可能希望查看一个"服务器脚本"将执行传递给它的任何命令。 即。

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()

* ref:https://docs.python.org/3.4/library/socketserver.html 我不需要提到这真的不安全......

如果你真的想把它传递给服务器端的python,我想我会把接收到的所有东西都放在tmp文件中并在它上面执行python。像Ansible一样。

如果有帮助,请告诉我!