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

如何在Jenkins中执行Shell脚本流水线任务并处理远程主机文件

在Jenkins中执行Shell文件并处理远程主机文件的方案

前置准备

  • 确保Jenkins节点(或主节点)能通过SSH访问目标远程主机,可在Jenkins凭据管理中配置SSH凭据(用户名+密码/密钥对)。
  • 确认远程主机已安装curl、jq(如需处理JSON)等必要工具。

流水线实现步骤

1. 拉取远程主机的输入文件file.json

通过SSH或scp将远程主机上的输入文件拷贝到Jenkins工作目录:

# 方式1:用SSH直接读取文件内容到本地
ssh your_remote_user@remote_host_ip "cat /remote/path/to/file.json" > ./file.json

# 方式2:用scp拷贝文件
scp your_remote_user@remote_host_ip:/remote/path/to/file.json ./

替换your_remote_user、remote_host_ip、/remote/path/to/file.json为实际信息。

2. 执行Shell脚本及指定的curl命令

假设你的Shell逻辑需要结合输入文件调用给定的curl命令,可直接在流水线中编写脚本逻辑,或执行已有的Shell文件:

#!/bin/bash
# 读取本地的输入文件内容(如果curl需要用到)
INPUT_CONTENT=$(cat ./file.json)

# 执行curl命令,替换<artifactory_host>为实际地址,填入凭据
curl -u artifactory_user:artifactory_pwd -X POST -k -H 'Content-Type:text/plain' -i https://<artifactory_host>/artifactory/api/search/aql -d "$INPUT_CONTENT" > output.json

在Jenkins流水线中执行这段逻辑:

sh '''
chmod +x ./your_script.sh # 如果是执行外部Shell文件
./your_script.sh
'''

3. 将输出JSON拷贝回远程主机

再次使用SSH或scp将生成的output.json传输到远程主机指定路径:

# 方式1:scp推送文件
scp ./output.json your_remote_user@remote_host_ip:/remote/destination/path/

# 方式2:SSH管道写入文件
cat ./output.json | ssh your_remote_user@remote_host_ip "cat > /remote/destination/path/output.json"

完整Jenkins流水线示例

pipeline {
    agent any
    environment {
        REMOTE_USER = 'your_remote_user'
        REMOTE_HOST = 'x.x.x.x'
        INPUT_FILE = '/remote/path/to/file.json'
        OUTPUT_PATH = '/remote/save/path/output.json'
        ARTIFACTORY_HOST = 'your_artifactory_domain'
        ARTIFACT_CREDS = credentials('jenkins-artifactory-creds') // Jenkins中配置的凭据ID
    }
    stages {
        stage('拉取远程输入文件') {
            steps {
                sh "ssh ${REMOTE_USER}@${REMOTE_HOST} 'cat ${INPUT_FILE}' > ./file.json"
            }
        }
        stage('执行Shell逻辑与curl命令') {
            steps {
                sh '''
                    INPUT_CONTENT=$(cat ./file.json)
                    curl -u ${ARTIFACT_CREDS_USR}:${ARTIFACT_CREDS_PSW} -X POST -k -H 'Content-Type:text/plain' -i https://${ARTIFACTORY_HOST}/artifactory/api/search/aql -d "$INPUT_CONTENT" > output.json
                '''
            }
        }
        stage('推送输出到远程主机') {
            steps {
                sh "scp ./output.json ${REMOTE_USER}@${REMOTE_HOST}:${OUTPUT_PATH}"
            }
        }
    }
}

注意事项

  • 建议将Jenkins节点的SSH公钥添加到远程主机的~/.ssh/authorized_keys中,实现无密码访问,避免流水线执行时阻塞。
  • 如果curl命令不需要用到file.json的内容,可直接跳过拉取输入文件的步骤。
  • 若输出JSON体积较大,优先使用scp传输,避免管道传输导致的数据丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:34:53