Página 1 de 1

[RESUELTO] Problema con run_powershell_from_file

Publicado: 2 de julio de 2021 - 10:59 a. m.
Por Cédric Morin
Buen día,

Tengo un pequeño problema con los asistentes de configuración ejecutar_powershell_desde_archivoEscribí mi script en PowerShell y no parece tener ningún problema al ejecutarse.

Código: Seleccionar todo

#Script pour determiner si Nuget est installé et dans quelle version

Try{
    $Version = (Get-PackageProvider -Name "Nuget" -ErrorAction SilentlyContinue).Version
    $Result = "NuGet found. Version : $($Version.ToString())"
}
Catch{
    $Result = "NuGet not found."
}

$Result
Cuando alimento mi función de auditoría con esto:

Código: Seleccionar todo

run_powershell_from_file("Get-INSANugetVersion.ps1",output_format='json')
Recibo un gran mensaje de error:

Código: Seleccionar todo

Auditing c:\waptdev\insat-nuget_x64_PROD-wapt\WAPT\.. ...
2021-07-02 10:41:13,071 CRITICAL Fatal error in audit function: CalledProcessErrorOutput: Command '$ProgressPreference = "SilentlyContinue"\n(#Script pour determiner si Nuget est installé et dans quelle version\n\nTry{\n    $Version = (Get-PackageProvider -Name "Nuget" -ErrorAction SilentlyContinue).Version\n    $Result = "NuGet found. Version : $($Version.ToString())"\n}\nCatch{\n    $Result = "NuGet not found."\n}\n\n\n$Result) | ConvertTo-Json' returned non-zero exit status 1.
Output:#< CLIXML
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><S S="Error">Au caractère Ligne:7 : 2_x000D__x000A_</S><S S="Error">+ }_x000D__x000A_</S><S S="Error">+  ~_x000D__x000A_</S><S S="Error">Parenthèse fermante « ) » manquante dans l'expression._x000D__x000A_</S><S S="Error">Au caractère Ligne:8 : 1_x000D__x000A_</S><S S="Error">+ Catch{_x000D__x000A_</S><S S="Error">+ ~~~~~_x000D__x000A_</S><S S="Error">Jeton inattendu « Catch » dans l'expression ou l'instruction._x000D__x000A_</S><S S="Error">Au caractère Ligne:13 : 8_x000D__x000A_</S><S S="Error">+ $Result) | ConvertTo-Json_x000D__x000A_</S><S S="Error">+        ~_x000D__x000A_</S><S S="Error">Jeton inattendu « ) » dans l'expression ou l'instruction._x000D__x000A_</S><S S="Error">Au caractère Ligne:13 : 10_x000D__x000A_</S><S S="Error">+ $Result) | ConvertTo-Json_x000D__x000A_</S><S S="Error">+          ~_x000D__x000A_</S><S S="Error">Un élément de canal vide n'est pas autorisé._x000D__x000A_</S><S S="Error">    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException_x000D__x000A_</S><S S="Error">    + FullyQualifiedErrorId : MissingEndParenthesisInExpression_x000D__x000A_</S><S S="Error"> _x000D__x000A_</S></Objs>:

Tenga en cuenta que si pongo esto en la auditoría, funciona como se esperaba:

Código: Seleccionar todo

    result = run('C:\\Windows\\System32\WindowsPowerShell\\v1.0\\powershell.exe -NoProfile -File .\\Get-INSANugetVersion.ps1')
    print(result)

Código: Seleccionar todo

Ligne de Commande : audit -f "c:\waptdev\insat-nuget_x64_PROD-wapt\WAPT\.."
Using config file: C:\Program Files (x86)\wapt\wapt-get.ini
Auditing c:\waptdev\insat-nuget_x64_PROD-wapt\WAPT\.. ...
NuGet found. Version : 2.8.5.208

c:\waptdev\insat-nuget_x64_PROD-wapt\WAPT\.. -> UNKNOWN
Entonces no entiendo por qué ejecutar_powershell_desde_archivo genera un error, ya que desde la consola de PowerShell y con correr ¿No tengo problemas?

¡Gracias por su ayuda!

--------------------------------------------------------------------------------------------------------------------------
- Versión WAPT instalada: 2.0
- Sistema operativo del servidor: Linux Ubuntu 20.04
- Sistema operativo del equipo de administración/creación de paquetes: Windows 10 (20H2)

Re: Problema con run_powershell_from_file

Publicado: 7 de julio de 2021 - 10:33 a. m.
por dcardon
Hola Cédric,
estamos usando un blob como parámetro porque Windows suele bloquear la carga de scripts de PowerShell en archivos .ps1. Sin embargo, me sorprende que el script no se haya convertido a base64... Abriré un ticket internamente.
Saludos,
Denis

Re: Problema con run_powershell_from_file

Publicado: 7 de julio de 2021 - 17:02
por dcardon
El script se convirtió correctamente a base64 en el código. PowerShell puede ser bastante inestable. He corregido un par de errores. Puedes intentar reemplazar la función `run_powershell()` en tu equipo de prueba con esta para verificar su funcionamiento. La probé yo mismo y funcionó correctamente con tu script. Esto se incluirá en la próxima versión, la 2.1.

Atentamente,

Denis

Código: Seleccionar todo

def run_powershell(cmd, output_format='json', **kwargs):
    """Run a command/script (possibly multiline) using powershell, return output in text format
    If format is 'json', the result is piped to ConvertTo-Json and converted back to a python dict for convenient use

    WARNING: This works only with powershell >= 3

    Args:
        output_format (str): set output format as json (default) or xml (ElementTree object) or text

    Returns:
        str or dict or list

    .. versionadded:: 1.3.9
    """
    if output_format not in ('json','text','xml'):
        raise ValueError("Input parameter output_format not correct (json/text/xml expected: %s" % output_format)


    output_version = run('powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "$PSVersionTable.PSVersion.Major"').strip()

    try:
        if int(output_version)<3 :
            raise Exception('run_powershell need powershell version >=3, please install tis-powershell package first')
    except:
        pass

    cmd = ensure_unicode(cmd)

    if output_format == 'json':
        output_format_ps = 'text'
        cmd = '$ProgressPreference = "SilentlyContinue"\n%s  | ConvertTo-Json ' % cmd
    else:
        output_format_ps = output_format
    # command is a utf16 without bom encoded with base64 without \n
    # we should not get stderr so that ouput can be decoded as json. stderr get progress report...
    if not 'return_stderr' in kwargs or not isinstance(kwargs['return_stderr'], list):
        return_stderr = []
    else:
        kwargs.pop('return_stderr')
    try:
        with disable_file_system_redirection():
            cmd = 'powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -OutputFormat %s -EncodedCommand "%s" ' %  (output_format_ps,  base64.b64encode(cmd.encode('utf-16le')).decode('utf-8'))
            logger.debug("running powershell command : \n%s" % cmd)
            result = run(cmd,
                         return_stderr=return_stderr,
                         **kwargs)
    except CalledProcessErrorOutput as e:
        raise CalledProcessErrorOutput(e.returncode, cmd, e.output)

    # remove comments...
    if output_format.lower() == 'xml':
        lines = [l for l in result.splitlines() if not l.strip().startswith('#') and l.strip()]
        import xml.etree.ElementTree as ET
        return ET.fromstringlist(lines)
    elif output_format.lower() == 'json':
        lines = [l for l in ensure_unicode(result).splitlines() if not l.strip().startswith('#')]
        if not lines:
            return None
        else:
            try:
                json_output = json.loads('\n'.join(lines))
                return json.dumps(json_output)
            except ValueError as e:
                raise ValueError('%s returned non json data:\n%s' % (cmd, result))
    else:
        return result

Re: [RESUELTO] Problema con run_powershell_from_file

Publicado: 8 de julio de 2021 - 11:50 a. m.
Por Cédric Morin
Hola,

lo probaré lo antes posible. Espero que antes de que termine el mes, ¡estamos bastante ocupados ahora mismo!

Cedric.

Re: [RESUELTO] Problema con run_powershell_from_file

Publicado: 20 de julio de 2021 - 10:19 a. m.
Por Cédric Morin
Hola,

acabo de hacer algunas pruebas y parece que funciona correctamente con la corrección.

¡Gracias!