Search The Query

How to SSH Into a Server Without Using SSH Keys

lock
Photo by regularguy.eth on Unsplash

It’s easy to log in to a remote host without passwords and without being prompted for a password using ssh keys. There are circumstances where you cannot add a public key to the authorized keys file on the remote account. Perhaps the account’s home directory is not writable nor permanent, meaning the keys can’t be stored there.

Fortunately, there are other options to log in to a remote host without entering the password yourself if you cannot use ssh keys but have the password. Why would you want to do this? Perhaps you need to script this, or the password is complicated that you want to make this easier.

There are multiple options to automate logging in with a password, but this article will cover two options.

Automated Login With Expect

Expect script is a great linux/unix and macOS utility. Expect Script is fairly simple to understand, and as the name implies, it works by parsing the output of the command and processing the supplied instruction when it matches the specified regular expression.

The following is a one-line script that uses ssh to connect to a remote host.

expect -c 'spawn ssh sib05ks; expect "password:"; send "mypassword\n"; interact'

Take note of the expect instruction, which is followed by the regular expression and, finally, the response that should be sent (“send”).

Keep in mind that when you enter a password at the command line, everyone may see it. Although doing so would still expose the password to the root user, it would be preferable to retain it in the environment or in a file that is only accessible by the user and read that in. There are other ways to secure the password, but those are outside the purview of this short article.

Using expect when scp’ing

Using expect when doing scp is similar to ssh. Here’s an example:

expect -c 'spawn scp /etc/hosts homelinux:/tmp/; expect "password:"; send “mypassword\n”; interact'

Using sshpass to login with password

sshpass runs “keyboard-interactive” password authentication in non-interactive mode.

Using sshpass is similar to using expect. Here’s an example:

sshpass -p mypassword ssh root@homelinux.com ifconfig

This command ssh to homelinux as root and run the ifconfig command.

scp using sshpass

Similar to expect, scp using sshpass is straightfoward.

sshpass -p mypassword scp /tmp/src_file root@homelinux.com:/tmp/

Final Words

Ssh keys is the preferred way to login to a remote host, but there are situations when this isn’t possible.

Fortunately, there are myriads of ways to login to a remote host using passwords when keys cannot be used.

Leave a Reply