Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a password to ssh in pure bash

Tags:

linux

bash

pipe

I want to pass a password to ssh using a bash script (Yes, I know that there are ssh keys that I could use, but this is not what I intend).

I found some solutions that were using expect but since it is not a standard bash tool I am wondering if I can do this using pipes.

Can someone explain to me, why exactly something like this:

echo "password\n" | ssh somehost.com 

or

ssh somehost.com <(echo "password\n") 

doesn't work? Is there any possibility to make it work? Maybe executing ssh as a different process, obtaining its PID and then sending a string directly to it?

like image 979
Liberat0r Avatar asked Jun 27 '14 14:06

Liberat0r


People also ask

Can I pass password in SSH command?

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

How do I prompt a password in bash?

#!/bin/bash echo "Enter Username : " # read username and echo username in terminal read username echo "Enter Password : " # password is read in silent mode i.e. it will # show nothing instead of password. read -s password echo echo "Your password is read in silent mode."

Can we pass password in SCP command?

The SCP command; on its own, is not sufficient enough to accommodate password authentication under a one-line command usage and therefore leads to a successive password prompt for the OS user to enter the required login passcode.


1 Answers

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

sshpass -f <(printf '%s\n' your_password) ssh user@hostname 

instead of using sshpass -p your_password. As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

BTW, a little explanation for the <(command) syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe

like image 178
CS Pei Avatar answered Sep 19 '22 07:09

CS Pei