how to use expect with bash
Solution 1
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 [email protected] mkdir <full path for new dir>
To install SSHPASS:
sudo apt-get install sshpass
If 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.
Solution 2
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.
Solution 3
If 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 [email protected] …
Related videos on Youtube
Uvais Ibrahim
Enthusiastic in Linux/Unix. Trying to learn the soul of Linux. :)
Updated on September 18, 2022Comments
-
Uvais Ibrahim over 1 year
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 [email protected] '
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 withexpect
.Please do help me.
-
prophecy201 about 11 yearsWhat about authorized keys? help.ubuntu.com/community/SSH/OpenSSH/Keys More security!
-
-
Eric Hodonsky over 6 yearsResurrect: Are your double quotes inside supposed to be escaped?