You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible Tower(RedHat)删除远程NTFS共享旧文件的方案及问题解决

报错解决办法

你遇到的/bin/sh: powershell: command not found错误,核心原因是RHEL上安装的PowerShell二进制文件名为pwsh,但ansible.windows.win_powershell模块默认调用powershell命令,有两种直接解决方式:

  • 在Playbook中指定模块的executable参数
    调用模块时明确指定PowerShell的实际路径,示例:

    - name: 执行PowerShell命令
      ansible.windows.win_powershell:
        script: |
          # 你的PowerShell脚本内容
        executable: /usr/bin/pwsh
    

    注意:ansible.windows.win_powershell模块本质用于连接Windows目标主机执行代码,若你没有可连接的Windows主机,该模块并不适配你的场景,推荐使用下方的文件清理方案。

  • 创建软链接映射命令名
    在RHEL的Ansible Tower节点上执行以下命令,让系统识别powershell命令指向pwsh:

    sudo ln -s /usr/bin/pwsh /usr/bin/powershell
    
删除远程NTFS共享过期文件的最佳实现方案

由于无可用中间Windows主机,且Ansible Tower部署在RHEL上,推荐直接利用RHEL节点上的pwsh通过SMB协议访问远程共享,结合AD账号认证完成文件清理,无需依赖Windows执行主机。

Playbook示例

- name: 清理远程NTFS共享中超过指定天数的文件
  hosts: localhost
  vars:
    smb_share_path: "\\\\remote-server\\target-share"  # YAML需用双反斜杠转义UNC路径
    ad_domain_account: "YOUR-DOMAIN\\ad-service-user"
    ad_account_password: "your-secure-password"
    expire_days: 30  # 超过30天的文件将被删除
  tasks:
    - name: 执行PowerShell清理脚本
      ansible.builtin.shell: |
        pwsh -Command '$cred = New-Object System.Management.Automation.PSCredential ("{{ ad_domain_account }}", (ConvertTo-SecureString "{{ ad_account_password }}" -AsPlainText -Force)); Get-ChildItem -Path "{{ smb_share_path }}" -Recurse -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-{{ expire_days }}) } | Remove-Item -Force'
      no_log: true  # 禁止日志记录密码,避免泄露

关键细节说明

  • SMB路径处理:YAML中UNC路径需用双反斜杠转义,确保PowerShell能识别远程共享地址。
  • AD权限认证:通过PSCredential构造AD服务账号的凭据,保证访问NTFS共享的权限合规。
  • 文件筛选逻辑:递归遍历共享内所有文件,筛选出最后修改时间早于阈值天数的文件并强制删除。
  • 安全优化:建议将AD密码存储在Ansible Tower的凭据库中,通过lookup或vars_prompt调用,不要硬编码在Playbook内。

内容的提问来源于stack exchange,提问作者LJS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:41:57