问题描述

编写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

【Azure Function App】Python Function调用Powershell脚本在Azure上执行失败的案例的更多相关文章

  1. C#调用PowerShell脚本

    今天通过一个小例子,学习了C#如何调用PowerShell脚本文件的Function以及传参. private bool CallPowershell(string outputFile) { str ...

  2. 【黑客基础】Windows PowerShell 脚本学习(上)

    视频地址:[黑客基础]Windows PowerShell 脚本学习 2019.12.05 学习笔记 1.$PSVersionTable :查看PowerShell的版本信息. 2.PowerShel ...

  3. Python Module_subprocess_调用 Powershell

    目录 目录 前言 Powershell call Python Python call Powershell Powershell发送邮件 最后 前言 使用Python内建的subprocess模块, ...

  4. 利用python搭建Powersploit powershell脚本站点

    powershell脚本站点的搭建 一.Powersploit Powersploit是一款基于powershell的后渗透(Post-Exploitation)框架,集成大量渗透相关模块和功能. 下 ...

  5. [Python]在python中调用shell脚本,并传入参数-02python操作shell实例

    首先创建2个shell脚本文件,测试用. test_shell_no_para.sh 运行时,不需要传递参数 test_shell_2_para.sh 运行时,需要传递2个参数  test_shell ...

  6. 在Bat批处理中调用Powershell脚本

    ##如何在BAT中调用powershell,把下面代码另存为bat格式pushd %~dp0powershell.exe -command ^  "& {set-executionp ...

  7. 通过cmd调用Powershell脚本

    一共需要3个文件,把这3个文件放在一个路径下 UTF8NoBOM.bat   这个文件是为了调用ps1 pwsh -file "%cd%\UTF8NoBOM.ps1" UTF8No ...

  8. cmd命令调用powershell脚本方法

    cmd方法: powershell -command ". ('ps1脚本路径'); WriteInfo  -param 'param参数值'" ps1脚本代码: function ...

  9. 怎样从 bat 批处理文件调用 PowerShell 脚本

    https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file https: ...

  10. 自动化部署脚本之windows上执行批处理文件

    windows  .bat  批处理 脚本路径如下: install-simo.bat文件内容: @ECHO OFF set scriptpath=%~dp0set logfile=%scriptpa ...

随机推荐

  1. 【HarmonyOS】详解低代码端云一体化开发之连接器

    ​[关键字] 元服务.低代码平台.端云一体化开发.连接器.拖拽式UI [1.写在前面] 前面我们写了两篇文章分别介绍了低代码平台的基本使用和端云一体化开发中数据模型的使用,有需要的可以了解一下,文章地 ...

  2. Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.10.8 提供带注解的限定符元数据

    6.1.1 提供带注解的限定符元数据 在第6.9.4节"使用@Qualifier微调基于注解的自动装配"中讨论了@Qualifier注解.该部分中的示例阐释了,在解析自动装配候选者 ...

  3. Paimon读取流程

    查询模式 先来看看官网关于Paimon查询模式的说明 可以看到查询模式围绕snapshot展开, 而snapshot分了两种一种是Last compact snapshot和 last snapsho ...

  4. 我在使用Winform7.0开发海康相机应用的时候系统悄无声息的退出

    一.简介 1.说明一下 最近,我在开发一个玻璃幕墙检测的项目,这个项目需要使用到海康的相机系统.业务是这样的,相机按着指定的坐标,扫描玻璃幕墙的每块玻璃,通过算法查看是否有损坏的,如果有就发出报警信息 ...

  5. C++面试八股文:什么是空指针/野指针/悬垂指针?

    某日二师兄参加XXX科技公司的C++工程师开发岗位第30面: 面试官:什么是空指针? 二师兄:一般我们将等于0/NULL/nullptr的指针称为空指针.空指针不能被解引用,但是可以对空指针取地址. ...

  6. Spring容器获取Bean的9种方式

    1 前言 随着SpringBoot的普及,Spring的使用也越来越广,在某些场景下,我们无法通过注解或配置的形式直接获取到某个Bean.比如,在某一些工具类.设计模式实现中需要使用到Spring容器 ...

  7. MyBatis实现动态SQL更新

    博主记得在一个周五快下班的下午,产品找到我(为什么总感觉周五快下班就来活 ),跟我说有几个业务列表查询需要加上时间条件过滤数据,这个条件可能会变,不保证以后不修改,这个改动涉及到多个列表查询,于是博主 ...

  8. 项目完成小结:使用Blazor和gRPC开发大模型客户端

    前言 先介绍下这个项目. 最近我一直在探索大语言模型,根据不同场景训练了好几个模型,为了让用户测试使用,需要开发前端. 这时候,用 Gradio 搭建的前端是不太够的,虽说 GitHub 上也有一堆开 ...

  9. 20.1K Star!Notion的开源替代方案:AFFiNE

    Notion这款笔记软件相信很多开发者都比较熟悉了,很多读者,包括我自己都用它来记录和管理自己的笔记.今天给大家推荐一个最近比较火的开源替代方案:AFFiNE.目前该开源项目已经斩获20.1K Sta ...

  10. ENVI、ERDAS计算Landsat 7地表温度:单窗算法实现

    本文介绍基于ENVI与ERDAS软件,对Landsat 7遥感影像数据加以单窗算法的地表温度(LST)反演操作. 目录 1 原理部分与前期操作准备 1.1 图像预处理 1.2 植被指数反演 1.3 单 ...