Sunday, 25 September 2016

Rust lang - initialize HashSet HashMap with constant members

Rust programming language is short of examples, how to initialize HashSet and HashMap variables with constant members. The following example demonstrates usage of seq macro rule for variables set, map1 and map2. Last th expression for the HashMap variable map3 demonstrates initialization with  constant elements without usage of macro 'seq!'.


/////////// main.rs ////////////////////
use std::collections::{HashMap,HashSet};

// from https://github.com/rust-lang/rust/issues/14726
macro_rules! seq {
    ($($x:expr),+) => {
        [$($x,)+].iter().map(|&x| x).collect()
    }
}

fn main() {
    let set: HashSet = seq!(1, 2, 3);
    let map1: HashMap = seq!((1, 10), (2, 20), (3, 30));
    let map2: HashMap<&'static str, &'static str> =
    seq!(("A", "1"),
        ("B", "2"),
        ("C", "3"));

    // demonstrate without macro
    let map3: HashMap<&'static str, &'static str> =
    [ ("A", "1"),
      ("B", "2"),
      ("C", "3") ]
      .iter().map(|&x| x).collect();
  
    println!("Set: {:?}", set);
    println!("Map: {:?}", map1);
    println!("Map: {:?}", map2);
    println!("Map: {:?}", map3);
}

Saturday, 3 September 2016

Automate ssh execution with password auth

Warning: The following command should be used only, operating on hosts not shared with other users, for example in internal test-labs. Otherwise the following command line might leak the password via ps process table to other users. 

In case  to automate ssh commands for example in test-lab and using password authentication instead of public-private authentication the following command options could be used with ssh (sshpass and -o options will work similar for scp).

sshpass -p${PASSWORD} ssh -c arcfour  -o StrictHostKeyChecking=no  -o UserKnownHostsFile=/dev/null -o ControlMaster=no -o LogLevel=ERROR -l ${USER} ${HOST_IP} ${COMMAND}

Explaining a few elements:
  • sshpass is a command feeding the password into ssh via stdin, emulating terminal input.
  • StrictHostKeyChecking=no will disable the lookup of host-key of the target host in local whitelist. In case of freshly added machines to test-lab, the ssh command will not wait for manual confirmation to trust the new remote host.

Using Ubuntu sshpass can be installed as:

sudo apt-get install sshpass