Pagina 1 di 1

[RISOLTO] Problema con run_powershell_from_file

Pubblicato: 2 luglio 2021 - 10:59
di Cédric Morin
Buongiorno,

Ho un piccolo problema con gli helper di configurazione esegui_powershell_da_fileHo scritto il mio script in PowerShell e non sembra avere problemi di esecuzione.

Codice: Seleziona tutto

#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
Quando inserisco questo dato nella mia funzione di audit:

Codice: Seleziona tutto

run_powershell_from_file("Get-INSANugetVersion.ps1",output_format='json')
Ricevo un messaggio di errore importante:

Codice: Seleziona tutto

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>:

Tieni presente che se inserisco questo nell'audit, funziona come previsto:

Codice: Seleziona tutto

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

Codice: Seleziona tutto

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
Quindi non capisco perché esegui_powershell_da_file genera un errore, poiché dalla console di PowerShell e con correre Non ho problemi?

Grazie per l'aiuto!

--------------------------------------------------------------------------------------------------------------------------
- Versione WAPT installata: 2.0
- Sistema operativo del server: Linux Ubuntu 20.04
- Sistema operativo della macchina di amministrazione/creazione pacchetti: Windows 10 (20H2)

Oggetto: Problema con run_powershell_from_file

Pubblicato: 7 luglio 2021 - 10:33
di dcardon
Ciao Cédric,
stiamo usando un blob come parametro perché Windows spesso blocca il caricamento degli script PowerShell nei file .ps1. Tuttavia, mi sorprende che lo script non sia stato convertito in base64... Aprirò un ticket interno.
Cordiali saluti,
Denis

Oggetto: Problema con run_powershell_from_file

Pubblicato: 7 luglio 2021 - 17:02
di dcardon
Lo script è stato convertito correttamente in base64 nel codice. PowerShell può essere piuttosto imprevedibile. Ho apportato un paio di correzioni. Puoi provare a sostituire la funzione `run_powershell()` sul tuo computer di prova con questa per verificarne il funzionamento. L'ho testata personalmente e ha funzionato correttamente con il tuo script. Questa funzione sarà inclusa nella prossima versione, la 2.1.

Sinceramente,

Denis

Codice: Seleziona tutto

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

Oggetto: [RISOLTO] Problema con run_powershell_from_file

Pubblicato: 8 luglio 2021 - 11:50
di Cédric Morin
Ciao,

lo testerò al più presto. Spero entro la fine del mese, al momento siamo piuttosto impegnati!

Cedric.

Oggetto: [RISOLTO] Problema con run_powershell_from_file

Pubblicato: 20 luglio 2021 - 10:19
di Cédric Morin
Ciao,

ho appena fatto delle prove e sembra che funzioni correttamente con la correzione!

Grazie!