[download]

local/bin/vbox-nat

   1 #!/bin/bash
   2 
   3 f=~/.ssh/vbox
   4 rm -f $f
   5 
   6 declare -A ports=(
   7      [ssh]=2222
   8     [http]=8080
   9 )
  10 
  11 vboxmanage list runningvms |
  12 while IFS=\" read _ name id; do
  13     name=${name,,}
  14     name=${name// /-}
  15 
  16     cat <<SSH >> $f
  17 Host $name
  18     HostName localhost
  19     Port ${ports[ssh]}
  20     LogLevel fatal
  21     StrictHostKeyChecking no
  22     UserKnownHostsFile /dev/null
  23 SSH
  24 
  25     vboxmanage showvminfo --machinereadable $id |
  26     awk -F '[",]' '/Forwarding/ { print $2 }'   |
  27     xargs -I % vboxmanage controlvm $id natpf1 delete %
  28 
  29     for i in ${!ports[@]}; do
  30         host=${ports[$i]}
  31         virt=${ports[$i]:0:2}
  32 
  33         echo "$HOSTNAME:$host <- $name:$virt"
  34         vboxmanage controlvm $id natpf1 "$i,tcp,,$host,,$virt"
  35 
  36         (( ports[$i]++ ))
  37     done
  38 done