By user1467855


2012-08-30 17:45:17 8 Comments

I need to create a script that automatically inputs a password to OpenSSH ssh client.

Let's say I need to SSH into [email protected] with the password a1234b.

I've already tried...

#~/bin/myssh.sh
ssh [email protected]
a1234b

...but this does not work.

How can I get this functionality into a script?

20 comments

@SMshrimant 2020-09-29 19:03:11

I am using below solution but for that you have to install sshpass If its not already installed, install it using sudo apt install sshpass

Now you can do this,

sshpass -p *YourPassword* shh [email protected]

You can create a bash alias as well so that you don't have to run the whole command again and again. Follow below steps

cd ~

sudo nano .bash_profile

at the end of the file add below code

mymachine() { sshpass -p *YourPassword* shh [email protected] }

source .bash_profile

Now just run mymachine command from terminal and you'll enter your machine without password prompt.

Note:

  1. mymachine can be any command of your choice.
  2. If security doesn't matter for you here in this task and you just want to automate the work you can use this method.

@Martin Prikryl 2020-09-30 06:39:23

Note that .bash_profile is quite often word-readable. So putting your password there is not a good idea.

@SMshrimant 2020-10-17 14:27:02

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.

@Manoj Rana 2019-09-30 10:33:13

In linux/ubuntu

ssh [email protected]_ip_address -p port_number

Press enter and then enter your server password

if you are not a root user then add sudo in starting of command

@DimiDak 2019-05-28 12:48:16

This is how I login to my servers.

ssp <server_ip>
  • alias ssp='/home/myuser/Documents/ssh_script.sh'
  • cat /home/myuser/Documents/ssh_script.sh

#!/bin/bash

sshpass -p mypassword ssh [email protected]$1

And therefore...

ssp server_ip

@BERGUIGA Mohamed Amine 2019-10-03 13:03:44

In the example bellow I'll write the solution that I used:

The scenario: I want to copy file from a server using sh script:

#!/usr/bin/expect
$PASSWORD=password
my_script=$(expect -c "spawn scp [email protected]:path/file.txt /home/Amine/Bureau/trash/test/
expect \"password:\"
send \"$PASSWORD\r\"
expect \"#\"
send \"exit \r\"
")

echo "$my_script"

@John Carrell 2018-12-04 17:04:47

I don't think I saw anyone suggest this and the OP just said "script" so...

I needed to solve the same problem and my most comfortable language is Python.

I used the paramiko library. Furthermore, I also needed to issue commands for which I would need escalated permissions using sudo. It turns out sudo can accept its password via stdin via the "-S" flag! See below:

import paramiko

ssh_client = paramiko.SSHClient()

# To avoid an "unknown hosts" error. Solve this differently if you must...
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# This mechanism uses a private key.
pkey = paramiko.RSAKey.from_private_key_file(PKEY_PATH)

# This mechanism uses a password.
# Get it from cli args or a file or hard code it, whatever works best for you
password = "password"

ssh_client.connect(hostname="my.host.name.com",
                       username="username",
                       # Uncomment one of the following...
                       # password=password
                       # pkey=pkey
                       )

# do something restricted
# If you don't need escalated permissions, omit everything before "mkdir"
command = "echo {} | sudo -S mkdir /var/log/test_dir 2>/dev/null".format(password)

# In order to inspect the exit code
# you need go under paramiko's hood a bit
# rather than just using "ssh_client.exec_command()"
chan = ssh_client.get_transport().open_session()
chan.exec_command(command)

exit_status = chan.recv_exit_status()

if exit_status != 0:
    stderr = chan.recv_stderr(5000)

# Note that sudo's "-S" flag will send the password prompt to stderr
# so you will see that string here too, as well as the actual error.
# It was because of this behavior that we needed access to the exit code
# to assert success.

    logger.error("Uh oh")
    logger.error(stderr)
else:
    logger.info("Successful!")

Hope this helps someone. My use case was creating directories, sending and untarring files and starting programs on ~300 servers as a time. As such, automation was paramount. I tried sshpass, expect, and then came up with this.

@RmccurdyDOTcom 2016-08-03 13:57:17

# create a file that echo's out your password .. you may need to get crazy with escape chars or for extra credit put ASCII in your password...
echo "echo YerPasswordhere" > /tmp/1
chmod 777 /tmp/1

# sets some vars for ssh to play nice with something to do with GUI but here we are using it to pass creds.
export SSH_ASKPASS="/tmp/1"
export DISPLAY=YOURDOINGITWRONG
setsid ssh [email protected] -p 22

reference: https://www.linkedin.com/pulse/youre-doing-wrong-ssh-plain-text-credentials-robert-mccurdy?trk=mp-reader-card

@Yan Foto 2016-10-21 15:09:26

I think this article is just being sarcastic!

@Shivam Mehrotra 2019-02-18 10:19:29

Use this script tossh within script, First argument is the hostname and second will be the password.

#!/usr/bin/expect
set pass [lindex $argv 1]
set host [lindex $argv 0]
spawn ssh -t [email protected]$host echo Hello
expect "*assword: " 
send "$pass\n";
interact"

@Martin Prikryl 2019-02-18 10:59:17

What does this show on top of the existing answers? Particularly those by damn_c, Lipongo or RemiZOffAlex and others...

@Shivam Mehrotra 2019-02-18 11:15:13

script execution along with ssh #!/usr/bin/expect set pass [lindex $argv 1] set host [lindex $argv 0] spawn ssh -t [email protected]$host sh /tmp/anyscript.sh expect "*assword: " send "$pass\n"; interact"

@Marko Vranjkovic 2019-08-13 14:26:03

If you are doing this on a Windows system, you can use Plink (part of PuTTY).

plink [email protected] -pw your_password

@Konstantin Ineshin 2019-04-16 17:23:59

I managed to get it working with that:

SSH_ASKPASS="echo \"my-pass-here\""
ssh -tt remotehost -l myusername

@Wolf 2020-10-20 03:55:13

Interesting, but didn't work for me

@damn_c 2015-02-03 06:59:49

After looking for an answer for 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 "assword:"
send "$password\r";
interact

Put it to /usr/bin/exp, then you can use:

  • exp <password> ssh <anything>
  • exp <password> scp <anysrc> <anydst>

Done!

@user2082382 2016-05-09 11:12:26

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!

@dmmfll 2016-06-11 23:19:52

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:

@clearlight 2017-01-20 10:50:16

Maybe it hasn't gotten more upvotes because people didn't expect it?

@PierreE 2017-03-23 00:46:15

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. 2017-05-11 14:58:04

@PierreE the password is specified on the command line, not in the script.

@Daniel Persson 2017-06-29 13:31:18

The password will be visible by anyone who runs ps on the machine.

@Ciro Santilli 郝海东冠状病六四事件法轮功 2017-07-29 09:29:40

"assword" is amazing :-)

@iSebbeYT 2017-11-08 15:28:01

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?

@shodanshok 2020-02-22 20:08:32

This is an extremely useful solution for non-standard ssh servers which don't work with sshpass

@Lipongo 2012-08-30 17:53:31

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

@user1467855 2012-08-30 18:02:38

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

@Lipongo 2012-08-30 19:53:44

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 2012-08-30 22:26:12

You can also use this shebang line: #!/usr/bin/env expect

@Karel Bílek 2013-04-09 22:02:17

I added interact to the end so the ssh session is actually interactive

@Aaron Digulla 2013-10-03 14:54:42

-1 for the huge security risk of keeping a plain text password in a script.

@Aaron McDaid 2016-08-03 14:26:04

@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 2016-08-09 15:12:09

@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.

@Sridhar Sarnobat 2018-01-16 21:47:33

sshpass + autossh

One nice bonus of the already-mentioned sshpass is that you can use it with autossh, eliminating even more of the interactive inefficiency.

sshpass -p mypassword autossh -M0 -t [email protected]

This will allow autoreconnect if, e.g. your wifi is interrupted by closing your laptop.

@allenyllee 2018-08-23 15:49:19

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/…

@abbotto 2013-05-24 12:21:23

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 [email protected]_SITE.COM

Custom port example:

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no [email protected]_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.

@Per Mejdal Rasmussen 2013-07-19 07:59:28

This is much better than using Expect.

@Alexander Taylor 2014-10-30 00:33:56

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 2015-07-13 17:42:44

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 2015-08-24 12:03:33

Is there something equivalent for cryptsetup luksAddKey /path/to/key, which prompts Enter a passphrase: ?

@Ye Lwin Soe 2016-08-29 07:27:03

for custom port to work add "-p port-number" at the end of command

@Parthian Shot 2016-09-06 18:09:54

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.

@Zelphir Kaltstahl 2016-11-14 10:05:27

@abbotto How to do this with ssh-add instead of ssh, in order to add a key?

@Ian 2017-11-20 17:08:10

@filip 2018-01-08 14:15:33

Good enough solution for Jenkins pipelines.

@Josh 2018-04-18 02:58:20

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.

@mazs 2018-06-25 12:10:25

@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.

@Winter 2018-08-26 21:29:15

Not available on Windows git bash

@Akhil Surapuram 2019-09-10 07:55:27

why we need to pass StrictHostKeyChecking=no

@Vladimir 2020-02-05 08:45:39

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 2020-02-06 18:49:19

@Vladmir For Mac OS you could try installing the unofficial package. https://gist.github.com/arunoda/7790979#installing-with-home‌​brew

@Ian 2017-11-20 17:07:16

sshpass with better security

I stumbled on this thread while looking for a way to ssh into a bogged-down server -- it took over a minute to process the SSH connection attempt, and timed out before I could enter a password. In this case, I wanted to be able to supply my password immediately when the prompt was available.

(And if it's not painfully clear: with a server in this state, it's far too late to set up a public key login.)

sshpass to the rescue. However, there are better ways to go about this than sshpass -p.

My implementation skips directly to the interactive password prompt (no time wasted seeing if public key exchange can happen), and never reveals the password as plain text.

#!/bin/sh
# preempt-ssh.sh
# usage: same arguments that you'd pass to ssh normally
echo "You're going to run (with our additions) ssh [email protected]"

# Read password interactively and save it to the environment
read -s -p "Password to use: " SSHPASS 
export SSHPASS

# have sshpass load the password from the environment, and skip public key auth
# all other args come directly from the input
sshpass -e ssh -o PreferredAuthentications=keyboard-interactive -o PubkeyAuthentication=no "[email protected]"

# clear the exported variable containing the password
unset SSHPASS

@Ian 2018-03-28 02:25:40

note to self: update script to use trap to prevent ctrl-C from leaking the SSHPASS variable

@Mike Partridge 2018-12-06 16:20:59

I found that PreferredAuthentications=keyboard-interactive didn't work, but replacing it with PreferredAuthentications=password worked.

@Cacahuete Frito 2020-10-04 20:51:44

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 2020-10-05 17:10:31

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/…

@shyam 2017-08-07 15:46:24

To connect remote machine through shell scripts , use below command:

sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no [email protected]

where IPADDRESS, USERNAME and PASSWORD are input values which need to provide in script, or if we want to provide in runtime use "read" command.

@Martin Prikryl 2017-08-12 16:48:21

What does this answer show on top of existing answers? + Never ever suggest anyone to use StrictHostKeyChecking=no without explaining the consequences.

@MustSeeMelons 2016-11-15 14:40:38

The answer of @abbotto did not work for me, had to do some things differently:

  1. yum install sshpass changed to - rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/sshpass-1.05-1.el6.x86_64.rpm
  2. the command to use sshpass changed to - sshpass -p "pass" ssh [email protected] -p 2122

@Xoroz 2016-05-24 13:25:38

I have a better solution that inclueds login with your account than changing to root user. It is a bash script

http://felipeferreira.net/index.php/2011/09/ssh-automatic-login/

@RemiZOffAlex 2015-01-17 00:10:59

Variant I

sshpass -p PASSWORD ssh [email protected]

Variant II

#!/usr/bin/expect -f
spawn ssh [email protected] "touch /home/user/ssh_example"
expect "assword:"
send "PASSWORD\r"
interact

@RemiZOffAlex 2015-11-19 18:03:56

No. sshpass is not ssh. SYNOPSIS sshpass [-ffilename|-dnum|-ppassword|-e] [options] command arguments

@Junior Mayhé 2016-09-28 18:14:24

In order to run sshpass in Linux CentOS you must yum -y install epel-release and then yum -y install sshpass

@RemiZOffAlex 2016-09-28 22:43:07

In this context of this data can be ignored

@Kirkland 2018-09-13 13:09:20

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.

@Diego Woitasen 2012-08-30 17:51:10

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 [email protected]

That's all, after that you'll be able to do ssh without password.

@user1467855 2012-08-30 17:54:05

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.

@Kimvais 2012-08-30 18:21:56

You can also store the private key on the said thumb drive.

@Aaron McDaid 2012-08-30 18:36:27

@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.

@Karel Bílek 2013-04-09 21:33:53

Unfortunately, I am in OP situation, because the sysadmin disallows authentication by rsa/dsa keys and requires passwors. What are you gonna do.

@Diego Woitasen 2013-12-06 01:54:36

I agree with @KarelBílek. The other options requires more skill, Python coding, expect. There is no easy option I think.

@zstewart 2015-09-12 22:22:59

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.

@Adama 2016-02-28 10:40:30

Thanks for demonstrating "ssh-copy-id". I was adding the IDs with the cumbersome way cat ~/.ssh/id_rsa.pub | ssh [email protected] "cat - >> ~/.ssh/authorized_keys". This is so much easier!

@Kade 2016-05-16 15:26:16

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.

@Parthian Shot 2016-09-06 18:06:53

Downvoted because this doesn't even try to answer the actual question asked.

@Mehrdad Mirreza 2018-08-02 10:20:17

This still prompts for the first login and cannot be used in a script!

@Craig Hicks 2019-03-26 19:15:46

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.

@Erhard Dinhobl 2020-10-14 12:15:15

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?

@WT29 2014-03-27 02:57:24

I got this working as follows

.ssh/config was modified to eliminate the yes/no prompt - I'm behind a firewall so I'm not worried about spoofed ssh keys

host *
     StrictHostKeyChecking no

Create a response file for expect i.e. answer.expect

set timeout 20
set node [lindex $argv 0]
spawn ssh [email protected] service hadoop-hdfs-datanode restart

expect  "*?assword {
      send "password\r"   <- your password here.

interact

Create your bash script and just call expect in the file

#!/bin/bash
i=1
while [$i -lt 129]    # a few nodes here

  expect answer.expect hadoopslave$i

  i=[$i + 1]
  sleep 5

done

Gets 128 hadoop datanodes refreshed with new config - assuming you are using a NFS mount for the hadoop/conf files

Hope this helps someone - I'm a Windows numpty and this took me about 5 hours to figure out!

@JCGB 2019-04-01 16:37:12

"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.

Related Questions

Sponsored Content

21 Answered Questions

[SOLVED] Best way to use multiple SSH private keys on one client

  • 2010-03-10 18:40:58
  • Justin
  • 467712 View
  • 907 Score
  • 21 Answer
  • Tags:   ssh ssh-keys openssh

12 Answered Questions

[SOLVED] How can I ssh directly to a particular directory?

27 Answered Questions

[SOLVED] ssh "permissions are too open" error

  • 2012-02-14 02:02:31
  • Yannick Schall
  • 1504824 View
  • 2184 Score
  • 27 Answer
  • Tags:   permissions ssh

30 Answered Questions

[SOLVED] SSH Key - Still asking for password and passphrase

15 Answered Questions

[SOLVED] How to mkdir only if a directory does not already exist?

35 Answered Questions

[SOLVED] How can I check if a directory exists in a Bash shell script?

  • 2008-09-12 20:06:25
  • Grundlefleck
  • 2847538 View
  • 3816 Score
  • 35 Answer
  • Tags:   bash shell unix posix

17 Answered Questions

[SOLVED] How to use SSH to run a local shell script on a remote machine?

28 Answered Questions

[SOLVED] ssh remote host identification has changed

6 Answered Questions

Sponsored Content