from impacket.dcerpc.v5.dcomrt import DCOMConnection
from impacket.dcerpc.v5.dcom import wmi
from impacket.dcerpc.v5.dtypes import NULL
import time
import random
import string
class WMIShell:
def __init__(self, target, username, password, domain=''):
self.dcom = DCOMConnection(target, username, password, domain)
iInterface = self.dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)
iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)
self.iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)
self.processClass, _ = self.iWbemServices.GetObject('Win32_Process')
def execute(self, command):
"""Execute command and return output"""
# Generate random filename
output_file = ''.join(random.choice(string.ascii_letters) for _ in range(8)) + '.txt'
output_path = f'C:\\\\Windows\\\\Temp\\\\{output_file}'
# Execute command with output redirection
cmd = f'cmd.exe /c {command} > {output_path} 2>&1'
self.processClass.Create(cmd, NULL, NULL)
# Wait for execution
time.sleep(2)
# Read output using TYPE command
read_cmd = f'cmd.exe /c type {output_path}'
# Note: Would need SMB connection to actually retrieve the file
# This is a simplified example
# Clean up
del_cmd = f'cmd.exe /c del {output_path}'
self.processClass.Create(del_cmd, NULL, NULL)
def __del__(self):
self.dcom.disconnect()
# Usage
shell = WMIShell('192.168.1.100', 'admin', 'pass')
shell.execute('whoami')
shell.execute('ipconfig')