【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
【Azure Function App】Python Function调用Powershell脚本在Azure上执行失败的案例的更多相关文章
- C#调用PowerShell脚本
今天通过一个小例子,学习了C#如何调用PowerShell脚本文件的Function以及传参. private bool CallPowershell(string outputFile) { str ...
- 【黑客基础】Windows PowerShell 脚本学习(上)
视频地址:[黑客基础]Windows PowerShell 脚本学习 2019.12.05 学习笔记 1.$PSVersionTable :查看PowerShell的版本信息. 2.PowerShel ...
- Python Module_subprocess_调用 Powershell
目录 目录 前言 Powershell call Python Python call Powershell Powershell发送邮件 最后 前言 使用Python内建的subprocess模块, ...
- 利用python搭建Powersploit powershell脚本站点
powershell脚本站点的搭建 一.Powersploit Powersploit是一款基于powershell的后渗透(Post-Exploitation)框架,集成大量渗透相关模块和功能. 下 ...
- [Python]在python中调用shell脚本,并传入参数-02python操作shell实例
首先创建2个shell脚本文件,测试用. test_shell_no_para.sh 运行时,不需要传递参数 test_shell_2_para.sh 运行时,需要传递2个参数 test_shell ...
- 在Bat批处理中调用Powershell脚本
##如何在BAT中调用powershell,把下面代码另存为bat格式pushd %~dp0powershell.exe -command ^ "& {set-executionp ...
- 通过cmd调用Powershell脚本
一共需要3个文件,把这3个文件放在一个路径下 UTF8NoBOM.bat 这个文件是为了调用ps1 pwsh -file "%cd%\UTF8NoBOM.ps1" UTF8No ...
- cmd命令调用powershell脚本方法
cmd方法: powershell -command ". ('ps1脚本路径'); WriteInfo -param 'param参数值'" ps1脚本代码: function ...
- 怎样从 bat 批处理文件调用 PowerShell 脚本
https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file https: ...
- 自动化部署脚本之windows上执行批处理文件
windows .bat 批处理 脚本路径如下: install-simo.bat文件内容: @ECHO OFF set scriptpath=%~dp0set logfile=%scriptpa ...
随机推荐
- Grafana系列-GaC-1-Grafana即代码的几种实现方式
系列文章 Grafana 系列文章 Terraform 系列文章 概述 GaC(Grafana as Code, Grafana 即代码) 很明显是扩展自 IaC(Infrastructure as ...
- Devexpress如何获取RadioGroup选中项的值和显示值
分享一个小技巧,如题目所示,DEV控件如何获取RadioGroup选中项的值和显示值.也是在网上找了很久,看了大家都是通过SelectIndex的值定位选中的按钮,并没有说取选中项的值,所以自己研究了 ...
- GPT3:人工智能时代的新型语言模型
目录 GPT-3:人工智能时代的新型语言模型 随着人工智能技术的不断发展,自然语言处理领域也迎来了新的里程碑.GPT-3 是当前最具代表性的语言模型之一,它具有如下特点: GPT-3 是一种全新的语言 ...
- JavaCV人脸识别三部曲之二:训练
欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 本文是<JavaCV人脸识别三部曲&g ...
- 开发中MongoDB遇到的各种问题
目录 一.安装6版本以下 二.安装6版本及以上 三.安装6版本以下(解压版) 四.配置本地 Windows MongoGB 服务 五.navicat 连接远程mongodb数据库 六.ip不一致问题 ...
- 屏蔽CSDN百度广告
最近在查询一些技术问题访问到CSDN时一直弹一些令人作恶的广告,说个特别的广告,脱发广告,特别有针对性程序员同胞们的共性问题,不过还是特别恶心,百度了一下,大家也特别反感,CSDN你真这么缺钱?废话不 ...
- Pb从入坑到放弃(三)数据窗口
写在前面 数据窗口是Pb的一个特色控件,有了数据窗口对于pb来说可谓如虎添翼. 对数据库中的数据操作,几乎都可以在数据窗口中完成. 使用数据窗口可以简单检索数据.以图形化的方式显示数据.绘制功能强大的 ...
- 「学习笔记」Lambda 表达式
Lambda 表达式因数学中的 \(\lambda\) 演算得名, 直接对应于其中的 lambda 抽象. Lambda 表达式能够捕获作用域中的变量的无名函数对象, 我们可以将其理解为一个匿名的内联 ...
- NumPy(1)-常用的初始化方法
一.NumPy介绍 NumPy是Python中科学计算的基础包,它是一个Python库,提供多维数组对象,各种派生对象(如掩码数组和矩阵),以及用于数组快速操作的各种API,有包括数学.逻辑.形状操作 ...
- Spring的依赖注入方式(set及constructor)
Bean的依赖注入方式: set方法注入 P命名空间注入本质也是set方法注入,但比起上面的set方法进行注入更加方便,主要体现在配置文件中,如下: 首先,引入P命名空间: xmlns:p=" ...