[ Level 2 ] Connect pool for ssh.

If you want to use the concept "connection pool" for ssh, you could try the following sample.
#!/bin/bash
#
# You might need to modify sshd_config with the following attributes:
#
# MaxStartup 200
# MaxSessions 200
#
[ "$1" == "-d" ] && set -vx && shift
control_master="$1" && [ "$control_master" != "false" ] && control_master=true
username="$2" && [ -z $username ] && username=stanley
remote_host="$3" && [ -z $remote_host ] && remote_host=127.0.0.1
cmd1="$4"&& [ -z $cmd1 ] && cmd1=ls
control_master_option=""
client_cmd="/tmp/a.sh"

buildControlMaster() {
  if $control_master
  then
    ssh -N -o "ControlMaster auto" -o "ControlPath ~/.ssh/master-$username@$remote_host" $username@$remote_host &
  fi
}

createClientCmd() {
  mkdir -p /tmp/add
  rm /tmp/add/* $client_cmd
  if $control_master
  then
    control_master_option="-o \"ControlMaster auto\" -o \"ControlPath ~/.ssh/master-$username@$remote_host\""
  fi
  echo "ssh $control_master_option $username@$remote_host $cmd1 >/tmp/add/\$\$.txt 2>&1" >> $client_cmd
}

test() {
for i in `seq 1 100`
do
  bash $client_cmd &
done
wait ## wait for all child process finished!
}

buildControlMaster
createClientCmd
time test

$ ./sshControlMaster.sh true ## if open fail, ssh would create isolate session.
channel 67: open failed: administratively prohibited: open failed
channel 69: open failed: administratively prohibited: open failed
channel 86: open failed: administratively prohibited: open failed
channel 88: open failed: administratively prohibited: open failed
channel 72: open failed: administratively prohibited: open failed
channel 18: open failed: administratively prohibited: open failed
...
channel 37: open failed: administratively prohibited: open failed
channel 1: open failed: administratively prohibited: open failed
channel 5: open failed: administratively prohibited: open failed
channel 10: open failed: administratively prohibited: open failed
channel 6: open failed: administratively prohibited: open failed
channel 11: open failed: administratively prohibited: open failed

real 0m5.176s
user 0m0.424s
sys 0m0.232s
$ ./sshControlMaster.sh false ## always create isolate session.

real 0m8.926s
user 0m0.544s
sys 0m0.288s
$ 

You will still get the performance enhancement even though some open session fail and create isolate one.

Wish this helps.

regards,
Stanley Huang

Comments

Popular posts from this blog

[Level 2] Shell Interactive With Zenity Episode 5 -- list

[Level 2] iif in Python