Created
March 14, 2020 13:13
-
-
Save BusyJay/bdf4169065e13564c87e62be15b30dad to your computer and use it in GitHub Desktop.
A script that restart failed ssh connection automatically.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::os::windows::process::CommandExt; | |
use std::process::{self, Command, Stdio}; | |
use std::time::{Duration, Instant}; | |
use std::{env, thread}; | |
fn main() { | |
let mut args: Vec<_> = env::args().collect(); | |
if let Some(idx) = args.iter().position(|x| x == "--detach") { | |
args.remove(idx); | |
if let Err(e) = Command::new(&args[0]) | |
.args(&args[1..]) | |
.creation_flags(0x0000_0200 | 0x0000_0008 | 0x0400_0000) | |
.spawn() | |
{ | |
eprintln!("Failed to run in detach mode: {:?}", e); | |
} | |
return; | |
} | |
let mut timer = Instant::now(); | |
loop { | |
let cmd = match Command::new("ssh") | |
.arg("-NT") | |
.args(&args[1..]) | |
.stderr(Stdio::piped()) | |
.creation_flags(0x0800_0000) | |
.spawn() | |
{ | |
Ok(c) => c, | |
Err(e) => { | |
eprintln!("Failed to spawn ssh {:?}: {}", args, e); | |
process::exit(1); | |
} | |
}; | |
let output = match cmd.wait_with_output() { | |
Ok(output) => output, | |
Err(e) => { | |
eprintln!("Failed to wait on ssh: {}", e); | |
process::exit(1); | |
} | |
}; | |
if output.status.code() != Some(255) { | |
return; | |
} | |
let elapsed = timer.elapsed(); | |
if elapsed < Duration::from_secs(5) { | |
thread::sleep(Duration::from_secs(5) - elapsed); | |
} | |
timer = Instant::now(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment