If you ever need to provide a password for SSH login inside a bash script or a shell command, to avoid being asked a password when SSH keys are not used, it can be done with usage of
expect command, or
Expect is a program that “talks” to other interactive programs according to a script.
Lets say you want to SSH to a server and run a remote command,
ls for instance, with a command like this:
ssh [email protected] "ls -lh file"
If you are not using SSH keys, you will be prompted a password, and will need to enter it manually.
If you want to avoid entering a password, and have it inputted to login prompt automatically you can use
Provide SSH password inside a script.
Expect reads cmdfile for a list of commands to execute. Expect may also be invoked implicitly on systems which support the #! notation by marking the script executable, and making the first line in your script:
Example of a script which runs a remote command over SSH, with password being provided inside a script.
spawn ssh [email protected] "ls /file"
Running a SSH command with provided password inside a one-liner, can be done using
expect -c and then putting the commands inside single quotes.
The -c flag prefaces a command to be executed before any in the script. The command should be quoted to prevent being broken up by the shell. This option may be used multiple times. Multiple commands may be executed with a single -c by separating them with semicolons.
Example of a one-line command:
expect -c 'spawn ssh [email protected] "ls -lh file"; expect "assword:"; send "mypassword\r"; interact'
SSH password prompt can also be bypassed by connecting with
sshpass command, which is available in EPEL repo in CentOS
To install sshpass, first make sure you have EPEL repo on your server.
You can install EPEL with
yum -y install epel-release
Install sshpass with
yum -y install sshpass
You can then connect to remote server with
sshpass using a command similar to this:
sshpass -p 'password' ssh [email protected]
If you have never connected to the server before, you will probably not get connected to remote server due to host key checking.
To bypass host key checking use
-o StrictHostKeyChecking=no option:
sshpass -p 'password' ssh -o StrictHostKeyChecking=no [email protected]
Find jobs for SysAdmins with Jooble