I Have created a shell script as given below.This script will login to a remote server as a normal user then switch to root user for creating a directory.The script is as given below.
ssh -t qbadmin@10.3.2.0 '
su root -c "
echo \"Give Directory name :\";
read dir;
mkdir \$dir;
";
'
Here the script will ask Password for normal user first.Then again it will ask for root Password.How could I automate this using expect command.I want to supply the password automatically for the root user only.I think it can be done with expect.
Please do help me.
13 Answers
I don't see an accepted answer years later so I will also add something that may be helpful to others. My situation had nothing to do with SSH, but using spawn expect in the following way I was able to get it working.
expect -c " spawn myProc expect \"Do you wish to continue with XYZ? (y/N)\" { send \"n\r\" exp_continue }
"Hope this helps.
A better/easier way than using expect is SSHPASS, which sends a password through with an SSH request:
sshpass -p <PASSWORD> ssh <USER>@<SERVER> <SSH Command>PASSWORD is the password to be entered when prompted, USER is the username, SERVER is the server IP Address (eg. 10.8.100.100) and SSH Command is the command you want to execute.
For your example:
sshpass -p <PASSWORD> ssh qbadmin@10.3.2.0 mkdir <full path for new dir>To install SSHPASS:
sudo apt-get install sshpassIf you are wanting the SSH session to remain afterwards than you can use expect with the following,
#!/bin/bash
##Enter Username and Password Details:
userName=<UserName>
password=<Password>
expect -c " spawn ssh ${userName}@10.8.100.100 ##put your own IP here expect "password: " ##or whatever password prompt you get send "$password\r" expect -re "Last Login: " ##or whatever the end of your welcome message is send "su -i" expect "password for <UserName>" send "$password\r"
"This will leave the root access logged in, however until the script sends a return statement it will hold control until you hit Ctrl+c. But this should answer your question.
1If you want to pass only the root password, you have to
- either configure a password-less login into the user account, e.g. using public key authentication and an ssh agent on the client side,
- or configure the server (i.e. to allow login as root, and then do
ssh -t root@10.3.2.0 …