Rust 連續多年在 Stack Overflow 開發者調查中位居「最受喜愛的程式語言」榜首,其核心優勢在於:

  • 零成本抽象:高階語言特性不會帶來執行期效能損失
  • 記憶體安全:編譯期即能捕捉資料競爭和記憶體洩漏
  • 跨平台編譯:單一原始碼編譯為 Linux、macOS、Windows 原生二進位檔
  • 優秀的 CLI 生態:clap、tokio、serde 等 crate 讓 CLI 開發事半功倍

本文將帶你從零開始,建構一個名為 sysmgr 的 Linux 伺服器管理工具,涵蓋以下功能模組:

  1. 系統資訊收集(CPU、記憶體、磁碟、網路)
  2. 進程管理(列出、終止、監控)
  3. 日誌分析(過濾、統計、告警)
  4. 自動化運維(定時任務、批量操作)

1. 專案初始化與依賴配置

1.1 建立專案

BASH
cargo new sysmgr
cd sysmgr

1.2 配置 Cargo.toml

TOML
[package]
name = "sysmgr"
version = "0.1.0"
edition = "2021"

[dependencies]
# CLI 框架
clap = { version = "4.5", features = ["derive"] }
# 非同步執行時
tokio = { version = "1.40", features = ["full"] }
# 系統資訊
sysinfo = "0.31"
# 序列化
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# 終端 UI
crossterm = "0.28"
# 正則表達式
regex = "1.10"
# 時間處理
chrono = "0.4"
# 日誌
tracing = "0.1"
tracing-subscriber = "0.3"
# 錯誤處理
anyhow = "1.0"
thiserror = "1.0"

1.3 專案結構

sysmgr/
├── Cargo.toml
├── src/
│   ├── main.rs          # 入口與命令路由
│   ├── cli.rs           # CLI 引數定義
│   ├── commands/
│   │   ├── mod.rs
│   │   ├── info.rs      # 系統資訊
│   │   ├── process.rs   # 進程管理
│   │   ├── log.rs       # 日誌分析
│   │   └── cron.rs      # 自動化任務
│   └── utils/
│       ├── mod.rs
│       └── output.rs    # 輸出格式化

2. CLI 框架搭建

2.1 定義命令結構

使用 clap 的 derive 巨集定義命令:

RUST
// src/cli.rs
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "sysmgr")]
#[command(about = "Linux 伺服器管理工具", version)]
pub struct Cli {
    /// 啟用詳細輸出
    #[arg(short, long, global = true)]
    pub verbose: bool,

    /// 輸出格式
    #[arg(short, long, default_value = "table", global = true)]
    pub format: OutputFormat,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// 顯示系統資訊
    Info {
        /// 指定資訊類型
        #[arg(short, long)]
        section: Option<InfoSection>,
    },
    /// 進程管理
    Proc {
        #[command(subcommand)]
        action: ProcAction,
    },
    /// 日誌分析
    Log {
        /// 日誌檔案路徑
        #[arg(short, long)]
        file: String,
        /// 過濾關鍵字
        #[arg(short, long)]
        keyword: Option<String>,
        /// 統計錯誤級別
        #[arg(short, long)]
        stats: bool,
    },
    /// 自動化任務
    Cron {
        #[command(subcommand)]
        action: CronAction,
    },
}

#[derive(Clone, Debug, clap::ValueEnum)]
pub enum InfoSection {
    Cpu,
    Memory,
    Disk,
    Network,
    All,
}

#[derive(Clone, Debug, clap::ValueEnum)]
pub enum OutputFormat {
    Table,
    Json,
    Csv,
}

#[derive(Subcommand)]
pub enum ProcAction {
    /// 列出進程
    List {
        /// 按名稱過濾
        #[arg(short, long)]
        name: Option<String>,
        /// 按 CPU 使用率排序
        #[arg(long)]
        sort_by_cpu: bool,
    },
    /// 終止進程
    Kill {
        /// 進程 ID
        pid: u32,
        /// 強制終止
        #[arg(short, long)]
        force: bool,
    },
    /// 監控進程
    Watch {
        /// 進程名稱
        name: String,
        /// 重新整理間隔(秒)
        #[arg(short, long, default_value = "2")]
        interval: u64,
    },
}

#[derive(Subcommand)]
pub enum CronAction {
    /// 列出定時任務
    List,
    /// 新增定時任務
    Add {
        /// Cron 表達式
        schedule: String,
        /// 要執行的命令
        command: String,
    },
    /// 刪除定時任務
    Remove {
        /// 任務 ID
        id: u32,
    },
}

2.2 主入口

RUST
// src/main.rs
mod cli;
mod commands;
mod utils;

use anyhow::Result;
use clap::Parser;
use cli::{Cli, Commands};

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // 初始化日誌
    if cli.verbose {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();
    }

    match cli.command {
        Commands::Info { section } => {
            commands::info::run(section, &cli.format).await?;
        }
        Commands::Proc { action } => {
            commands::process::run(action, &cli.format).await?;
        }
        Commands::Log { file, keyword, stats } => {
            commands::log::run(&file, keyword.as_deref(), stats, &cli.format).await?;
        }
        Commands::Cron { action } => {
            commands::cron::run(action, &cli.format).await?;
        }
    }

    Ok(())
}

3. 系統資訊模組

3.1 實現系統資訊收集

RUST
// src/commands/info.rs
use crate::cli::{InfoSection, OutputFormat};
use anyhow::Result;
use sysinfo::System;
use serde::Serialize;

#[derive(Serialize)]
struct SystemInfo {
    hostname: String,
    os: String,
    kernel: String,
    uptime: u64,
    cpu_count: usize,
    cpu_usage: f32,
    total_memory: u64,
    used_memory: u64,
    total_swap: u64,
    used_swap: u64,
}

pub async fn run(section: Option<InfoSection>, format: &OutputFormat) -> Result<()> {
    let mut sys = System::new_all();
    sys.refresh_all();

    let section = section.unwrap_or(InfoSection::All);

    match section {
        InfoSection::Cpu => print_cpu_info(&sys, format),
        InfoSection::Memory => print_memory_info(&sys, format),
        InfoSection::Disk => print_disk_info(format),
        InfoSection::Network => print_network_info(format),
        InfoSection::All => {
            print_cpu_info(&sys, format);
            println!();
            print_memory_info(&sys, format);
            println!();
            print_disk_info(format);
            println!();
            print_network_info(format);
        }
    }

    Ok(())
}

fn print_cpu_info(sys: &System, format: &OutputFormat) {
    let cpu_count = sys.cpus().len();
    let cpu_usage: f32 = sys.cpus().iter().map(|c| c.cpu_usage()).sum::<f32>() / cpu_count as f32;

    match format {
        OutputFormat::Json => {
            let data = serde_json::json!({
                "cpu_count": cpu_count,
                "cpu_usage_percent": cpu_usage,
                "cpu_brand": sys.cpus().first().map(|c| c.brand()).unwrap_or("Unknown"),
            });
            println!("{}", serde_json::to_string_pretty(&data).unwrap());
        }
        _ => {
            println!("=== CPU 資訊 ===");
            println!("核心數: {}", cpu_count);
            println!("使用率: {:.1}%", cpu_usage);
            if let Some(cpu) = sys.cpus().first() {
                println!("型號: {}", cpu.brand());
            }
        }
    }
}

fn print_memory_info(sys: &System, format: &OutputFormat) {
    let total = sys.total_memory();
    let used = sys.used_memory();
    let total_swap = sys.total_swap();
    let used_swap = sys.used_swap();

    match format {
        OutputFormat::Json => {
            let data = serde_json::json!({
                "total_memory_mb": total / 1024 / 1024,
                "used_memory_mb": used / 1024 / 1024,
                "memory_usage_percent": (used as f64 / total as f64) * 100.0,
                "total_swap_mb": total_swap / 1024 / 1024,
                "used_swap_mb": used_swap / 1024 / 1024,
            });
            println!("{}", serde_json::to_string_pretty(&data).unwrap());
        }
        _ => {
            println!("=== 記憶體資訊 ===");
            println!("總記憶體: {} MB", total / 1024 / 1024);
            println!("已使用: {} MB ({:.1}%)", used / 1024 / 1024, (used as f64 / total as f64) * 100.0);
            println!("總交換空間: {} MB", total_swap / 1024 / 1024);
            println!("已使用交換: {} MB", used_swap / 1024 / 1024);
        }
    }
}

fn print_disk_info(format: &OutputFormat) {
    use sysinfo::Disks;

    let disks = Disks::new_with_refreshed_list();

    match format {
        OutputFormat::Json => {
            let data: Vec<_> = disks.iter().map(|d| {
                serde_json::json!({
                    "mount_point": d.mount_point().to_string_lossy(),
                    "filesystem": d.file_system().to_string_lossy(),
                    "total_gb": d.total_space() / 1024 / 1024 / 1024,
                    "available_gb": d.available_space() / 1024 / 1024 / 1024,
                })
            }).collect();
            println!("{}", serde_json::to_string_pretty(&data).unwrap());
        }
        _ => {
            println!("=== 磁碟資訊 ===");
            println!("{:<20} {:<10} {:<10} {:<10}", "掛載點", "檔案系統", "總容量", "可用");
            for disk in disks.iter() {
                println!("{:<20} {:<10} {:<8} GB  {:<6} GB",
                    disk.mount_point().to_string_lossy(),
                    disk.file_system().to_string_lossy(),
                    disk.total_space() / 1024 / 1024 / 1024,
                    disk.available_space() / 1024 / 1024 / 1024);
            }
        }
    }
}

fn print_network_info(format: &OutputFormat) {
    use sysinfo::Networks;

    let networks = Networks::new_with_refreshed_list();

    match format {
        OutputFormat::Json => {
            let data: Vec<_> = networks.iter().map(|(name, data)| {
                serde_json::json!({
                    "interface": name,
                    "received_mb": data.total_received() / 1024 / 1024,
                    "transmitted_mb": data.total_transmitted() / 1024 / 1024,
                })
            }).collect();
            println!("{}", serde_json::to_string_pretty(&data).unwrap());
        }
        _ => {
            println!("=== 網路資訊 ===");
            println!("{:<15} {:<15} {:<15}", "介面", "接收", "傳送");
            for (name, data) in networks.iter() {
                println!("{:<15} {:<10} MB  {:<10} MB",
                    name,
                    data.total_received() / 1024 / 1024,
                    data.total_transmitted() / 1024 / 1024);
            }
        }
    }
}

3.2 測試系統資訊模組

BASH
# 編譯
cargo build --release

# 查看所有系統資訊
./target/release/sysmgr info

# 只查看 CPU 資訊
./target/release/sysmgr info --section cpu

# JSON 格式輸出
./target/release/sysmgr info --format json

# 查看記憶體資訊(JSON)
./target/release/sysmgr info --section memory --format json

4. 進程管理模組

4.1 實現進程列表

RUST
// src/commands/process.rs
use crate::cli::{ProcAction, OutputFormat};
use anyhow::Result;
use sysinfo::{System, Process, Pid};
use serde::Serialize;

#[derive(Serialize)]
struct ProcessInfo {
    pid: u32,
    name: String,
    cpu_usage: f32,
    memory_mb: u64,
    status: String,
    user: String,
}

pub async fn run(action: ProcAction, format: &OutputFormat) -> Result<()> {
    match action {
        ProcAction::List { name, sort_by_cpu } => {
            list_processes(name, sort_by_cpu, format).await?;
        }
        ProcAction::Kill { pid, force } => {
            kill_process(pid, force).await?;
        }
        ProcAction::Watch { name, interval } => {
            watch_process(name, interval).await?;
        }
    }
    Ok(())
}

async fn list_processes(
    name_filter: Option<String>,
    sort_by_cpu: bool,
    format: &OutputFormat,
) -> Result<()> {
    let mut sys = System::new_all();
    sys.refresh_all();

    let mut processes: Vec<ProcessInfo> = sys.processes().iter().map(|(pid, proc_)| {
        ProcessInfo {
            pid: pid.as_u32(),
            name: proc_.name().to_string_lossy().to_string(),
            cpu_usage: proc_.cpu_usage(),
            memory_mb: proc_.memory() / 1024 / 1024,
            status: format!("{:?}", proc_.status()),
            user: proc_.user_id().map(|u| u.to_string()).unwrap_or_default(),
        }
    }).collect();

    // 過濾
    if let Some(name) = name_filter {
        processes.retain(|p| p.name.to_lowercase().contains(&name.to_lowercase()));
    }

    // 排序
    if sort_by_cpu {
        processes.sort_by(|a, b| b.cpu_usage.partial_cmp(&a.cpu_usage).unwrap());
    } else {
        processes.sort_by_key(|p| p.pid);
    }

    // 輸出
    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&processes)?);
        }
        OutputFormat::Csv => {
            println!("PID,NAME,CPU%,MEMORY_MB,STATUS,USER");
            for p in &processes {
                println!("{},{},{:.1},{},{},{}", p.pid, p.name, p.cpu_usage, p.memory_mb, p.status, p.user);
            }
        }
        OutputFormat::Table => {
            println!("{:<8} {:<25} {:<8} {:<10} {:<10} {}", "PID", "名稱", "CPU%", "記憶體(MB)", "狀態", "使用者");
            println!("{}", "-".repeat(80));
            for p in processes.iter().take(50) {
                println!("{:<8} {:<25} {:<8.1} {:<10} {:<10} {}",
                    p.pid, truncate(&p.name, 24), p.cpu_usage, p.memory_mb, p.status, p.user);
            }
            println!("\n共 {} 個進程", processes.len());
        }
    }

    Ok(())
}

fn truncate(s: &str, max_len: usize) -> String {
    if s.len() > max_len {
        format!("{}...", &s[..max_len - 3])
    } else {
        s.to_string()
    }
}

async fn kill_process(pid: u32, force: bool) -> Result<()> {
    let mut sys = System::new();
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);

    let pid = Pid::from(pid as usize);

    if let Some(process) = sys.process(pid) {
        if force {
            process.kill();
            println!("已強制終止進程 {} ({})", pid, process.name().to_string_lossy());
        } else {
            // 發送 SIGTERM
            #[cfg(unix)]
            {
                use std::process::Command;
                Command::new("kill").arg(pid.to_string()).output()?;
                println!("已發送 TERM 訊號至進程 {} ({})", pid, process.name().to_string_lossy());
            }
        }
    } else {
        println!("找不到進程 {}", pid);
    }

    Ok(())
}

async fn watch_process(name: String, interval: u64) -> Result<()> {
    use std::time::Duration;

    println!("監控進程: {} (每 {} 秒重新整理,按 Ctrl+C 結束)", name, interval);

    loop {
        let mut sys = System::new();
        sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);

        let matched: Vec<_> = sys.processes().iter()
            .filter(|(_, p)| p.name().to_string_lossy().to_lowercase().contains(&name.to_lowercase()))
            .collect();

        // 清除螢幕
        print!("\x1B[2J\x1B[1;1H");
        println!("=== 進程監控: {} ===", name);
        println!("時間: {}", chrono::Local::now().format("%Y-%m-%d %H:%M:%S"));
        println!();

        if matched.is_empty() {
            println!("未找到匹配 '{}' 的進程", name);
        } else {
            println!("{:<8} {:<25} {:<8} {:<10}", "PID", "名稱", "CPU%", "記憶體(MB)");
            println!("{}", "-".repeat(55));
            for (pid, proc_) in &matched {
                println!("{:<8} {:<25} {:<8.1} {:<10}",
                    pid, proc_.name().to_string_lossy(),
                    proc_.cpu_usage(),
                    proc_.memory() / 1024 / 1024);
            }
        }

        tokio::time::sleep(Duration::from_secs(interval)).await;
    }
}

4.2 測試進程管理

BASH
# 列出所有進程
./target/release/sysmgr proc list

# 按 CPU 使用率排序
./target/release/sysmgr proc list --sort-by-cpu

# 過濾特定進程
./target/release/sysmgr proc list --name nginx

# JSON 格式輸出
./target/release/sysmgr proc list --format json

# 終止進程
./target/release/sysmgr proc kill 1234

# 強制終止
./target/release/sysmgr proc kill 1234 --force

# 監控進程
./target/release/sysmgr proc watch nginx --interval 5

5. 日誌分析模組

5.1 實現日誌分析

RUST
// src/commands/log.rs
use crate::cli::OutputFormat;
use anyhow::Result;
use regex::Regex;
use serde::Serialize;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};

#[derive(Serialize)]
struct LogStats {
    total_lines: usize,
    error_count: usize,
    warn_count: usize,
    info_count: usize,
    debug_count: usize,
    errors_per_hour: HashMap<String, usize>,
}

pub async fn run(
    file: &str,
    keyword: Option<&str>,
    stats: bool,
    format: &OutputFormat,
) -> Result<()> {
    let file = File::open(file)?;
    let reader = BufReader::new(file);

    if stats {
        analyze_stats(reader, format)?;
    } else if let Some(kw) = keyword {
        filter_lines(reader, kw, format)?;
    } else {
        println!("請指定 --keyword 或 --stats 引數");
    }

    Ok(())
}

fn analyze_stats(reader: BufReader<File>, format: &OutputFormat) -> Result<()> {
    let mut stats = LogStats {
        total_lines: 0,
        error_count: 0,
        warn_count: 0,
        info_count: 0,
        debug_count: 0,
        errors_per_hour: HashMap::new(),
    };

    // 正則:匹配時間戳和日誌級別
    let re = Regex::new(r"(?P<timestamp>\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}).*(?P<level>ERROR|WARN|INFO|DEBUG)")?;

    for line in reader.lines() {
        let line = line?;
        stats.total_lines += 1;

        if let Some(caps) = re.captures(&line) {
            let level = caps.name("level").unwrap().as_str();
            let timestamp = caps.name("timestamp").unwrap().as_str();

            match level {
                "ERROR" => {
                    stats.error_count += 1;
                    // 提取小時
                    if let Some(hour) = timestamp.get(11..13) {
                        *stats.errors_per_hour.entry(hour.to_string()).or_insert(0) += 1;
                    }
                }
                "WARN" => stats.warn_count += 1,
                "INFO" => stats.info_count += 1,
                "DEBUG" => stats.debug_count += 1,
                _ => {}
            }
        }
    }

    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&stats)?);
        }
        _ => {
            println!("=== 日誌統計 ===");
            println!("總行數: {}", stats.total_lines);
            println!("ERROR: {}", stats.error_count);
            println!("WARN: {}", stats.warn_count);
            println!("INFO: {}", stats.info_count);
            println!("DEBUG: {}", stats.debug_count);

            if !stats.errors_per_hour.is_empty() {
                println!("\n=== 每小時錯誤分布 ===");
                let mut hours: Vec<_> = stats.errors_per_hour.iter().collect();
                hours.sort_by_key(|(h, _)| h.clone());
                for (hour, count) in hours {
                    println!("{}:00 - {} 個錯誤", hour, count);
                }
            }
        }
    }

    Ok(())
}

fn filter_lines(reader: BufReader<File>, keyword: &str, format: &OutputFormat) -> Result<()> {
    let re = Regex::new(&format!("(?i){}", regex::escape(keyword)))?;
    let mut count = 0;

    for line in reader.lines() {
        let line = line?;
        if re.is_match(&line) {
            count += 1;
            match format {
                OutputFormat::Json => {
                    println!("{}", serde_json::json!({"line": count, "content": line}));
                }
                _ => {
                    println!("{}", line);
                }
            }
        }
    }

    eprintln!("\n共找到 {} 行匹配", count);
    Ok(())
}

5.2 測試日誌分析

BASH
# 統計日誌
./target/release/sysmgr log --file /var/log/syslog --stats

# JSON 格式統計
./target/release/sysmgr log --file /var/log/syslog --stats --format json

# 過濾關鍵字
./target/release/sysmgr log --file /var/log/syslog --keyword "error"

# 過濾並輸出 JSON
./target/release/sysmgr log --file /var/log/syslog --keyword "failed" --format json

6. 自動化任務模組

6.1 實現 Cron 管理

RUST
// src/commands/cron.rs
use crate::cli::{CronAction, OutputFormat};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

#[derive(Serialize, Deserialize, Debug)]
struct CronJob {
    id: u32,
    schedule: String,
    command: String,
    enabled: bool,
}

#[derive(Serialize, Deserialize, Debug, Default)]
struct CronConfig {
    jobs: Vec<CronJob>,
}

fn config_path() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(home).join(".sysmgr").join("cron.json")
}

fn load_config() -> Result<CronConfig> {
    let path = config_path();
    if !path.exists() {
        return Ok(CronConfig::default());
    }
    let content = fs::read_to_string(path)?;
    Ok(serde_json::from_str(&content)?)
}

fn save_config(config: &CronConfig) -> Result<()> {
    let path = config_path();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, serde_json::to_string_pretty(config)?)?;
    Ok(())
}

pub async fn run(action: CronAction, format: &OutputFormat) -> Result<()> {
    match action {
        CronAction::List => {
            let config = load_config()?;
            match format {
                OutputFormat::Json => {
                    println!("{}", serde_json::to_string_pretty(&config.jobs)?);
                }
                _ => {
                    println!("{:<5} {:<20} {:<40} {:<8}", "ID", "排程", "命令", "狀態");
                    println!("{}", "-".repeat(75));
                    for job in &config.jobs {
                        let status = if job.enabled { "啟用" } else { "停用" };
                        println!("{:<5} {:<20} {:<40} {:<8}", job.id, job.schedule, job.command, status);
                    }
                }
            }
        }
        CronAction::Add { schedule, command } => {
            let mut config = load_config()?;
            let new_id = config.jobs.iter().map(|j| j.id).max().unwrap_or(0) + 1;
            config.jobs.push(CronJob {
                id: new_id,
                schedule,
                command,
                enabled: true,
            });
            save_config(&config)?;
            println!("已新增任務 ID: {}", new_id);
        }
        CronAction::Remove { id } => {
            let mut config = load_config()?;
            let initial_len = config.jobs.len();
            config.jobs.retain(|j| j.id != id);
            if config.jobs.len() == initial_len {
                println!("找不到任務 ID: {}", id);
            } else {
                save_config(&config)?;
                println!("已刪除任務 ID: {}", id);
            }
        }
    }
    Ok(())
}

6.2 測試自動化任務

BASH
# 新增定時任務
./target/release/sysmgr cron add "0 */6 * * *" "/usr/bin/backup.sh"

# 列出所有任務
./target/release/sysmgr cron list

# JSON 格式列出
./target/release/sysmgr cron list --format json

# 刪除任務
./target/release/sysmgr cron remove 1

7. 進階功能

7.1 跨平台編譯

BASH
# 編譯為 Linux x86_64
cargo build --release --target x86_64-unknown-linux-gnu

# 編譯為 Linux ARM64
cargo build --release --target aarch64-unknown-linux-gnu

# 編譯為 macOS
cargo build --release --target x86_64-apple-darwin

# 編譯為 Windows
cargo build --release --target x86_64-pc-windows-gnu

7.2 靜態連結(避免 glibc 版本問題)

BASH
# 使用 musl 進行靜態連結
rustup target add x86_64-unknown-linux-musl
cargo build --release --target x86_64-unknown-linux-musl

# 生成的二進位檔可以在任何 Linux 發行版上運行
ls -lh target/x86_64-unknown-linux-musl/release/sysmgr

7.3 打包與分發

BASH
# 使用 cargo-deb 打包為 Debian 套件
cargo install cargo-deb
cargo deb

# 使用 cargo-generate-rpm 打包為 RPM 套件
cargo install cargo-generate-rpm
cargo generate-rpm

# 生成 tar.gz 分发包
tar -czvf sysmgr-0.1.0-linux-x86_64.tar.gz \
    -C target/release sysmgr

8. 效能最佳化

8.1 編譯最佳化

TOML
# Cargo.toml
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"
strip = true

8.2 執行期最佳化

  • 使用 mimalloc 替代預設分配器
RUST
// src/main.rs
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
  • 非同步 I/O 處理大量日誌
RUST
use tokio::io::AsyncBufReadExt;

async fn process_large_log(path: &str) -> Result<()> {
    let file = tokio::fs::File::open(path).await?;
    let reader = tokio::io::BufReader::new(file);
    let mut lines = reader.lines();

    while let Some(line) = lines.next_line().await? {
        // 處理每一行
    }
    Ok(())
}

9. 總結

本文帶你使用 Rust 建構了一個功能完整的 Linux 伺服器管理 CLI 工具,涵蓋了:

  1. CLI 框架搭建:使用 clap 定義清晰的命令結構
  2. 系統資訊收集:CPU、記憶體、磁碟、網路的即時監控
  3. 進程管理:列出、過濾、終止、監控進程
  4. 日誌分析:過濾、統計、錯誤分布分析
  5. 自動化任務:Cron 任務的 CRUD 管理
  6. 跨平台編譯:單一原始碼編譯為多平台二進位檔
  7. 效能最佳化:靜態連結、LTO、mimalloc 等

Rust 的優勢在伺服器管理工具開發中體現得淋漓盡致:

  • 安全性:編譯期即能避免資料競爭和記憶體問題
  • 效能:與 C/C++ 相當的執行效率
  • 可移植性:交叉編譯輕鬆部署到不同架構
  • 生態系:豐富的 crate 加速開發

相關資源: - sysinfo 文件 - clap 文件 - tokio 文件 - Rust CLI 應用指南