1 Commits

Author SHA1 Message Date
f56cf593a3 Format Rust code using rustfmt 2025-04-08 17:39:53 +00:00
4 changed files with 99 additions and 161 deletions

View File

@ -104,7 +104,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
allowUpdates: true allowUpdates: true
body: "Release rexec ${{ env.VERSION }}. Static build for Linux (x86_64), Windows (x86_64) и MacOS (arm64)." body: "Релиз rexec версии ${{ env.VERSION }}. Статические сборки для Linux (x86_64), Windows (x86_64) и MacOS (arm64)."
upload: upload:
name: Upload Release Assets name: Upload Release Assets

2
Cargo.lock generated
View File

@ -1111,7 +1111,7 @@ checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78"
[[package]] [[package]]
name = "rexec" name = "rexec"
version = "1.2.1" version = "1.1.0"
dependencies = [ dependencies = [
"brace-expand", "brace-expand",
"clap 4.3.4", "clap 4.3.4",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "rexec" name = "rexec"
version = "1.2.1" version = "1.2.0"
readme = "https://github.com/house-of-vanity/rexec#readme" readme = "https://github.com/house-of-vanity/rexec#readme"
edition = "2021" edition = "2021"
description = "Parallel SSH executor" description = "Parallel SSH executor"

View File

@ -13,7 +13,7 @@ use colored::*;
use dns_lookup::lookup_host; use dns_lookup::lookup_host;
use env_logger::Env; use env_logger::Env;
use itertools::Itertools; use itertools::Itertools;
use log::{error, info, warn}; use log::{error, info};
use massh::{MasshClient, MasshConfig, MasshHostConfig, SshAuth}; use massh::{MasshClient, MasshConfig, MasshHostConfig, SshAuth};
use question::{Answer, Question}; use question::{Answer, Question};
use rayon::prelude::*; use rayon::prelude::*;
@ -185,7 +185,7 @@ fn main() {
all_hosts all_hosts
}; };
// Dedup hosts from known_hosts file but preserve original order // Dedup hosts from known_hosts file
let matched_hosts: Vec<_> = hosts.into_iter().unique().collect(); let matched_hosts: Vec<_> = hosts.into_iter().unique().collect();
// Build MasshHostConfig hostnames list // Build MasshHostConfig hostnames list
@ -199,66 +199,36 @@ fn main() {
}); });
} }
// Store hosts with their indices to preserve order
let mut host_with_indices: Vec<(Host, usize)> = Vec::new();
for (idx, host) in matched_hosts.iter().enumerate() {
host_with_indices.push((host.clone(), idx));
}
info!("Matched hosts:"); info!("Matched hosts:");
let resolved_ips = Arc::new(Mutex::new(Vec::<(String, IpAddr)>::new()));
// Do DNS resolution in parallel but store results for ordered display later matched_hosts
let resolved_ips_with_indices = Arc::new(Mutex::new(Vec::<(String, IpAddr, usize)>::new()));
host_with_indices
.par_iter() .par_iter()
.for_each(|(host, idx)| match lookup_host(&host.name) { .for_each(|host| match lookup_host(&host.name) {
Ok(ips) if !ips.is_empty() => { Ok(ips) if !ips.is_empty() => {
let ip = ips[0]; let ip = ips[0];
let mut results = resolved_ips_with_indices.lock().unwrap();
results.push((host.name.clone(), ip, *idx)); info!("{} [{}]", &host.name, ip);
let mut results = resolved_ips.lock().unwrap();
results.push((host.name.clone(), ip));
} }
Ok(_) => { Ok(_) => {
let mut results = resolved_ips_with_indices.lock().unwrap(); error!("DNS resolved, but IP not found: {}", &host.name.red());
results.push((
host.name.clone(),
IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
*idx,
));
} }
Err(_) => { Err(_) => {
let mut results = resolved_ips_with_indices.lock().unwrap(); error!("DNS resolve failed: {}", &host.name.red());
results.push((
host.name.clone(),
IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
*idx,
));
} }
}); });
// Sort by original index to ensure hosts are displayed in order let mut hosts_and_ips: HashMap<IpAddr, String> = HashMap::new();
let mut resolved_hosts = resolved_ips_with_indices.lock().unwrap().clone();
resolved_hosts.sort_by_key(|(_, _, idx)| *idx);
// Now print the hosts in the correct order
for (hostname, ip, _) in &resolved_hosts {
if ip.is_unspecified() {
error!("DNS resolve failed: {}", hostname.red());
} else {
info!("{} [{}]", hostname, ip);
}
}
// Create massh_hosts in the correct order
let mut hosts_and_ips: HashMap<IpAddr, (String, usize)> = HashMap::new();
let mut massh_hosts: Vec<MasshHostConfig> = Vec::new(); let mut massh_hosts: Vec<MasshHostConfig> = Vec::new();
for (hostname, ip, idx) in resolved_hosts { if let Ok(results) = resolved_ips.lock() {
// Skip hosts that couldn't be resolved for (hostname, ip) in results.iter() {
if !ip.is_unspecified() { hosts_and_ips.insert(*ip, hostname.clone());
hosts_and_ips.insert(ip, (hostname.clone(), idx));
massh_hosts.push(MasshHostConfig { massh_hosts.push(MasshHostConfig {
addr: ip, addr: *ip,
auth: None, auth: None,
port: None, port: None,
user: None, user: None,
@ -266,15 +236,23 @@ fn main() {
} }
} }
// Process hosts in batches to maintain order // Build MasshConfig using massh_hosts vector
let batch_size = args.parallel as usize; let config = MasshConfig {
default_auth: SshAuth::Agent,
default_port: 22,
default_user: args.username,
threads: args.parallel as u64,
timeout: 0,
hosts: massh_hosts,
};
let massh = MasshClient::from(&config);
// Ask for confirmation // Ask for confirmation
if !massh_hosts.is_empty() if config.hosts.len() != 0
&& (args.noconfirm && (args.noconfirm == true
|| match Question::new(&*format!( || match Question::new(&*format!(
"Continue on following {} servers?", "Continue on following {} servers?",
&massh_hosts.len() &config.hosts.len()
)) ))
.confirm() .confirm()
{ {
@ -283,41 +261,11 @@ fn main() {
_ => unreachable!(), _ => unreachable!(),
}) })
{ {
info!("Run command on {} servers.", &massh_hosts.len()); info!("Run command on {} servers.", &config.hosts.len());
let mut processed = 0; // Run a command on all the configured hosts.
// Receive the result of the command for each host and print its output.
while processed < massh_hosts.len() { let rx = massh.execute(args.command);
let end = std::cmp::min(processed + batch_size, massh_hosts.len());
// Create a new config and vector for this batch
let mut batch_hosts = Vec::new();
for host in &massh_hosts[processed..end] {
batch_hosts.push(MasshHostConfig {
addr: host.addr,
auth: None,
port: None,
user: None,
});
}
// Create a new MasshClient for this batch
let batch_config = MasshConfig {
default_auth: SshAuth::Agent,
default_port: 22,
default_user: args.username.clone(),
threads: batch_hosts.len() as u64,
timeout: 0,
hosts: batch_hosts,
};
let batch_massh = MasshClient::from(&batch_config);
// Run commands on this batch
let rx = batch_massh.execute(args.command.clone());
// Collect all results from this batch before moving to the next
let mut batch_results = Vec::new();
while let Ok((host, result)) = rx.recv() { while let Ok((host, result)) = rx.recv() {
let ip: String = host.split('@').collect::<Vec<_>>()[1] let ip: String = host.split('@').collect::<Vec<_>>()[1]
@ -325,21 +273,16 @@ fn main() {
.collect::<Vec<_>>()[0] .collect::<Vec<_>>()[0]
.to_string(); .to_string();
let ip = ip.parse::<IpAddr>().unwrap(); let ip = ip.parse::<IpAddr>().unwrap();
println!(
if let Some((hostname, idx)) = hosts_and_ips.get(&ip) { "\n{}",
batch_results.push((hostname.clone(), ip, result, *idx)); hosts_and_ips
} else { .get(&ip)
error!("Unexpected IP address in result: {}", ip); .unwrap_or(&"Couldn't parse IP".to_string())
} .to_string()
} .yellow()
.bold()
// Sort the batch results by index to ensure they're displayed in order .to_string()
batch_results.sort_by_key(|(_, _, _, idx)| *idx); );
// Display the results
for (hostname, _ip, result, _) in batch_results {
println!("\n{}", hostname.yellow().bold().to_string());
let output = match result { let output = match result {
Ok(output) => output, Ok(output) => output,
Err(e) => { Err(e) => {
@ -347,17 +290,15 @@ fn main() {
continue; continue;
} }
}; };
let code_string = if output.exit_status == 0 { let code_string = if output.exit_status == 0 {
format!("{}", output.exit_status.to_string().green()) format!("{}", output.exit_status.to_string().green())
} else { } else {
format!("{}", output.exit_status.to_string().red()) format!("{}", output.exit_status.to_string().red())
}; };
println!( println!(
"{}", "{}",
format!( format!(
"Exit code [{}] / stdout {} bytes / stderr {} bytes", "Exit code [{}] | std out/err [{}/{}] bytes",
code_string, code_string,
output.stdout.len(), output.stdout.len(),
output.stderr.len() output.stderr.len()
@ -395,9 +336,6 @@ fn main() {
} }
} }
} }
processed = end;
}
} else { } else {
warn!("Stopped"); warn!("Stopped");
} }