Automatically enter SSH password with script
Solution 1
First you need to install sshpass.
- Ubuntu/Debian:
apt-get install sshpass
- Fedora/CentOS:
yum install sshpass
- Arch:
pacman -S sshpass
Example:
sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM
Custom port example:
sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM:2400
Notes:
-
sshpass
can also read a password from a file when the-f
flag is passed.- Using
-f
prevents the password from being visible if theps
command is executed. - The file that the password is stored in should have secure permissions.
- Using
Solution 2
After looking for an answer to the question for months, I finally found a better solution: writing a simple script.
#!/usr/bin/expect
set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]
eval spawn $cmd
expect "password:"
send "$password\r";
interact
Put it to /usr/bin/exp
, So you can use:
exp <password> ssh <anything>
exp <password> scp <anysrc> <anydst>
Done!
Solution 3
Use public key authentication: https://help.ubuntu.com/community/SSH/OpenSSH/Keys
In the source host run this only once:
ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost
That's all, after that you'll be able to do ssh without password.
Solution 4
You could use an expects script. I have not written one in quite some time but it should look like below. You will need to head the script with #!/usr/bin/expect
#!/usr/bin/expect -f
spawn ssh HOSTNAME
expect "login:"
send "username\r"
expect "Password:"
send "password\r"
interact
Solution 5
Variant I
sshpass -p PASSWORD ssh USER@SERVER
Variant II
#!/usr/bin/expect -f
spawn ssh USERNAME@SERVER "touch /home/user/ssh_example"
expect "assword:"
send "PASSWORD\r"
interact
Related videos on Youtube
user1467855
Updated on March 24, 2022Comments
-
user1467855 over 2 years
I need to create a script that automatically inputs a password to OpenSSH
ssh
client.Let's say I need to SSH into
myname@somehost
with the passworda1234b
.I've already tried...
#~/bin/myssh.sh ssh myname@somehost a1234b
...but this does not work.
How can I get this functionality into a script?
-
user1467855 almost 12 yearsI see. But I am REQUIRED to ssh with password. This is because, "I" may have the script on a thumb drive and need to run it from any computer; while not disabling the need for password.
-
user1467855 almost 12 yearsI did as you suggested but get the following errors:
/bin/myssh.sh: 2: spawn: not found /bin/myssh.sh: 3: expect: not found /bin/myssh.sh: 4: send: not found /bin/myssh.sh: 5: expect: not found /bin/myssh.sh: 6: send: not found
-
Kimvais almost 12 yearsYou can also store the private key on the said thumb drive.
-
Aaron McDaid almost 12 years@user1467855, I think you need to better explain your requirements. Nobody is suggesting that you have an unsecure network. In the public-key approach, it would still be possible for users to log in with the password. But you would copy the private key onto your thumb drive, which means the thumb drive would be the only thing that can log in without a password.
-
Lipongo almost 12 yearsThanks Aaron for modifying my answer to be correct. You may need to run the below command to find the correct path to put in for expect.
which expect
-
glenn jackman almost 12 yearsYou can also use this shebang line:
#!/usr/bin/env expect
-
Karel Bílek about 11 yearsUnfortunately, I am in OP situation, because the sysadmin disallows authentication by rsa/dsa keys and requires passwors. What are you gonna do.
-
Karel Bílek about 11 yearsI added
interact
to the end so the ssh session is actually interactive -
Per Mejdal Rasmussen almost 11 yearsThis is much better than using Expect.
-
Aaron Digulla over 10 years-1 for the huge security risk of keeping a plain text password in a script.
-
Diego Woitasen over 10 yearsI agree with @KarelBílek. The other options requires more skill, Python coding, expect. There is no easy option I think.
-
Alexander Taylor over 9 yearsjust be aware that while sshpass blocks your password from commands like
ps -aux
, you shouldn't normally run commands by typing your password because other users on the same computer may be able to see the password by runningps -aux
. if practical, you also want to use public key authentication instead, as mentioned in the other answer. this allows you to separate authentication info from your script so you can share your script with others worry-free, and later decide to enable encryption on your ~/.ssh folder without also encrypting your script. -
Andy almost 9 yearsUnfortunately this isn't working for me on a server with a custom ssh port...why can't ssh just give us the option to insert the password in the command line?
-
3pic almost 9 yearsIs there something equivalent for
cryptsetup luksAddKey /path/to/key
, which promptsEnter a passphrase:
? -
zstewart almost 9 yearsWhile I would normally COMPLETELY agree about using keyauth, my school's IT department is dumb and doesn't have keyauth enabled on their servers.
-
RemiZOffAlex over 8 yearsNo. sshpass is not ssh.
SYNOPSIS sshpass [-ffilename|-dnum|-ppassword|-e] [options] command arguments
-
Adama over 8 yearsThanks for demonstrating "ssh-copy-id". I was adding the IDs with the cumbersome way cat ~/.ssh/id_rsa.pub | ssh user@host "cat - >> ~/.ssh/authorized_keys". This is so much easier!
-
user2082382 about 8 yearsThis answer should get more votes imo, it is a great wrapper. Just tried a few common operations like rsyncing with various flags and remote command execution and it worked every time. Added to my toolbox of useful scripts, Thanks @damn_c!
-
Kade about 8 yearsA quick note to anyone who found this question from Googling like I did: Try this first, if you run into some sort of signing error, try using
ssh-add
on your machine. That fixed my issue. -
dmmfll about 8 yearsI used this to get around having to type in a password every time I ran an Ansible script on a new server instance that did not yet have my key in ~/.ssh/authorized_keys.
exp <password> ansible-playbook set-user-remove-password-login.yml -k
To my great pleasure, the password was typed in when ansible prompted me with the SSH password: -
Aaron McDaid almost 8 years@AaronDigulla, how is this any less secure than any alternatives, for example the private key is also readable? Perhaps we should suggest that the script be readable only by the user?
-
Aaron Digulla almost 8 years@AaronMcDaid Making the script only readable to a user makes it better. But root can still read it and most attackers try to get root access. Private keys are useless without passwords to unlock them. Which creates a loop since OP wanted to know how to avoid entering the password. But if he puts this script on a thumb drive, he's adding a lot of risk because thumb drives get lost or can be stolen and then, someone has access.
-
Ye Lwin Soe almost 8 yearsfor custom port to work add "-p port-number" at the end of command
-
Parthian Shot almost 8 yearsDownvoted because this doesn't even try to answer the actual question asked.
-
Parthian Shot almost 8 yearsWorth noting that there's still a brief window of time during which the password can be nabbed from
/proc
. It's still better to not usesshpass
in this way. If possible, you want to pass passwords via files with strong permissions or (better yet) environment variables. -
Junior Mayhé over 7 yearsIn order to run sshpass in Linux CentOS you must
yum -y install epel-release
and thenyum -y install sshpass
-
RemiZOffAlex over 7 yearsIn this context of this data can be ignored
-
Yan Foto over 7 yearsI think this article is just being sarcastic!
-
Zelphir Kaltstahl over 7 years@abbotto How to do this with
ssh-add
instead ofssh
, in order to add a key? -
clearlight over 7 yearsMaybe it hasn't gotten more upvotes because people didn't expect it?
-
PierreE over 7 yearsThe reason why this is IMO not a very good answer is because the password is written in the script which is by far the least secure method...
-
Ben L. about 7 years@PierreE the password is specified on the command line, not in the script.
-
Daniel Persson almost 7 yearsThe password will be visible by anyone who runs ps on the machine.
-
Ciro Santilli OurBigBook.com almost 7 years"assword" is amazing :-)
-
Martin Prikryl almost 7 yearsWhat does this answer show on top of existing answers? + Never ever suggest anyone to use
StrictHostKeyChecking=no
without explaining the consequences. -
iSebbeYT over 6 yearsLets say you entered the wrong password using this script. Then Terminal will ask for another password a few times before your script can continue. Is there some way the script can abort entering a password if it was not correct?
-
Ian over 6 yearsI've added an answer with a more secure usage of
sshpass
. -
filip over 6 yearsGood enough solution for Jenkins pipelines.
-
Ian about 6 yearsnote to self: update script to use
trap
to prevent ctrl-C from leaking theSSHPASS
variable -
Josh about 6 years
sshpass
has an option,-f
, to read the password from a file. Thus, it won't be visible when usingps
, and if the file has appropriate permissions in one's own home directory, it should be safe. -
magor about 6 years@Per Mejdal Rasmussen maybe its better than using
expect
but as long that you don't know what is the exact situation of the OP, you cannot state that as a fact. Not everyone is living in the same environment as you are used to. For my use case expect is the solution, all the other 'better' solutions won't work in my case. -
Mehrdad Mirreza almost 6 yearsThis still prompts for the first login and cannot be used in a script!
-
allenyllee almost 6 yearsNote that you can't add option
-f
to autossh in this combination, becausewhen used with autossh, ssh will be *unable* to ask for passwords or passphrases.
harding.motd.ca/autossh/README.txt also superuser.com/questions/1278583/… -
Winter almost 6 yearsNot available on Windows git bash
-
Kirkland almost 6 yearsWhile I know this is an old post it's worth noting that the Variant II method would leave the password given to the session vulnerable in the bash history, making it highly inadvisable.
-
Mike Partridge over 5 yearsI found that
PreferredAuthentications=keyboard-interactive
didn't work, but replacing it withPreferredAuthentications=password
worked. -
Martin Prikryl over 5 yearsWhat does this show on top of the existing answers? Particularly those by damn_c, Lipongo or RemiZOffAlex and others...
-
Shivam Mehrotra over 5 yearsscript execution along with ssh #!/usr/bin/expect set pass [lindex $argv 1] set host [lindex $argv 0] spawn ssh -t root@$host sh /tmp/anyscript.sh expect "*assword: " send "$pass\n"; interact"
-
Craig Hicks over 5 yearsUsing passwordless keys (you didn't even mention that is what happens when just pressing enter in response to all prompts) has the disadvantage that a major source of security leaks is accidentally backing up and exporting unencrypted key files. Obviously sometimes some critical files have to live unencrypted - one way to handle that is keep those under etc and back etc up separately from main backup.
-
JCGB about 5 years"I'm behind a firewall so I'm not worried about spoofed ssh keys". A firewall does exactly nothing in this case. The HostKeyCheck is so you can verify the host on the other end is not a trojan Host. I.e. one that's just pretending to be where you want to connect to. If you connect to an unknown host, and do something sensitive, like write a file that has credentials or a token or enter a password, that information is now effectively public knowledge. You being behind a firewall is irrelevant.
-
Akhil Surapuram almost 5 yearswhy we need to pass StrictHostKeyChecking=no
-
Vladimir over 4 yearsMac OS is fun: trying
brew install sshpass
and got "Error: No available formula with the name "sshpass". We won't add sshpass because it makes it too easy for novice SSH users to ruin SSH's security." -
abbotto over 4 years@Vladmir For Mac OS you could try installing the unofficial package.
https://gist.github.com/arunoda/7790979#installing-with-homebrew
-
shodanshok over 4 yearsThis is an extremely useful solution for non-standard ssh servers which don't work with
sshpass
-
Martin Prikryl over 3 yearsNote that
.bash_profile
is quite often word-readable. So putting your password there is not a good idea. -
alx over 3 yearsI'm running
ssh
inside the remote machine again, with the same password. Right now I'm exportingSSHPASS
into the remote machine withexport SSHPASS=$SSHPASS
. Is there a safer way? To provide some context, I ssh into a cluster of machines, set up ssh keys, and then distribute them into other computers in the cluster. All of that runs from a script in a single computer. So I need 2 levels ofssh
. -
Ian over 3 yearsThis solution is only for the case where you don't have prior access to the machine to set up a key-based login. I would look at key forwarding dev.to/levivm/…
-
Erhard Dinhobl over 3 yearsI am trying now to get this working since 10-12 hours. No luck: For another user its working but not for the one I need. Is there any solution on providing a pass in a script?
-
SMshrimant over 3 yearsThank you @MartinPrikryl for addressing the issue, I have updated the note at the end so anyone who is using this solution, is also aware that password is easily readable.
-
eadmaster over 3 yearsi've added
log_user 0
to skip some unrequired logs -
Martin Prikryl over 3 yearsWhat does this show what other existing answers don't already? + Never suggest anyone to use
StrictHostKeyChecking=no
without explaining the security consequences. -
Martin Prikryl over 3 yearsI do not see any "quick and dirty" in the OP.
-
vlsd over 3 yearsThis seems to work at first, but since the
-M0
flag disables monitoring my connection fails after a while withoutautossh
realizing it; if I omit the flag then it also works until the connection fails, at which point my password is rejected by the server -
Manuel Romeiro about 3 yearsFor automatic script, don't forget the option "-no-antispoof" or the console will waiting with a message "Access granted. Press Return to begin session.". The command to be executed should be placed at the end: plink your_username@yourhost -pw your_password -no-antispoof your_command
-
Zang322 about 3 yearsI tried
sshpass -p "nvidia" ssh -o StrictHostKeyChecking=no nvidia@"$x" "kill `pgrep ads2`"
. However it didn't work. ?? -
dns over 2 yearsThe best answer for Windows user so far.
-
nhed over 2 yearssarcastic maybe? but this fine if trying to automate against systems with their default
admin
if you are in the process of provisioning them -
AzizSM over 2 yearsssshpass work well on scp too
-
RmccurdyDOTcom over 2 yearsNo this does not require 'expect' or 'sshpass' ... this being one of the ONLY ways to ssh with just native Debian install ... so this works without root @nhed Also note 90% of these are just using non native programing, expect or sshpass all being the same 'answer' mine is the best ... so there ;P
-
nhed over 2 yearsI agree that it does not require
expect
/sshpass
. @RmccurdyDOTcom didn't notice you linked your pwn article, so yeah you would know if you were sarcastic or not - but on that front I was referring to the prior comment by Yan. Personally I would try to abstain from clear text and opt for ssh keys but there is the issue of bootstrapping virgin systems - where i think this is a good option if seeding the right public keys is not an option.