0

I would like to write a script that can ssh into a linux target without any user interaction. The machine my script runs from as well as the targets that I'm trying to ssh into get reformatted every night so I can't use ssh-keygen (as far as I've seen) because I'm required to enter in the target's password manually when the keys are being set up. So instead I'm trying to use sshpass. Here's a simple example of how I'd like to use it:

#!/bin/bash
host=$1
user=$2
pass=$3

sshpass -p $pass scp myfiles.tar.gz $user@$host:/
sshpass -p $pass ssh $user@$host "tar xvf myfiles.tar.gz" 

This works fine EXCEPT when the target's password is blank. If instead I write:

sshpass -p "" scp myfiles.tar.gz $user@$host:/
sshpass -p "" ssh $user@$host "tar xvf myfiles.tar.gz"

The commands work fine for that target. So I'd like to be able to do this somehow with the 'pass' variable that I was using. I've tried things like

pass=""
pass="\"\""
pass="''"
pass="\n"

but none of them seem to work. Does anyone know what I need to set my 'pass' variable to?

  • If the machine is being reformatted or reimaged every night, why can't you get your public key added to the image for your `authorized_keys` file? – DopeGhoti Feb 12 '14 at 00:54
  • @DopeGhoti I don't have control over the base images of the targets. They're real-time linux devices that I'm reformatting using NI-MAX. I've tried setting up the keys on the machine I'm running from but then as soon as I reformat the targets, their keys change and I need to enter the targets' passwords again to delete the old keys and add the new ones. – Eric Satterness Feb 12 '14 at 15:06

1 Answers1

0

Always quote your variables:

...
pass=""
sshpass -p "$pass" scp myfiles.tar.gz "$user@$host:/"
sshpass -p "$pass" ssh "$user@$host" "tar xvf myfiles.tar.gz"

This prevents empty strings from disappearing, and also prevents other issues like passwords with spaces splitting up and passwords with asterisks turning into filenames.

PS: shellcheck automatically points this out.

that other guy
  • 116,971
  • 11
  • 170
  • 194