使用Ansible执行脚本:远程脚本输出保存至远程服务器文件失败求助
解决Ansible远程执行脚本并保存输出到远程文件的问题
你的核心问题出在**command模块不支持Shell的重定向语法(比如>>)**——因为command模块会直接执行命令,不会调用系统Shell解析这些特殊语法,所以输出重定向根本不会生效。下面给你几种可靠的解决方案,按需选择:
方法一:用shell模块直接支持重定向(最简单)
shell模块会通过系统Shell(默认是/bin/sh)执行命令,完全支持重定向、管道等Shell特性,这是最直接的解决方式:
- name: Transfer and execute script, save output remotely hosts: slave remote_user: root become: yes # 新版本Ansible建议用become替代旧的sudo: yes tasks: - name: Transfer the script to remote server copy: src: uptime.sh dest: /home/uptime.sh # 建议指定完整文件名,避免歧义 mode: 0777 - name: Execute script and save output (including errors) shell: /home/uptime.sh >> /home/uptime_output.txt 2>&1 # 2>&1 把错误输出也重定向到文件,方便排查脚本执行问题
如果你的脚本开头已经有#!/bin/sh或#!/bin/bash的Shebang,甚至可以直接写/home/uptime.sh,不用加sh前缀。
方法二:用command模块+捕获输出写入文件(更灵活)
如果坚持要用command模块,可以先捕获脚本执行的输出,再写入远程文件——这种方式还能在Ansible端先处理输出(比如过滤、修改内容):
- name: Transfer, execute script and save output hosts: slave remote_user: root become: yes tasks: - name: Transfer script copy: src: uptime.sh dest: /home/uptime.sh mode: 0777 - name: Run script and capture output command: /home/uptime.sh register: script_result - name: Write output to remote file(覆盖模式) copy: content: "{{ script_result.stdout }}\n" dest: /home/uptime_output.txt mode: 0644 # 如果需要追加内容而非覆盖,替换成下面的lineinfile模块 - name: Append output to remote file(追加模式) lineinfile: path: /home/uptime_output.txt line: "{{ script_result.stdout }}" create: yes # 文件不存在时自动创建
方法三:用script模块一步完成脚本传输+执行
如果你不需要在远程服务器保留脚本文件,可以用script模块——它会自动把本地脚本上传到远程临时目录,执行后自动删除临时文件:
- name: Run local script remotely and save output hosts: slave remote_user: root become: yes tasks: - name: Execute local script on remote and capture output script: uptime.sh register: script_result - name: Save both stdout and stderr to remote file copy: content: "=== Script Output ===\n{{ script_result.stdout }}\n\n=== Error Output ===\n{{ script_result.stderr }}\n" dest: /home/uptime_output.txt mode: 0644
额外注意事项
- 确保远程服务器的
/home目录有写入权限(用root用户的话没问题,普通用户需要提前确认权限); - 脚本的可执行权限:
mode: 0777虽然能保证可执行,但生产环境建议用更严格的0755; - 如果你用的是Ansible 2.4+,尽量用
become: yes替代旧的sudo: yes语法,更符合官方规范。
内容的提问来源于stack exchange,提问作者Akhil Teej
相关产品推荐
相关产品推荐

