I am trying to write a bash script that will allow me to login using ssh connection.
The condition is that the password is stored into a .txt file.
I need to write a bash script that will automatically request a connection to
ssh USER@example.net -p 733
and automatically will use the passwords that are stored into a .txt file
I never wrote something in bash. Can someone help me.
Thank you in advance for your time.
You can't do it with plain bash
script. You need to use expect
command.
Having said that it is really a very bad idea to have a password stored in a text file, here is how you can do it using expect
:
#!/usr/bin/expect
set timeout 20
set f [open "password.txt"]
set password [read $f]
close $f
spawn ssh user@host
expect "user@host's password:"
send $password
interact
Still I suggest to follow @Wolph's advice to look into using a pair of keys when accessing a remote server using ssh
.
i suggest you to use password less authentication it will be more secure follow these steps :
example@example:~/bash$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/example/.ssh/id_rsa): ## the directory which located private key and public key.
Enter passphrase (empty for no passphrase): ## you can use passphrase password if you want .
Enter same passphrase again: ## enter same password again.
Your identification has been saved in /home/example/.ssh/id_rsa.
Your public key has been saved in /home/example/.ssh/id_rsa.pub.
The key fingerprint is:
70:03:68:70:0a:52:16:55:55:66:62:2b:51:67:81:92 example@example
The key's randomart image is:
+--[ RSA 2048]----+
|o.=+oo++=oB. |
|.o oo E+.B |
| .. o.+ |
| + . |
| S |
| |
| |
| |
| |
+-----------------+
then type
scp -o Port=733 ~/.ssh/id_rsa.pub USER@example.net:/home/example/.ssh/authorized_keys
- then it will ask you first time for your remotely server for latest
time
- now if you type
ssh -p 733 USER@example.net
you don't need to put
any password again that's it password less authentication more secure than any script.