问题描述

编写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. .NET源码解读kestrel服务器及创建HttpContext对象流程

    .NET本身就是一个基于中间件(middleware)的框架,它通过一系列的中间件组件来处理HTTP请求和响应.因此,本篇文章主要描述从用户键入请求到服务器响应的大致流程,并深入探讨.NET通过kes ...

  2. memcached使用中踩的一些坑

    背景 线上启用memcached(以下简称mc)作为热点缓存组件已经多年,其稳定性和性能都经历住了考验,这里记录一下踩过的几个坑. 大key存储 某年某月某日,观察mysql的读库CPU占比有些异常偏 ...

  3. 记一次 .NET 某医院预约平台 非托管泄露分析

    一:背景 1. 讲故事 前几天有位朋友找到我,说他的程序有内存泄露,让我帮忙排查一下,截图如下: 说实话看到 32bit, 1.5G 这些关键词之后,职业敏感告诉我,他这个可能是虚拟地址紧张所致,不管 ...

  4. Open LLM 排行榜近况

    Open LLM 排行榜是 Hugging Face 设立的一个用于评测开放大语言模型的公开榜单.最近,随着 Falcon 的发布并在 Open LLM 排行榜 上疯狂屠榜,围绕这个榜单在推特上掀起了 ...

  5. Git插件报错,Appears to be a git repo or submodule

    Hexo博客需要引入第三方插件,不少包作者误把包项目得.git文件上传到github,或者在插件的github路径下直接下载插件文件夹,结果是插件内含有.git文件,导致下载别的npm包时报错npm ...

  6. C补充

    C语言之unsigned 与signed 无符号与有符号数据的操作区别在于当最高位,当最高位为0时都一样: 在C中,默认的基础数据类型均为signed,现在我们以char为例,说明(signed) c ...

  7. 用极限网关实现 ES 容灾,简单!

    身为 IT 人士,大伙身边的各种系统肯定不少吧.系统虽多,但最最最重要的那套.那几套,大伙肯定是捧在手心,关怀备至.如此重要的系统,万一发生故障了且短期无法恢复,该如何保障业务持续运行? 有过这方面思 ...

  8. Word书签替换,加盖电子印章及转换PDF(Java实用版)

    一.前言 在项目中有需要对word进行操作的,可以看看哈,本次使用比较强大的spire组件来对word进行操作,免费版支持三页哦,对于不止三页的word文件,可以购买收费版,官网:https://ww ...

  9. fread()模板

    char buf[1<<20],*p1,*p2;#define GC (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin ...

  10. 如何新建一个django项目

    1.新建项目 2选择django 3.接下来我们进入 djangotest目录输入以下命令,启动服务器: python manage.py runserver 0.0.0.0:8000 0.0.0.0 ...