Automatically enter SSH password with script

706,715

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 the ps command is executed.
    • The file that the password is stored in should have secure permissions.

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
Share:
706,715

Related videos on Youtube

user1467855
Author by

user1467855

Updated on March 24, 2022

Comments

  • user1467855
    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 password a1234b.

    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
    user1467855 almost 12 years
    I 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
    user1467855 almost 12 years
    I 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
    Kimvais almost 12 years
    You can also store the private key on the said thumb drive.
  • Aaron McDaid
    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
    Lipongo almost 12 years
    Thanks 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
    glenn jackman almost 12 years
    You can also use this shebang line: #!/usr/bin/env expect
  • Karel Bílek
    Karel Bílek about 11 years
    Unfortunately, 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
    Karel Bílek about 11 years
    I added interact to the end so the ssh session is actually interactive
  • Per Mejdal Rasmussen
    Per Mejdal Rasmussen almost 11 years
    This is much better than using Expect.
  • Aaron Digulla
    Aaron Digulla over 10 years
    -1 for the huge security risk of keeping a plain text password in a script.
  • Diego Woitasen
    Diego Woitasen over 10 years
    I agree with @KarelBílek. The other options requires more skill, Python coding, expect. There is no easy option I think.
  • Alexander Taylor
    Alexander Taylor over 9 years
    just 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 running ps -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
    Andy almost 9 years
    Unfortunately 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
    3pic almost 9 years
    Is there something equivalent for cryptsetup luksAddKey /path/to/key, which prompts Enter a passphrase: ?
  • zstewart
    zstewart almost 9 years
    While 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
    RemiZOffAlex over 8 years
    No. sshpass is not ssh. SYNOPSIS sshpass [-ffilename|-dnum|-ppassword|-e] [options] command arguments
  • Adama
    Adama over 8 years
    Thanks 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
    user2082382 about 8 years
    This 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
    Kade about 8 years
    A 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
    dmmfll about 8 years
    I 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
    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
    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
    Ye Lwin Soe almost 8 years
    for custom port to work add "-p port-number" at the end of command
  • Parthian Shot
    Parthian Shot almost 8 years
    Downvoted because this doesn't even try to answer the actual question asked.
  • Parthian Shot
    Parthian Shot almost 8 years
    Worth 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 use sshpass in this way. If possible, you want to pass passwords via files with strong permissions or (better yet) environment variables.
  • Junior Mayhé
    Junior Mayhé over 7 years
    In order to run sshpass in Linux CentOS you must yum -y install epel-release and then yum -y install sshpass
  • RemiZOffAlex
    RemiZOffAlex over 7 years
    In this context of this data can be ignored
  • Yan Foto
    Yan Foto over 7 years
    I think this article is just being sarcastic!
  • Zelphir Kaltstahl
    Zelphir Kaltstahl over 7 years
    @abbotto How to do this with ssh-add instead of ssh, in order to add a key?
  • clearlight
    clearlight over 7 years
    Maybe it hasn't gotten more upvotes because people didn't expect it?
  • PierreE
    PierreE over 7 years
    The 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.
    Ben L. about 7 years
    @PierreE the password is specified on the command line, not in the script.
  • Daniel Persson
    Daniel Persson almost 7 years
    The password will be visible by anyone who runs ps on the machine.
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com almost 7 years
    "assword" is amazing :-)
  • Martin Prikryl
    Martin Prikryl almost 7 years
    What does this answer show on top of existing answers? + Never ever suggest anyone to use StrictHostKeyChecking=no without explaining the consequences.
  • iSebbeYT
    iSebbeYT over 6 years
    Lets 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
    Ian over 6 years
  • filip
    filip over 6 years
    Good enough solution for Jenkins pipelines.
  • Ian
    Ian about 6 years
    note to self: update script to use trap to prevent ctrl-C from leaking the SSHPASS variable
  • Josh
    Josh about 6 years
    sshpass has an option, -f, to read the password from a file. Thus, it won't be visible when using ps, and if the file has appropriate permissions in one's own home directory, it should be safe.
  • magor
    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
    Mehrdad Mirreza almost 6 years
    This still prompts for the first login and cannot be used in a script!
  • allenyllee
    allenyllee almost 6 years
    Note that you can't add option -f to autossh in this combination, because when 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
    Winter almost 6 years
    Not available on Windows git bash
  • Kirkland
    Kirkland almost 6 years
    While 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
    Mike Partridge over 5 years
    I found that PreferredAuthentications=keyboard-interactive didn't work, but replacing it with PreferredAuthentications=password worked.
  • Martin Prikryl
    Martin Prikryl over 5 years
    What does this show on top of the existing answers? Particularly those by damn_c, Lipongo or RemiZOffAlex and others...
  • Shivam Mehrotra
    Shivam Mehrotra over 5 years
    script 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
    Craig Hicks over 5 years
    Using 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
    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
    Akhil Surapuram almost 5 years
    why we need to pass StrictHostKeyChecking=no
  • Vladimir
    Vladimir over 4 years
    Mac 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
    abbotto over 4 years
    @Vladmir For Mac OS you could try installing the unofficial package. https://gist.github.com/arunoda/7790979#installing-with-home‌​brew
  • shodanshok
    shodanshok over 4 years
    This is an extremely useful solution for non-standard ssh servers which don't work with sshpass
  • Martin Prikryl
    Martin Prikryl over 3 years
    Note that .bash_profile is quite often word-readable. So putting your password there is not a good idea.
  • alx
    alx over 3 years
    I'm running ssh inside the remote machine again, with the same password. Right now I'm exporting SSHPASS into the remote machine with export 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 of ssh.
  • Ian
    Ian over 3 years
    This 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
    Erhard Dinhobl over 3 years
    I 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
    SMshrimant over 3 years
    Thank 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
    eadmaster over 3 years
    i've added log_user 0 to skip some unrequired logs
  • Martin Prikryl
    Martin Prikryl over 3 years
    What does this show what other existing answers don't already? + Never suggest anyone to use StrictHostKeyChecking=no without explaining the security consequences.
  • Martin Prikryl
    Martin Prikryl over 3 years
    I do not see any "quick and dirty" in the OP.
  • vlsd
    vlsd over 3 years
    This seems to work at first, but since the -M0 flag disables monitoring my connection fails after a while without autossh 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
    Manuel Romeiro about 3 years
    For 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
    Zang322 about 3 years
    I tried sshpass -p "nvidia" ssh -o StrictHostKeyChecking=no nvidia@"$x" "kill `pgrep ads2`" . However it didn't work. ??
  • dns
    dns over 2 years
    The best answer for Windows user so far.
  • nhed
    nhed over 2 years
    sarcastic maybe? but this fine if trying to automate against systems with their default admin if you are in the process of provisioning them
  • AzizSM
    AzizSM over 2 years
    ssshpass work well on scp too
  • RmccurdyDOTcom
    RmccurdyDOTcom over 2 years
    No 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
    nhed over 2 years
    I 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.