5

I want to SSH into a remote machine but instead of typing the password, I want to redirect it from another file.

So I have a file password.txt that stores the password. File.sh is my bash file.

In File.sh

#!/bin/bash
ssh -T user@10.2.5.1

While executing the file, I did:

./File.sh < password.txt

But I was asked to enter password anyway.

How do I get the password to be input from the file?

Jakuje
  • 21,357

3 Answers3

16

SSH with 'password in a file' is commonly used as public key authentication. Create a key pair using ssh-keygen, upload the public key to the other host:

scp ./.ssh/id_rsa.pub user@10.2.5.1:~/

and place it as ~/.ssh/authorized_keys:

ssh user@10.2.5.1
mkdir ~/.ssh
mv ~/id_rsa.pub ~/.ssh/authorized_keys

or, if an authorized_keys file already exists:

cat ~/id_rsa.pub >> ~/.ssh/authorized_keys

set the appropriate permissions (600 for the file, 700 for the directory):

chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh

and start a new ssh session.

Lambert
  • 12,680
  • Hello, I suggested an edit that appends to authorized_keys instead of overwriting it if it already exists. – Kos Sep 22 '16 at 10:18
  • 2
    This doesn't precisely answers the question imho, he asked for a password clearly stored in a txt – capitano666 Sep 22 '16 at 15:51
8

You can use sshpass to do that:

sshpass -f password.txt ssh -T user@10.2.5.1
Jakuje
  • 21,357
2
#!/usr/bin/expect -f
spawn ssh shw@hostname
expect -exact "shw@hostname's password: "
send -- "PASSWORD\r"
expect "$ "
interact

Expect is a tool to automate the process.

SHW
  • 14,786
  • 14
  • 66
  • 101