0

I have an .exe file running in a virtual machine called "adBot" and receiving commands to create users in an active directory (another "adClient" script), this part of the code works quite well, however how can I get it to receive commands from powershell. I am using the rpyc and subprocess libraries for the connection

#adBot
import argparse
import rpyc
from rpyc.utils.server import ThreadedServer
import datetime
import subprocess
date_time = datetime.datetime.now()

class MonitorService(rpyc.Service):
    def on_connect(self, conn):
        print("Conectado {}".format(date_time))
    def on_disconnect(self, conn):
        print("Desconectado {}\n".format(date_time))
    def exposed_run_command(self,command):
        try:
            output = subprocess.check_output(command,shell=True) 
            print(output)
        except subprocess.CalledProcessError as Error:
            print(Error.returncode)
            print(Error.output)
def main():
    parser = argparse.ArgumentParser(description="Active Directory Bot")
    parser.add_argument("-port",type=int,help="Enter Custom Port Number")
    args = parser.parse_args()
    port = args.port
    print("Puerto Recuperado: " + str(port))
    if not port:
        port = 18821 
    print("Puerto Usado: "+ str(port))
 
    t = ThreadedServer(MonitorService,port=port)
    t.start()
#AdClient
import rpyc
DISABLE_user = 'disable'
ENABLE_user = 'enable'
DELETE_user = 'delete'
ADD_group = 'add'
REMOVE_group = 'remove'
AD_IP = "172.19.128.3"  # IP Directorio Activo
LOCAL = "localhost"
MV_SERVER = "192.168.74.128"  # IP  maquina Virtual
AD_BOT_PORT = 18821
domain_controller = "dc=TEST,dc=LOCAL"
users_ou = f"ou=ALL,ou=Employee,{domain_controller}"
groups_ou = f"ou=Employee_Groups,{domain_controller}"

def enviarComando(comando):
 
    try:
        con = rpyc.connect(MV_SERVER, AD_BOT_PORT)
        con.root.run_command(comando)
        print("ok")
    except Exception as ERR:
        print(f"Error en enviar comando {ERR}")
    except TimeoutError as TIMEOUT:
        print(f"Error en tiempo de espera: {TIMEOUT}")

def crearUsuario(nombres, apellidos,desc, oficina, numTelf, numCasa, mobileNum, titulo, departamento, compania, dirCasa, active=False):

    if active:
        deshabilitar = "no"
    else:
        deshabilitar = "yes"
    descripcion = desc+f" USUARIO CREADO EN EL DIRECTORIO ACTIVO {datetime.datetime.now()}"
    displayName = nombres + " " + apellidos
    defaultPassword = "P@tito.123"
    username = cda.defineUsername(nombres, apellidos)
    upn = cda.defineUPN(username)
    email = cda.defineCorreo(nombres,apellidos)
    dn = f'"cn={username},{users_ou}"'
    country = "EC"
    grupo = f'"cn=All,{groups_ou}"'# All grupo ya creado
    comando = 'dsadd user ' \
              f'{dn} ' \
              f'-samid "{username}" ' \
              f'-upn "{upn}" ' \
              f'-fn "{nombres}" ' \
              f'-ln "{apellidos}" ' \
              f'-display "{displayName}" ' \
              f'-empid "{"NULL"}" ' \
              f'-pwd {defaultPassword} ' \
              f'-desc "{descripcion}" ' \
              f'-office "{oficina}" ' \
              f'-tel "{numTelf}" ' \
              f'-email "{email}" ' \
              f'-hometel "{numCasa}" ' \
              f'-pager "{"NULL"}" ' \
              f'-mobile "{mobileNum}" ' \
              f'-fax "{"NULL"}" ' \
              f'-iptel "{"NULL"}" ' \
              f'-webpg "{"NULL"}" ' \
              f'-title "{titulo}" ' \
              f'-dept "{departamento}" ' \
              f'-company "{compania}" ' \
              f'-disabled {deshabilitar} ' \
              '-pwdneverexpires yes ' \
              '-mustchpwd yes ' \
              f'-memberof {grupo} ' \
              '-acctexpires never ' \
              ''
    #comando = "New-ADUser -name 'sales user' -GivenName Sales -Surname USER -SamAccountName SalesUser -UserPrincipalName saleuser@corp.lan"
    print(comando)
    enviarComando(comando)

I hope to be able to send powershell commands from the script

Cuervo 616
  • 21
  • 3
  • Do the answers here have what you're looking for? https://stackoverflow.com/questions/21944895/running-powershell-script-within-python-script-how-to-make-python-print-the-pow – Cpt.Whale Mar 20 '23 at 20:35
  • @Cpt.Whale I need to send a command from the script 'adclient' to 'AdBot' which is running on the server. This is for remote control of PowerShell – Cuervo 616 Mar 21 '23 at 19:25
  • Also in the .excel of the server that is running it gives me the error -> "New-ADUser" is not recognized as an internal or external command, program or executable batch file – Cuervo 616 Mar 21 '23 at 19:36
  • `.run_command()` starts CMD shell, not powershell. Please look through the linked question for examples. You probably want something like `.run_command("powershell.exe -c 'New-ADUser ...' ")` or switch to using `subprocess.Popen(["powershell.exe","list","of","args"])` – Cpt.Whale Mar 21 '23 at 21:26
  • Thank you @Cpt.Whale, what I used was "powershell -c" and then I entered the command. Thank you very much, you were very kind. – Cuervo 616 Mar 22 '23 at 14:22

0 Answers0