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

如何在Airflow中从GitHub读取脚本并直接在远程Unix服务器执行?

Airflow实现从GitHub读取脚本并远程执行(不落地脚本)

有两种可行方案,均无需将脚本文件复制到远程服务器:

方案一:SSH Operator结合curl直接拉取执行

直接在SSH Operator的命令中通过curl拉取GitHub上的脚本内容,管道传给bash执行:

from airflow.providers.ssh.operators.ssh import SSHOperator

execute_github_script = SSHOperator(
    task_id="execute_github_script",
    ssh_conn_id="your_remote_server_conn",  # Airflow中已配置的远程服务器SSH连接ID
    command=(
        "curl -s https://raw.githubusercontent.com/你的用户名/你的仓库名/main/hello.sh | bash"
    ),
)

如果是私有仓库,需在curl命令中带上GitHub个人访问令牌(PAT):

curl -s -H "Authorization: token 你的PAT令牌" https://raw.githubusercontent.com/你的用户名/你的仓库名/main/hello.sh | bash

方案二:Python Operator配合SSH Hook读取并执行

先通过Python从GitHub获取脚本内容,再通过SSH Hook将内容传入远程服务器的bash执行:

from airflow.providers.ssh.hooks.ssh import SSHHook
from airflow.operators.python import PythonOperator
import requests

def run_github_script():
    # 拉取脚本内容
    github_url = "https://raw.githubusercontent.com/你的用户名/你的仓库名/main/hello.sh"
    # 私有仓库需添加headers
    headers = {"Authorization": "token 你的PAT令牌"}
    response = requests.get(github_url, headers=headers)
    script_content = response.text

    # 建立SSH连接并执行脚本
    ssh_hook = SSHHook(ssh_conn_id="your_remote_server_conn")
    with ssh_hook.get_conn() as ssh_client:
        stdin, stdout, stderr = ssh_client.exec_command("bash")
        stdin.write(script_content)
        stdin.flush()
        stdin.channel.shutdown_write()
        
        # 处理执行输出与错误
        print(stdout.read().decode())
        error_msg = stderr.read().decode()
        if error_msg:
            raise Exception(f"脚本执行出错: {error_msg}")

execute_script_task = PythonOperator(
    task_id="execute_script_task",
    python_callable=run_github_script
)

注意事项

  • 确保远程服务器能访问GitHub,内网环境需配置代理或使用内网GitHub地址。
  • 私有仓库的访问令牌需具备仓库读取权限,且建议通过Airflow变量存储,不要硬编码。
  • 两种方案均不会将脚本写入远程服务器磁盘,完全通过流式方式执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:20:27