Files
rexec/src/main.rs

250 lines
7.3 KiB
Rust
Raw Normal View History

2023-06-20 01:41:07 +03:00
use brace_expand::brace_expand;
2023-06-16 14:31:16 +03:00
use colored::*;
use dialoguer::Confirm;
2023-06-15 16:30:49 +03:00
use dns_lookup::lookup_host;
2023-06-16 14:31:16 +03:00
use env_logger::Env;
2023-06-16 17:38:56 +03:00
use itertools::Itertools;
2023-06-16 14:31:16 +03:00
use log::{error, info};
use massh::{MasshClient, MasshConfig, MasshHostConfig, SshAuth};
2023-06-20 02:56:44 +03:00
use regex::Regex;
use std::collections::HashMap;
2023-06-16 14:31:16 +03:00
use std::fs::read_to_string;
2023-06-18 13:18:52 +03:00
use std::hash::Hash;
2023-06-16 14:31:16 +03:00
use std::net::IpAddr;
2023-06-20 02:46:02 +03:00
2023-06-20 01:41:07 +03:00
use std::process;
2023-06-16 14:31:16 +03:00
#[macro_use]
extern crate log;
use clap::Parser;
2023-06-20 01:41:07 +03:00
// Define args
2023-06-16 14:31:16 +03:00
#[derive(Parser, Debug)]
2023-06-20 01:41:07 +03:00
#[command(author = "AB ab@hexor.ru", version, about = "Parallel SSH executor in Rust", long_about = None)]
2023-06-16 14:31:16 +03:00
struct Args {
#[arg(short, long, default_value_t = whoami::username())]
username: String,
2023-06-20 01:41:07 +03:00
#[arg(short, long, help = "Use known_hosts to build servers list")]
known_hosts: bool,
#[arg(short, long, help = "Expression to build server list")]
expression: String,
2023-06-16 14:31:16 +03:00
2023-06-18 13:18:52 +03:00
#[arg(short, long, help = "Command to execute on servers")]
2023-06-16 14:31:16 +03:00
command: String,
2023-06-16 17:38:56 +03:00
2023-06-18 13:18:52 +03:00
#[arg(long, default_value_t = false, help = "Show exit code ONLY")]
2023-06-16 17:38:56 +03:00
code: bool,
2023-06-20 01:41:07 +03:00
#[arg(
short = 'f',
long,
default_value_t = false,
help = "Don't ask for confirmation"
)]
2023-06-18 13:18:52 +03:00
noconfirm: bool,
2023-06-16 17:38:56 +03:00
#[arg(short, long, default_value_t = 100)]
parallel: i32,
2023-06-16 14:31:16 +03:00
}
2023-06-16 17:38:56 +03:00
// Represent line from known_hosts file
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
2023-06-20 01:41:07 +03:00
struct Host {
2023-06-16 14:31:16 +03:00
name: String,
ip: Option<IpAddr>,
}
2023-06-16 17:38:56 +03:00
// Read known_hosts file
2023-06-20 01:41:07 +03:00
fn read_known_hosts() -> Vec<Host> {
let mut result: Vec<Host> = Vec::new();
2023-06-16 14:31:16 +03:00
for line in read_to_string(format!("/home/{}/.ssh/known_hosts", whoami::username()))
.unwrap()
.lines()
{
let line = line.split(" ").collect::<Vec<&str>>();
let hostname = line[0];
2023-06-20 01:41:07 +03:00
result.push(Host {
name: hostname.to_string(),
ip: None,
})
}
result
}
2023-07-03 15:19:29 +03:00
fn expand_string(string: String) -> Vec<Host> {
let mut result: Vec<String> = Vec::new();
let mut _result: Vec<String> = Vec::new();
let mut hosts: Vec<Host> = Vec::new();
if let Some(open_bracket_index) = string.find('[') {
if let Some(close_bracket_index) = string.find(']') {
let prefix = &string[..open_bracket_index];
let range = &string[open_bracket_index + 1..close_bracket_index];
let postfix = &string[close_bracket_index + 1..];
let parts: Vec<&str> = range.split(':').collect();
if parts.len() == 2 {
if let Ok(start) = parts[0].parse::<u32>() {
if let Ok(end) = parts[1].parse::<u32>() {
for num in start..=end {
_result.push(format!("{}{}{}", prefix, num, postfix));
}
}
}
}
}
} else {
_result.push(String::from(string));
}
2023-06-20 01:41:07 +03:00
2023-07-03 15:19:29 +03:00
for string in _result {
if let Some(open_brace_index) = string.find('{') {
if let Some(close_brace_index) = string.find('}') {
let prefix = &string[..open_brace_index];
let list = &string[open_brace_index + 1..close_brace_index];
let postfix = &string[close_brace_index + 1..];
let items: Vec<&str> = list.split(',').collect();
for item in items {
result.push(format!("{}{}{}", prefix, item, postfix));
}
}
} else {
result.push(String::from(string));
}
}
for hostname in result {
hosts.push(Host {
2023-06-16 14:31:16 +03:00
name: hostname.to_string(),
ip: None,
})
}
2023-07-03 15:19:29 +03:00
hosts
2023-06-16 14:31:16 +03:00
}
2023-06-15 17:58:54 +03:00
2023-06-15 16:30:49 +03:00
fn main() {
2023-06-16 14:31:16 +03:00
env_logger::Builder::from_env(Env::default().default_filter_or("info"))
.format_timestamp(None)
.format_target(false)
.init();
let args = Args::parse();
2023-06-20 01:41:07 +03:00
let hosts = if args.known_hosts {
info!("Using ~/.ssh/known_hosts to build server list.");
let known_hosts = read_known_hosts();
// Build regex
let re = match Regex::new(&args.expression) {
Ok(result) => result,
Err(e) => {
error!("Error parsing regex. {}", e);
process::exit(1);
}
};
// match hostnames from known_hosts to regex
known_hosts
.into_iter()
.filter(|r| re.is_match(&r.name.clone()))
.collect()
} else {
info!("Using string expansion to build server list.");
2023-07-03 15:19:29 +03:00
expand_string(args.expression)
2023-06-20 01:41:07 +03:00
};
2023-06-16 14:31:16 +03:00
2023-06-16 17:38:56 +03:00
// Dedup hosts from known_hosts file
2023-06-20 02:46:02 +03:00
let matched_hosts: Vec<_> = hosts.into_iter().unique().collect();
2023-06-16 17:38:56 +03:00
// Build MasshHostConfig hostnames list
2023-06-16 14:31:16 +03:00
let mut massh_hosts: Vec<MasshHostConfig> = vec![];
2023-06-18 13:18:52 +03:00
let mut hosts_and_ips: HashMap<IpAddr, String> = HashMap::new();
2023-06-16 14:31:16 +03:00
info!("Matched hosts:");
for host in matched_hosts.iter() {
let ip = match lookup_host(&host.name) {
Ok(ip) => ip[0],
Err(_) => {
2023-06-20 01:41:07 +03:00
error!("{} couldn't be resolved.", &host.name.red());
2023-06-16 14:31:16 +03:00
continue;
}
};
info!("{} [{}]", &host.name, ip);
2023-06-18 13:18:52 +03:00
hosts_and_ips.insert(ip, host.name.clone());
2023-06-16 14:31:16 +03:00
massh_hosts.push(MasshHostConfig {
addr: ip,
auth: None,
port: None,
user: None,
})
}
2023-06-16 17:38:56 +03:00
// Build MasshConfig using massh_hosts vector
2023-06-15 16:30:49 +03:00
let config = MasshConfig {
default_auth: SshAuth::Agent,
default_port: 22,
2023-06-18 13:18:52 +03:00
default_user: args.username,
2023-06-16 17:38:56 +03:00
threads: args.parallel as u64,
2023-06-15 16:30:49 +03:00
timeout: 0,
2023-06-16 14:31:16 +03:00
hosts: massh_hosts,
2023-06-15 16:30:49 +03:00
};
let massh = MasshClient::from(&config);
2023-06-16 17:38:56 +03:00
// Ask for confirmation
2023-06-18 13:18:52 +03:00
if args.noconfirm == true
|| Confirm::new()
.with_prompt(format!(
"Continue on following {} servers?",
&config.hosts.len()
))
.interact()
.unwrap()
2023-06-16 14:31:16 +03:00
{
info!("\n");
info!("Run command on {} servers.", &config.hosts.len());
2023-06-16 17:38:56 +03:00
info!("\n");
// Run a command on all the configured hosts.
// Receive the result of the command for each host and print its output.
2023-06-16 14:31:16 +03:00
let rx = massh.execute(args.command);
2023-06-15 16:30:49 +03:00
2023-06-16 14:31:16 +03:00
while let Ok((host, result)) = rx.recv() {
2023-06-18 13:18:52 +03:00
let ip: String = host.split('@').collect::<Vec<_>>()[1]
.split(':')
2023-06-20 01:41:07 +03:00
.collect::<Vec<_>>()[0]
.to_string();
2023-06-18 13:18:52 +03:00
let ip = ip.parse::<IpAddr>().unwrap();
2023-06-20 01:41:07 +03:00
info!(
"{}",
hosts_and_ips
.get(&ip)
2023-06-20 02:56:44 +03:00
.unwrap_or(&"Couldn't parse IP".to_string())
.to_string()
.yellow()
.bold()
.to_string()
2023-06-20 01:41:07 +03:00
);
let output = match result {
Ok(output) => output,
Err(e) => {
error!("Can't access server: {}", e);
2023-06-20 02:56:44 +03:00
continue;
2023-06-20 01:41:07 +03:00
}
};
2023-06-16 14:31:16 +03:00
if output.exit_status == 0 {
2023-06-20 02:44:54 +03:00
println!("Code {}", output.exit_status);
2023-06-16 14:31:16 +03:00
} else {
2023-06-20 02:44:54 +03:00
error!("Code {}", output.exit_status);
2023-06-16 14:31:16 +03:00
};
2023-06-16 17:38:56 +03:00
if !args.code {
2023-06-20 02:44:54 +03:00
println!("STDOUT:\n{}", String::from_utf8(output.stdout).unwrap());
println!("STDERR:\n{}", String::from_utf8(output.stderr).unwrap());
2023-06-16 17:38:56 +03:00
}
2023-06-16 14:31:16 +03:00
}
} else {
warn!("Stopped");
2023-06-15 16:30:49 +03:00
}
}