Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

一個指令把檔案推到多台主機:mooon_upload 工具解析

編輯:關於 Android 開發

一個指令把檔案推到多台主機:mooon_upload 工具解析

運維工作中有一類需求特別瑣碎:把同一份檔案發到十幾台機器上。逐台 scp 顯然不現實,而 Ansible、SaltStack 這類重量級方案對小規模場景又顯得殺雞用牛刀。這裡介紹一個輕量做法——自己寫一支以 libssh2 為基礎的批次上傳小工具。

使用方式

./mooon_upload -h=192.168.10.11,192.168.10.12 -p=6000 -u=root -P='root123' -s=./abc -d=/tmp/

這行指令的意思很直白:把本地的 ./abc 上傳到 192.168.10.11 與 192.168.10.12 兩台機器的 /tmp/ 目錄,SSH 連接埠是 6000。

參數設計

參數定義用了自家庭中繼的巨集,好處是把型別、預設值、取值範圍與說明集中在一處宣告:

#include "mooon/net/libssh2.h"
#include "mooon/sys/stop_watch.h"
#include "mooon/utils/args_parser.h"
#include "mooon/utils/print_color.h"
#include "mooon/utils/string_utils.h"
#include "mooon/utils/tokener.h"
#include <fstream>
#include <iostream>

// 逗號分隔的遠端主機列表
STRING_ARG_DEFINE(h, "", "remote hosts");
// 遠端主機的 sshd 埠號
INTEGER_ARG_DEFINE(uint16_t, p, 22, 10, 65535, "remote hosts port");
// 使用者名稱
STRING_ARG_DEFINE(u, "root", "remote host user");
// 密碼
STRING_ARG_DEFINE(P, "", "remote host password");

// 被上傳的檔案路徑
STRING_ARG_DEFINE(s, "", "the source file uploaded");
// 檔案上傳後存放的目錄路徑
STRING_ARG_DEFINE(d, "", "the directory to store");

// 連線逾時,單位為秒
INTEGER_ARG_DEFINE(uint16_t, t, 10, 1, 65535, "timeout seconds to remote host");

用一個結構體承載結果

因為要統計每台機器的成敗,所以需要一個簡單的結果結構,並為它多載入 operator<< 方便輸出:

// 結果資訊
struct ResultInfo
{
    bool success;    // true 表示執行成功
    std::string ip;  // 遠端 host 的 IP 位址
    uint32_t seconds; // 花費時長,精確到秒

    ResultInfo() : success(false), seconds(0) {}

    std::string str() const
    {
        std::string tag = success ? "SUCCESS" : "FAILURE";
        return mooon::utils::CStringUtils::format_string(
            "[%s %s]: %u seconds", ip.c_str(), tag.c_str(), seconds);
    }
};

inline std::ostream& operator<<(std::ostream& out, const struct ResultInfo& result)
{
    std::string tag = result.success ? "SUCCESS" : "FAILURE";
    out << "[" PRINT_COLOR_YELLOW << result.ip << PRINT_COLOR_NONE " "
        << tag << "] " << result.seconds << " seconds";
    return out;
}

主流程

整體結構可以拆成四段:參數解析與校驗、主機清單切分、逐台上傳、結果彙整。

int main(int argc, char* argv[])
{
    // 1. 解析命令列參數
    std::string errmsg;
    if (!mooon::utils::parse_arguments(argc, argv, &errmsg)) {
        fprintf(stderr, "parameter error: %s\n", errmsg.c_str());
        exit(1);
    }

    uint16_t port = mooon::argument::p->value();
    std::string source = mooon::argument::s->value();
    std::string directory = mooon::argument::d->value();
    std::string hosts = mooon::argument::h->value();
    std::string user = mooon::argument::u->value();
    std::string password = mooon::argument::P->value();

    mooon::utils::CStringUtils::trim(source);
    mooon::utils::CStringUtils::trim(directory);
    mooon::utils::CStringUtils::trim(hosts);
    mooon::utils::CStringUtils::trim(user);
    mooon::utils::CStringUtils::trim(password);

    // 2. 必填參數檢查
    if (source.empty())    { fprintf(stderr, "parameter[-s]'s value not set\n"); exit(1); }
    if (directory.empty()) { fprintf(stderr, "parameter[-d]'s value not set\n"); exit(1); }
    if (user.empty())      { fprintf(stderr, "parameter[-u]'s value not set\n"); exit(1); }
    if (password.empty())  { fprintf(stderr, "parameter[-P]'s value not set\n"); exit(1); }

    // -h 未提供時,退而求其次讀環境變數 HOSTS
    if (hosts.empty()) {
        const char* hosts_ = getenv("HOSTS");
        if (NULL == hosts_) {
            fprintf(stderr, "parameter[-h]'s value not set\n");
            exit(1);
        }
        hosts = hosts_;
        mooon::utils::CStringUtils::trim(hosts);
        if (hosts.empty()) {
            fprintf(stderr, "parameter[-h]'s value not set\n");
            exit(1);
        }
    }

    // 3. 切分主機清單
    std::vector<std::string> hosts_ip;
    int num_remote_hosts_ip =
        mooon::utils::CTokener::split(&hosts_ip, hosts, ",", true);
    if (0 == num_remote_hosts_ip) {
        fprintf(stderr, "parameter[-h] error\n");
        exit(1);
    }

    std::string remote_filepath =
        directory + std::string("/")
        + mooon::utils::CStringUtils::extract_filename(source);

    std::vector<struct ResultInfo> results(num_remote_hosts_ip);

    // 4. 逐台上傳
    for (int i = 0; i < num_remote_hosts_ip; ++i) {
        const std::string& remote_host_ip = hosts_ip[i];
        results[i].ip = remote_host_ip;
        results[i].success = false;

        fprintf(stdout, "[" PRINT_COLOR_YELLOW "%s" PRINT_COLOR_NONE "]\n",
                remote_host_ip.c_str());
        fprintf(stdout, PRINT_COLOR_GREEN);

        mooon::sys::CStopWatch stop_watch;
        try {
            int file_size = 0;
            mooon::net::CLibssh2 libssh2(remote_host_ip, port, user, password,
                                         mooon::argument::t->value());
            libssh2.upload(source, remote_filepath, &file_size);

            fprintf(stdout,
                    "[" PRINT_COLOR_YELLOW "%s" PRINT_COLOR_NONE
                    "] SUCCESS: %d bytes\n",
                    remote_host_ip.c_str(), file_size);
            results[i].success = true;
        }
        catch (mooon::sys::CSyscallException& ex) {
            fprintf(stderr, "[" PRINT_COLOR_RED "%s" PRINT_COLOR_NONE
                            "] failed: %s\n",
                    remote_host_ip.c_str(), ex.str().c_str());
        }
        catch (mooon::utils::CException& ex) {
            fprintf(stderr, "[" PRINT_COLOR_RED "%s" PRINT_COLOR_NONE
                            "] failed: %s\n",
                    remote_host_ip.c_str(), ex.str().c_str());
        }

        results[i].seconds = stop_watch.get_elapsed_microseconds() / 1000000;
        std::cout << std::endl;
    }

    // 5. 輸出總結
    std::cout << std::endl;
    std::cout << "================================" << std::endl;
    int num_success = 0;
    int num_failure = 0;
    for (std::vector<struct ResultInfo>::size_type i = 0; i < results.size(); ++i) {
        const struct ResultInfo& result_info = results[i];
        std::cout << result_info << std::endl;
        if (result_info.success) ++num_success;
        else                     ++num_failure;
    }
    std::cout << "SUCCESS: " << num_success
              << ", FAILURE: " << num_failure << std::endl;

    return 0;
}

設計上的幾個考量

這支工具的骨架其實很值得借鏡:

  • 單台失敗不影響其他:每台機器包在獨立的 try/catch 裡,一台上不去不會中斷整個流程。
  • 耗時可量測:用 CStopWatch 記錄每台的上傳秒數,方便比較哪台機器網路較慢。
  • 終端色彩輸出:成功綠色、失敗紅色,一眼就能掃出問題機器。
  • 參數可從環境變數補位:-h 沒給就讀 HOSTS,方便寫進 cron 或 CI 腳本。
  • 結果彙整:最後統一列出每台狀態與成功/失敗統計,利於快速定位。

若要進一步打磨,可以考慮改成多執行緒或 epoll 事件驅動的並行上傳,把大檔案在多台機器間的傳輸時間壓下來;另外密碼以明文字串傳入並非長久之計,改成支援 SSH 金鑰會安全得多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved