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

简介: 【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://<your function app name>.scm.chinacloudsites.cn/newui), 查看 Logfiles/Application/Functions/Function/<your function name>/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

 

相关文章
|
10天前
|
存储 Shell 区块链
怎么把Python脚本打包成可执行程序?
该文档介绍了如何将Python脚本及其运行环境打包成EXE可执行文件,以便在不具备Python环境的计算机上运行。首先确保Python脚本能够正常运行,然后通过安装PyInstaller并使用`--onefile`参数将脚本打包成独立的EXE文件。此外,还提供了去除命令行窗口和指定可执行文件图标的详细方法。这些步骤帮助用户轻松地将Python程序分发给最终用户。
怎么把Python脚本打包成可执行程序?
|
4天前
|
安全 JavaScript 前端开发
自动化测试的魔法:如何用Python编写你的第一个测试脚本
【8月更文挑战第41天】在软件的世界里,质量是王道。而自动化测试,就像是维护这个王国的骑士,确保我们的软件产品坚不可摧。本文将引导你进入自动化测试的奇妙世界,教你如何使用Python这把强大的魔法杖,编写出能够守护你代码安全的第一道防护咒语。让我们一起开启这场魔法之旅吧!
|
5天前
【Azure Logic App】使用Event Hub 连接器配置 Active Directory OAuth 认证无法成功连接到中国区Event Hub的解决之法
An exception occurred while retrieving properties for Event Hub: logicapp. Error Message: 'ClientSecretCredential authentication failed: AADSTS90002: Tenant 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Che
|
10天前
|
存储 Java 开发者
python脚本实现原理
【9月更文挑战第4天】python脚本实现原理
25 5
|
7天前
|
运维 监控 API
自动化运维:使用Python脚本进行日常管理
【9月更文挑战第6天】在现代的IT环境中,自动化运维已成为提升效率、减少人为错误的关键。本文将介绍如何通过Python脚本简化日常的运维任务,包括批量配置管理和日志分析。我们将从基础语法讲起,逐步深入到脚本的实际应用,旨在为读者提供一套完整的解决方案,以实现运维工作的自动化和优化。
11 1
|
11天前
|
安全
【Azure App Service】App service无法使用的情况分析
App Service集成子网后,如果子网网段中的剩余IP地址非常少的情况下,会在App Service实例升级时( 先加入新实例,然后在移除老实例 )。新加入的实例不能被分配到正确的内网IP地址,无法成功的访问内网资源。 解决方法就是为App Service增加子网地址, 最少需要/26 子网网段地址。
|
20天前
【Azure Durable Function】PowerShell Activity 函数遇见 Newtonsoft.Json.JsonReaderException: The reader's MaxDepth of 64 has been exceeded.
【Azure Durable Function】PowerShell Activity 函数遇见 Newtonsoft.Json.JsonReaderException: The reader's MaxDepth of 64 has been exceeded.
|
20天前
|
安全 JavaScript 应用服务中间件
【Azure Function App】如何修改Azure函数应用的默认页面呢?
【Azure Function App】如何修改Azure函数应用的默认页面呢?
|
20天前
|
C# C++ Python
【Azure 应用服务】Azure Durable Function(持久函数)在执行Activity Function时候,因为调用函数名称错误而导致长时间无响应问题
【Azure 应用服务】Azure Durable Function(持久函数)在执行Activity Function时候,因为调用函数名称错误而导致长时间无响应问题
|
20天前
|
SQL JavaScript 前端开发
【Azure 应用服务】Azure JS Function 异步方法中执行SQL查询后,Callback函数中日志无法输出问题
【Azure 应用服务】Azure JS Function 异步方法中执行SQL查询后,Callback函数中日志无法输出问题