【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 ...
随机推荐
- 全志G2D实现屏幕旋转,开机logo实现手动旋转。
产品设计出来之后啊,大家使用的时候觉得反过来使用更加便捷.但是屏幕显示是反的.那怎么办那????? 修改硬件费时费工,那能否软件实现那????? 如果纯软件使用那就太费系统资源了.于是就想到了使用全志 ...
- 前端vue可以左右滚动的切换的tabs tabs选项卡 滑动动画效果 自动宽度
前端vue可以左右滚动的切换的tabs tabs选项卡 滑动动画效果 自动宽度, 下载完整代码请访问https://ext.dcloud.net.cn/plugin?id=13003 效果图如下: ...
- Python编程和机器学习中的自然语言处理:如何从文本中提取有意义的信息和数据
目录 引言 自然语言处理(Natural Language Processing,NLP)是一种人工智能技术,旨在使计算机理解和处理自然语言文本,从中提取有意义的信息和数据.NLP是机器学习领域中的重 ...
- celery笔记七之周期/定时任务及crontab定义
本文首发于公众号:Hunter后端 原文链接:celery笔记七之周期/定时任务及crontab定义 periodic task,即为周期,或者定时任务,比如说每天晚上零点零分需要运行一遍某个函数,或 ...
- kafka学习笔记01
类似于京东商城这种电商系统,一般会在前端页面进行埋点记录仪用户的行为数据,包括浏览.点赞.收藏.评论等.这些行为会被记录到日志服务器中,使用Flume进行采集,然后传入Hadoop中. Flu ...
- 【Promptulate】一个强大的LLM Prompt Layer框架
本文节选自笔者博客: https://www.blog.zeeland.cn/archives/promptulate666 前言 在构建了[prompt-me]一个专为 Prompt Enginee ...
- 图书商城项目练习②后端服务Node/Express/Sqlite
本系列文章是为学习Vue的项目练习笔记,尽量详细记录一下一个完整项目的开发过程.面向初学者,本人也是初学者,搬砖技术还不成熟.项目在技术上前端为主,包含一些后端代码,从基础的数据库(Sqlite).到 ...
- golang 实现四层负载均衡
大家好,我是蓝胖子,做开发的同学应该经常听到过负载均衡的概念,今天我们就来实现一个乞丐版的四层负载均衡,并用它对mysql进行负载均衡测试,通过本篇你可以了解到零拷贝的应用,四层负载均衡的本质以及实践 ...
- gRPC vs. HTTP:网络通信协议的对比
概述 gRPC 和 HTTP 是两种常见的网络通信协议,用于在客户端和服务器之间进行通信.它们具有不同的特点和适用场景,下面对它们进行详细比较. HTTP(Hypertext Transfer Pro ...
- Windows同时安装多个JDK
一.下载并安装JDK这一步选择你需要的JDK并下载安装,记得要记住安装的路径. 二.为JDK配置环境变量①找到系统环境变量 ②新建如下三个环境变量 第一个表示默认Java的home路径,以后在更改JD ...