Monday, April 25, 2011

SSH - Passing Unix login passwords through shell scripts

Ref: http://nixcraft.com/shell-scripting/4489-ssh-passing-unix-login-passwords-through-shell-scripts.html

You need to create a login file as follows login.txt:
Code:
server1|user|password

A shell script as follows (sshlogin.sh):
Code:
#!/bin/bash
FILE=login.txt
CONNECT=sshlogin.exp
SERVERNAME=$1
MyServer=""
MyUser=""
MyPassword=""
exec 3<&0
exec 0<$FILE
while read line
do
        MyServer=$(echo $line | cut -d'|' -f1)
        MyUser=$(echo $line | cut -d'|' -f2)
        MyPassword=$(echo $line | cut -d'|' -f3)
        if [ "$SERVERNAME" == "$MyServer" ];
        then
           echo "Running ssh $MyUser@$MyServer..."
          $CONNECT $MyPassword $MyServer $MyUser
        fi
done
exec 0<&3
echo "$SERVERNAME not found in login.txt file"
Modified sshlogin.exp from Ssh login expect script to supply password

In order to use following script you need to install expect tool, use apt-get or yum command!

Code:
#!/usr/bin/expect -f
# Expect script to supply root/admin password for remote ssh server 
# and execute command.
# This script needs three argument to(s) connect to remote server:
# password = Password of remote UNIX server, for root user.
# ipaddr = IP Addreess of remote UNIX server, no hostname
# scriptname = Path to remote script which will execute on remote server
# For example:
#  ./sshlogin.exp password 192.168.1.11 who 
# ------------------------------------------------------------------------
# Copyright (c) 2004 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
# set Variables
set password [lrange $argv 0 0] 
set ipaddr [lrange $argv 1 1]   
set username [lrange $argv 2 2] 
set timeout -1   
# now connect to remote UNIX box (ipaddr) with given script to execute
spawn ssh $username@$ipaddr
match_max 100000
# Look for passwod prompt
expect "*?assword:*"
# Send password aka $password 
send -- "$password\r"
# send blank line (\r) to make sure we get back to gui
send -- "\r"
expect eof
To run script - set permissions
Code:
chmod +x sshlogin.sh
chmod +x  sshlogin.exp
Test it by connecting 127.0.0.1
Code:
./sshlogin 127.0.0.1

No comments:

Post a Comment