如何通过Python脚本在Azure Linux VM上运行Shell脚本?
Azure Python SDK 执行Linux VM自定义Shell脚本实现方案
问题现象
通过Azure Python SDK调用虚拟机Run Command能力时,单行命令可正常执行,但无法运行独立Shell脚本文件:
- 可正常执行的单行命令代码:
run_command_parameters = { 'command_id': 'RunShellScript', 'script': 'ls -l /tmp' } poller = compute_client.virtual_machines.begin_run_command(resource_group, virtual_machine, run_command_parameters) result = poller.result() print(result.value[0].message)
- 将
script参数替换为'./my_script.sh'时代码执行失败 - 尝试传入未公开的
script_path参数时,仅返回默认示例脚本输出,未执行自定义脚本逻辑,返回内容如下:
Enable succeeded: [stdout] This is a sample script Optional parameters: /var/lib/waagent/run-command/download/59/script.sh [stderr]
核心原因
- Run Command接口的
script参数仅接收需要在目标虚拟机上逐行执行的命令内容,不识别本地开发机上的相对脚本路径;且Run Command默认以root身份在/root目录下执行,直接写./my_script.sh会因为路径不匹配找不到文件。 - 未公开的
script_path是SDK内置的默认示例脚本配置项,调用时会执行SDK自带的样例脚本,不会加载用户自定义脚本,因此返回样例脚本的固定输出。
正确实现方式
方案1:直接读取本地脚本内容传入(无需提前上传脚本)
这是最通用的方案,不需要提前将脚本上传到目标VM,SDK会自动将脚本内容通过Run Command通道传到VM执行:
# 读取本地自定义Shell脚本的完整内容 with open('./my_script.sh', 'r', encoding='utf-8') as f: script_content = f.read() run_command_parameters = { 'command_id': 'RunShellScript', 'script': [ # 将脚本内容写入VM临时目录 f"cat > /tmp/custom_script.sh << 'SCRIPT_EOF'\n{script_content}\nSCRIPT_EOF", # 赋予脚本可执行权限 'chmod 755 /tmp/custom_script.sh', # 执行脚本 'bash /tmp/custom_script.sh' ] } poller = compute_client.virtual_machines.begin_run_command( resource_group, virtual_machine, run_command_parameters ) result = poller.result() print(result.value[0].message)
方案2:执行VM上已存在的脚本
如果你的脚本已经提前上传到目标虚拟机的固定路径,直接在script参数中写全路径调用即可:
run_command_parameters = { 'command_id': 'RunShellScript', 'script': [ # 替换为你的脚本在VM上的实际存放路径 'chmod 755 /opt/scripts/my_script.sh', 'bash /opt/scripts/my_script.sh' ] } poller = compute_client.virtual_machines.begin_run_command( resource_group, virtual_machine, run_command_parameters ) result = poller.result() print(result.value[0].message)
注意:不要使用未公开的
script_path参数,该参数不属于对外提供的用户配置项,无法实现自定义脚本执行的需求。
内容的提问来源于stack exchange,提问作者sunrrrise
相关产品推荐
相关产品推荐

