【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

 

相关文章
|
2月前
|
存储 安全 数据安全/隐私保护
【Azure Function App】在Function App中使用System Managed Identity访问Storage Account
本文介绍了如何在Azure Function中使用托管身份(Managed Identity)替代AzureWebJobsStorage连接函数应用到存储账户,以提高安全性并减少Access Key的使用。具体步骤包括:1) 启用系统分配的身份;2) 为函数应用授予存储访问权限,添加必要角色(如Storage Blob Data Contributor);3) 配置`AzureWebJobsStorage__blobServiceUri`参数指定Blob Service Uri。完成后删除旧配置,即可通过Managed Identity访问Storage Account。
110 20
|
1月前
|
数据采集 运维 API
把Postman调试脚本秒变Python采集代码的三大技巧
本文介绍了如何借助 Postman 调试工具快速生成 Python 爬虫代码,并结合爬虫代理实现高效数据采集。文章通过“跨界混搭”结构,先讲解 Postman 的 API 调试功能,再映射到 Python 爬虫技术,重点分享三大技巧:利用 Postman 生成请求骨架、通过 Session 管理 Cookie 和 User-Agent,以及集成代理 IP 提升稳定性。以票务信息采集为例,展示完整实现流程,探讨其在抗封锁、团队协作等方面的价值,帮助开发者快速构建生产级爬虫代码。
把Postman调试脚本秒变Python采集代码的三大技巧
|
26天前
|
安全 Linux 开发工具
【Azure Function】分享把Function App从.NET 6.0升级到.NET 8.0 Isolated的步骤
本文介绍了将Azure Function App从.NET 6.0升级到.NET 8.0 Isolated的步骤。.NET 6.0作为长期支持版本,生命周期至2024年11月结束。为确保持续支持,建议升级至更新版本。升级步骤包括安装.NET 8 SDK、更新Azure Functions Core Tools、修改项目文件目标框架为net8.0、更新兼容的NuGet包、本地测试以及重新发布到Azure。更多详细信息可参考官方文档。
|
1月前
【Function App】在PowerShell Function中指定特殊的Microsoft.Graph.Users版本
在Azure Function App中运行PowerShell Function时,通过Requirements.psd1文件管理模块版本。若需将“Microsoft.Graph.Users”从最新版2.26.0改回2.23.0以避免冲突,可通过以下步骤解决:1) 在requirements.psd1中明确指定版本为2.23.0 2) 在profile.ps1中添加`Import-Module Microsoft.Graph.Users -RequiredVersion 2.23.0`语句。此方法确保加载特定版本模块
59 18
|
2月前
|
数据采集 数据可视化 大数据
Python入门修炼:开启你在大数据世界的第一个脚本
Python入门修炼:开启你在大数据世界的第一个脚本
103 6
|
5月前
|
C#
【Azure Function】Function App出现System.IO.FileNotFoundException异常
Exception while executing function: xxxxxxx,The type initializer for 'xxxxxx.Storage.Adls2.StoreDataLakeGen2Reading' threw an exception. Could not load file or assembly 'Microsoft.Extensions.Configuration, Version=9.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the
154 64
|
3月前
|
SQL Oracle 关系型数据库
【YashanDB知识库】共享利用Python脚本解决Oracle的SQL脚本@@用法
【YashanDB知识库】共享利用Python脚本解决Oracle的SQL脚本@@用法
|
2月前
|
存储 数据库 UED
【Axure原型案例】悦购APP产品原型设计
本文介绍了悦购APP的产品原型设计,专注于潮流服装市场。设计包括登录、过渡、首页、商品分享、个人中心、购物车、消息及修改信息等页面。通过Axure实现交互功能,如页面跳转、动态效果和数据模拟,优化内容、交互与兼容性,确保用户体验流畅。最终,原型为开发和推广提供了坚实基础,助力悦购APP成为高效的潮流购物平台。
113 0
|
4月前
|
JavaScript Shell C#
多种脚本批量下载 Docker 镜像:Shell、PowerShell、Node.js 和 C#
本项目提供多种脚本(Shell、PowerShell、Node.js 和 C#)用于批量下载 Docker 镜像。配置文件 `docker-images.txt` 列出需要下载的镜像及其标签。各脚本首先检查 Docker 是否安装,接着读取配置文件并逐行处理,跳过空行和注释行,提取镜像名称和标签,调用 `docker pull` 命令下载镜像,并输出下载结果。使用时需创建配置文件并运行相应脚本。C# 版本需安装 .NET 8 runtime。
237 2
|
3月前
|
SQL Oracle 关系型数据库
【YashanDB知识库】共享利用Python脚本解决Oracle的SQL脚本@@用法
本文来自YashanDB官网,介绍如何处理Oracle客户端sql*plus中使用@@调用同级目录SQL脚本的场景。崖山数据库23.2.x.100已支持@@用法,但旧版本可通过Python脚本批量重写SQL文件,将@@替换为绝对路径。文章通过Oracle示例展示了具体用法,并提供Python脚本实现自动化处理,最后调整批处理脚本以适配YashanDB运行环境。

热门文章

最新文章

推荐镜像

更多