首页 > 系统相关 >【Azure Function App】Python Function调用Powershell脚本在Azure上执行失败的案例

【Azure Function App】Python Function调用Powershell脚本在Azure上执行失败的案例

时间:2023-10-07 20:25:43浏览次数:33  
标签:Function function run Python azure Azure powershell

问题描述

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

 

标签:Function,function,run,Python,azure,Azure,powershell
From: https://www.cnblogs.com/lulight/p/17747359.html

相关文章

  • python过滤以#;//号开头的行注释行 startswith()
    作用:过滤指定符号开头的行(过滤注释行)Pythonstartswith()方法用于检查字符串是否是以指定子字符串开头,如果是则返回True,否则返回False。如果参数beg和end指定值,则在指定范围内检查。方法(函数):str.startswith(substr,beg=0,end=len(string));参数:str--......
  • python28days
    面向过程编程面向对象编程类的定义和对象的产生定制对象自己独有的属性属性的查找顺序(类属性,对象属性)—————————————————————————————————————————————————————————————在编程中,面向过程和面向对象是编程的两大......
  • Python 图片管理工具介绍(筛像素+从文件夹取出图片并放到文件夹内+excel读取)
    功能介绍:这是一个Python脚本工具,用于批量管理和复制图片。其主要功能如下:从Excel表格读取数据:程序使用openpyxl库从Excel文件中读取数据,其中A列包含源图片的路径(可以有多个路径,用逗号分隔),B列包含目标目录。图片筛选:仅复制最小维度大于800像素的图片,这可以确保目标目录中的......
  • Python3.12 新特性——GIL 重大突破!
    Python3.12新特性2023年10月2日,Python3.12正式发布了,和之前版本相比,Python3.12有比较大的更新,核心最主要的就是能够支持解释器之间的隔离了,在一个Python进程当中能够有多个解释器,这在一定程度上缓解了GIL带来的问题,在这个版本当中主要有下面的一些主要的新特性:更灵......
  • Python标准库分享之文件管理 (部分os包,shutil包)
    在操作系统下,用户可以通过操作系统的命令来管理文件,参考linux文件管理相关命令。Python标准库则允许我们从Python内部管理文件。相同的目的,我们有了两条途径。尽管在Python调用标准库的方式不如操作系统命令直接,但有它自己的优势。你可以利用Python语言,并发挥其他Python工具,形成组......
  • 【接口自动化】安装环境-python
    1.下载Python访问Python官网: www.python.org/点击downloads按钮,在下拉框中选择系统类型(windows/MacOS/Linux等)选择下载最新版本的Python没有版本要求的话,尽量使用最新版本前几个版本。避免新版本的不稳定 2. 安装Python双击下载好的Python安装包勾选左下角Add......
  • python的装饰器
    python的装饰器1、装饰器的定义给已有的函数添加额外功能的函数,它本质上就是一个闭包函数。装饰器的功能特点:不修改已有函数的功能特点不修改已有函数的调用方式给已有函数添加额外的功能需求:给comment函数添加一个额外功能(需要先登陆,再评论)要求:不能改变现有comment函数......
  • python日志logger
    写代码过程中,为了方便问题定位,经常需要打印信息,但是太多的print()不好,所以可以用到loggerLogger通常分为两类:一类是StreamHandler,将日志信息输出到控制台;另一类是FileHandler,将日志信息输出到文件。Python标准库中的logging模块提供了强大的Logger功能。importloggingcla......
  • python+playwright 元素操作
    Playwright可以与HTML输入元素交互,例如文本输入、复选框、单选按钮、选择选项、鼠标单击、键入字符、键和快捷方式以及上传文件和焦点元素。fill()输入文字使用 locator.fill() 是填写表单字段的最简单方法。它聚焦元素并input使用输入的文本触发事件。它适用于<input>,<t......
  • Python笔记目录
    Python笔记目录本视频学习自b站python视频,原地址在此笔记在原版笔记的基础上根据自己的理解做了调整,与原版的顺序和内容有有些区别笔记仅供学习使用,侵删第一章Python的安装、卸载第二章PyCharm的下载、安装、使用第三章Python的编写和运行第四章Python的基础语法......