• 【Azure Function App】Python Function调用Powershell脚本在Azure上执行失败的案例


    问题描述

    编写Python Function,并且在Function中通过 subprocess  调用powershell.exe 执行 powershell脚本。

    复制代码
    import azure.functions as func
    import logging
    import subprocess
    
    
    app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
    
    def run(cmd):
        completed = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
        return completed
    
    @app.route(route="http_trigger")
    def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
    
        name = req.params.get('name')
        if not name:
            try:
                req_body = req.get_json()
            except ValueError:
                pass
            else:
                name = req_body.get('name')
    
        hello_command = "Write-Host 'Hello Wolrd!"+name+"'"
        hello_info = run(hello_command)
        if hello_info.returncode != 0:
            logging.info("An error occured: %s", hello_info.stderr)
        else:
            logging.info("Hello command executed successfully!")
        
        logging.info("-------------------------")
    
        logging.info(str(hello_info.stdout))
    
        if name:
            return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
        else:
            return func.HttpResponse(
                 "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
                 status_code=200
            )
        
    复制代码

    本地测试环境为Windows,执行成功!

    当通过VS Code部署到Azure Function App后,在门户上调用就出现 500 Internal Server Error 错误。

    这是什么情况呢?

     

    问题解答

    查看Azure Function的后台日志,进入Kudu站点(https://.scm.chinacloudsites.cn/newui), 查看 Logfiles/Application/Functions/Function//xxxxxxx_xxxxx.log

    复制代码
    2023-10-07T11:32:41.605 [Information] Executing 'Functions.http_trigger' (Reason='This function was programmatically called via the host APIs.', Id=353799e7-fb4f-4ec9-bb42-ed2cafbda9da)
    2023-10-07T11:32:41.786 [Information] Python HTTP trigger function processed a request.
    2023-10-07T11:32:41.874 [Error] Executed 'Functions.http_trigger' (Failed, Id=353799e7-fb4f-4ec9-bb42-ed2cafbda9da, Duration=275ms)
    Result: Failure
    Exception: FileNotFoundError: [Errno 2] No such file or directory: 'powershell'
    Stack:   File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 479, in _handle__invocation_request
        call_result = await self._loop.run_in_executor(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
        result = self.fn(*self.args, **self.kwargs)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 752, in _run_sync_func
        return ExtensionManager.get_sync_invocation_wrapper(context,
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/extension.py", line 215, in _raw_invocation_wrapper
        result = function(**args)
                 ^^^^^^^^^^^^^^^^
      File "/home/site/wwwroot/function_app.py", line 26, in http_trigger
        hello_info = run(hello_command)
                     ^^^^^^^^^^^^^^^^^^
      File "/home/site/wwwroot/function_app.py", line 9, in run
        completed = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/local/lib/python3.11/subprocess.py", line 548, in run
        with Popen(*popenargs, **kwargs) as process:
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/usr/local/lib/python3.11/subprocess.py", line 1026, in __init__
        self._execute_child(args, executable, preexec_fn, close_fds,
      File "/usr/local/lib/python3.11/subprocess.py", line 1950, in _execute_child
        raise child_exception_type(errno_num, err_msg, err_filename)
    复制代码

    发现异常 “ Exception: FileNotFoundError: [Errno 2] No such file or directory: 'powershell' ”,

    进入Kudu的Bash 或 SSH 页面,通过powershell 和 pwsh 命令,验证当前环境是否有安装PowerShell

    因为Azure中创建的Python Function均为Linux系统,而Linux中没有安装Powershell,所以才出现Python代码中调用Python失败。

    那是否可以自己在Function App的环境中安装Powershell呢? 答案不可以。

    那是否有其他的方案呢?

    有的,Azure Function可以创建Powershell Function,把PowerShell作为一个HTTP Trigger的Function,在Python Function中调用Powershell Function的URL,就可以实现在Azure上调用PowerShell的目的。

     

     

    参考资料

    Installing PowerShell on Ubuntu : https://learn.microsoft.com/en-us/powershell/scripting/install/install-ubuntu?view=powershell-7.3

    在 Azure 中使用 Visual Studio Code 创建 PowerShell 函数:https://docs.azure.cn/zh-cn/azure-functions/create-first-function-vs-code-powershell

    在 Azure 中使用 Visual Studio Code 创建 Python 函数 : https://docs.azure.cn/zh-cn/azure-functions/create-first-function-vs-code-python?pivots=python-mode-configuration

     

  • 相关阅读:
    幕译--本地字幕生成与翻译--Whisper客户端
    【C++】vector,list迭代器失效
    Java Timer使用介绍
    使用c++17std库varaint替代varaint开源库报错处理
    怎么把heic改成jpg?方法大全在这里
    地下水深度去除铁锰的滤料详解
    ORB-SLAM2 ---- IC_Angle函数
    解答嵌入式和单片机的关系
    含文档+PPT+源码等]精品基于SSM的旅游信息管理系统的设计与实现[包运行成功]
    智慧教育信息化建设解决方案
  • 原文地址:https://www.cnblogs.com/lulight/p/17747359.html