Rust在Linux系统自动化运维中的价值与落地路径
一、为什么选择Rust做Linux自动化运维
二、典型场景与最小示例
示例代码片段(节选)
use tokio::process::Command;
use tokio::time::{timeout, Duration};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let servers = vec!["host1".to_string(), "host2".to_string()];
let mut tasks = Vec::new();
for s in servers {
let task = tokio::spawn(async move {
let mut cmd = Command::new("ssh");
cmd.arg(&s).arg("uptime");
match timeout(Duration::from_secs(10), cmd.output()).await {
Ok(Ok(out)) => Ok((s, String::from_utf8_lossy(&out.stdout).trim().to_string())),
Ok(Err(e)) => Err((s, format!("exec error: {}", e))),
Err(_) => Err((s, "timeout".to_string())),
}
});
tasks.push(task);
}
for t in tasks {
match t.await {
Ok(Ok((s, out))) => println!("{}: {}", s, out),
Ok(Err((s, e))) => eprintln!("{}: {}", s, e),
Err(e) => eprintln!("join error: {}", e),
}
}
Ok(())
}
use std::fs::File;
use std::io::{BufRead, BufReader};
fn read_lines<P>(p: P) -> std::io::Result<impl Iterator<Item = String>>
where
P: AsRef<std::path::Path>,
{
let f = File::open(p)?;
Ok(BufReader::new(f).lines().filter_map(|l| l.ok()))
}
fn main() {
if let Ok(lines) = read_lines("/proc/stat") {
for line in lines {
if line.starts_with("cpu ") {
let parts: Vec<&str> = line.split_whitespace().collect();
let user: u64 = parts[1].parse().unwrap();
let nice: u64 = parts[2].parse().unwrap();
let system: u64
let idle: u64 = parts[4].parse().unwrap();
println!("CPU User={} Nice={} System={} Idle={}", user, nice, system, idle);
break;
}
}
}
}
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use std::convert::Infallible;
async fn handle(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("OK")))
}
#[tokio::main]
async fn main() {
let make_svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handle)) });
let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr).serve(make_svc);
if let Err(e) = server.await { eprintln!("server error: {}", e); }
}
以上示例展示了并发编排、系统采集与轻量服务三类常见运维能力的骨架实现。
三、工程化与交付实践
四、进阶场景与生态
五、落地路线图