Zurück

Unattended Batch Jobs using SSH / DSA


Overview

If you want to automate an unattended process (e.g. cron or batch jobs) with SSH, you may notice, that SSH or SCP asks for a password, even from a script.

scp -q backuphost:/etc/hosts .
zahn@backuphost's password:

In this article, we show how to manage exactly this situation in a suitable security context using SSH version 2 with a DSA Private/Public Key Pair.

Create the Keys

zahn@backuphost> cd $HOME/.ssh
zahn@backuphost> ssh-keygen -t dsa -f batchkey -N ""
zahn@backuphost> scp batchkey.pub zahn@remotehost:$HOME/.ssh

This creates a DSA Public/Private Key without any Passphrase, so you don't have to enter a password when the script runs.

zahn@remotehost> cd $HOME/.ssh
zahn@remotehost> cat batchkey.pub >> authorized_keys

Check File Permissions

zahn@backuphost> ls -l
-rw------- 1 zahn dba 672 May 4 09:29 batchkey

zahn@remotehost> ls -l
-rw-r--r-- 1 zahn dba 601 May 4 09:30 authorized_keys

Unattended Backup using SCP

BATCHKEY="/home/zahn/.ssh/batchkey"
export BATCHKEY

REMOTEHOST="zahn@remotehost"
export REMOTEHOST

REMOTE_DIR="/backup"
export REMOTE_DIR

BACKUP_LOG="/var/log/my_backup.log"
export BACKUP_LOG

BACKUPDATE=`date +%Y-%m-%d`
export BACKUPDATE

scp -2 -i ${BATCHKEY} File-${BACKUPDATE}.tar.gz \ ${REMOTEHOST}:${REMOTE_DIR} >> ${BACKUP_LOG} 2>&1