0

My Requirement is to login into the remote machine and make some folders for this I am planning to take username and pwd as input from the user and try to make automate shell script.

1.)I used the following code to ssh into the machine and give the expected pwd to login into this machine.

DSADMINPWD=dsadminpwd
PWD=pwd
/usr/bin/expect<<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no <username>@<remotemachineurl>
expect "password"
send "$PWD\n"
EOD

The above works fine. But while doing su dsadmin after this. I am unable to go inside that user from the previously taken password.

2.) I have to change user like su dsadmin from inside this machine. Also there is a password for dsadmin. But it is not working properly.

    DSADMINPWD=dsadminpwd
    PWD=pwd
    /usr/bin/expect<<EOD
    spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no <username>@<remotemachineurl>
    expect "password"
    send "$PWD\n"
    EOD

    su dsadmin
    <like to make some folders in dsadmin directory>
    exit... 

After doing su dsadmin it will come as

   bash-3.00$

No sign of password or anything here.

From the above it is not working

Could you please suggest if anything is possible to make su after ssh with password in automated script. Any suggestions would be highly appreciated.

Thanks!

user1709952
  • 169
  • 2
  • 7
  • 21

1 Answers1

0

I used the expect command long time ago and it worked smoothly with the su command even if it was launched from a ssh console.

Here some examples that maybe you can find useful.

First of all the bash script:

#!/bin/bash

exec 1> stdoutfile
exec 2> stderrfile

./yourexpectscript  YOUR_REMOTEIP_HERE userexample passwordexample

Secondly the expect script:

#!/usr/bin/expect --

send_user "connecting to remote server\n"

set server [lindex $argv 0]
set user [lindex $argv 1]
set pass [lindex $argv 2]
set dsadminpass "dsadminpwd"

spawn ssh $user@$server
expect "password: "
send "$pass\n"

expect {
    "> " { }
    "$ " { }
    "# " { }
}

#example command in ssh shell
send "ls -lah\n"

expect {
    "> " { }
    "$ " { }
    "# " { }
    default { }
}

#su command
send "su - dsadmin\n"

expect {
    "Password: " { }
}

send "$dsadminpass\n"

expect {
    "> " { }
    "$ " { }
    "# " { }
    default { }
}

#example command in dsadmin shell
send "ls -lah\n"

#login out dsdamin shell
send "exit\n"

expect {
    "> " { }
    "$ " { }
    "# " { }
    default { }
}

#login out ssh connection
send "exit\n"

send_user "connection to remote server finished\n"
Gooseman
  • 2,102
  • 17
  • 16