Sunday, May 28, 2017

auto ssh login shell script

automatically ssh login script below.

1. directory tree

% tree
.
├── auto_login.sh # main file
├── login_client.sh # script to login client host
└── login_server.sh # script to login server host
% cat auto_login.sh
#!/bin/sh

 auto_ssh() {
     host=$1
     id=$2
     pass=$3

      expect -c "
      set timeout 10
      spawn ssh ${id}@${host}
      #expect \"Are you sure you want to continue connecting (yes/no)?\"
      #send \"yes\n\"
      expect \"${id}@${host}'s password:\"
      send \"$pass\n\"
      expect \"# \"
      send \"cd /opt/work/ ; ls\n\"
      interact
      "
 }
remove "#" if you have not exchange ssh key with target host yet.
% cat login_server.sh
#!/bin/sh

# execute main script
. ./auto_login.sh
# auto login 'host address' 'username' 'password'
auto_ssh '192.168.111.223' 'vagrant' 'vagrant'
% cat login_client.sh
#!/bin/sh

# execute main script
. ./auto_login.sh
# auto login 'host address' 'username' 'password'
auto_ssh '192.168.111.224' 'vagrant' 'vagrant'

2. execution

% bash login_server.sh
spawn ssh vagrant@192.168.111.223
vagrant@192.168.111.223's password:
Last login: Sat May 27 17:19:45 2017 from 192.168.111.1
Welcome to your Vagrant-built virtual machine.
[vagrant@server ~]$