xonecas.ioDon't click! Sean Caetano Martin Sign in
cast / src / vm / ssh.rs 52 lines1.2 kB Raw
1use crate::vm::files;
2use std::io::Write;
3use std::process::{Child, Command, Stdio};
4
5pub fn spawn(port: u16, script: &str) -> std::io::Result<Child> {
6    let mut child = Command::new("ssh")
7        .args(["-i"])
8        .arg(files::key())
9        .args(["-p", &port.to_string()])
10        .args([
11            "-o",
12            "StrictHostKeyChecking=no",
13            "-o",
14            "UserKnownHostsFile=/dev/null",
15        ])
16        .args([
17            "-o",
18            "LogLevel=ERROR",
19            "-o",
20            "BatchMode=yes",
21            "-o",
22            "ConnectTimeout=5",
23        ])
24        .args(["cast@127.0.0.1", "bash", "-s"])
25        .stdin(Stdio::piped())
26        .stdout(Stdio::piped())
27        .stderr(Stdio::piped())
28        .spawn()?;
29    child
30        .stdin
31        .take()
32        .map(|mut s| s.write_all(script.as_bytes()));
33    Ok(child)
34}
35
36pub fn quote(s: &str) -> String {
37    format!("'{}'", s.replace('\'', "'\\''"))
38}
39
40pub fn run(port: u16, script: &str) -> bool {
41    spawn(port, script)
42        .and_then(|c| c.wait_with_output())
43        .is_ok_and(|o| o.status.success())
44}
45
46#[cfg(test)]
47mod tests {
48    #[test]
49    fn quote_survives_single_quotes() {
50        assert_eq!(super::quote("O'Neil"), r"'O'\''Neil'");
51    }
52}