Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate SSH without using public key authentication or expect(1)

Is there a way to pass a password to ssh automatically. I would like to automatically ssh to a server without using public key authentication or expect scripts, by somehow getting ssh to read the password from stdin or a file.

The reason it has to be that way is that I would like to backup my files to a server using rsync/ssh running as a cron job. This server mounts my home directory after it authenticates me, so using public key authentication does not work since ~/.ssh isn't available until after the login is successful. expect(1) is out of the question because I would like to run it as a cron job, and since cron jobs don't run under a terminal the combination of expect/ssh just doesn't work. I do not have root access to that server, and it would be difficult to get the admins to make any changes to the way things work there.

like image 903
fuad Avatar asked Mar 01 '23 05:03

fuad


2 Answers

expect is out of the question because I would like to run it as a cron job, and since cron jobs don't run under a terminal the combination of expect/ssh just doesn't work

You can run expect scripts from cron, at least you can with expect libraries like "pexpect" for Python. I just tested this to confirm, running a pexpect scp/ssh script from cron and I was able to successfully scp a file from a Python script running in cron.

Example code:

#!/usr/bin/python

import pexpect

FILE="/path/to/file"
REMOTE_FILE=""
USER="user"
HOST="example.com"
PASS="mypass"
COMMAND="scp -oPubKeyAuthentication=no %s %s@%s:%s" % (FILE, USER, HOST, REMOTE_FILE)

child = pexpect.spawn(COMMAND)
child.expect('password:')
child.sendline(PASS)
child.expect(pexpect.EOF)
print child.before
like image 133
Jay Avatar answered Apr 08 '23 13:04

Jay


Use sshpass.

For example, when password is in password.txt file:

sshpass -fpassword.txt ssh username@hostname

(taken from the answer to a similar question)

like image 38
uvsmtid Avatar answered Apr 08 '23 15:04

uvsmtid