Add your public SSH keys to a remote host’s authorized_keys in a single command
[user@localhost ~]$ cat ~/.ssh/id_rsa.pub ~/.ssh/id_dsa.pub | ssh user@remotehost ’sh -c “cat - >> ~/.ssh/authorized_keys”‘
You’ll be prompted for the password just this one last time. This is perfect for running a script that runs several remote commands through ssh. Here’s a script that checks for your keys and adds them if they’re not there. You’ll get prompted for a password twice if the keys didn’t already exist, and then no more.
#!/bin/sh
MY_NAME=`hostname`
MY_IPADDR=`hostname -i`CHECK_KEYS=`ssh user@remotehost “touch ~/.ssh/authorized_keys > /dev/null 2> /dev/null; \
chmod 700 ~/.ssh/authorized_keys; grep -e $MY_NAME ~/.ssh/authorized_keys”`LENGTH=`expr $CHECK_KEYS” : ‘.*’`
if [ $LENGTH -lt 3 ]; then
# cat the keys
else
# they already exist
fi
Another way around the password prompting issue from running a bunch of ssh commands is to branch the script and have one branch check your hostname to make sure you’re not the remote host and then start running all your commands. When you get to the stuff you want to do remotely, echo the script across your ssh tunnel and execute it. Now in the script, go into the 2nd branch that only runs if the hostname check matches the remote host, and it will skip down to this part on the remote run. This gets around having a 2nd script with all your remote commands in it. It might not be elegant, but it works!
#!/bin/sh
if [ `hostname` != $1 ]; then
# you ran this script with the remote host as the 1st argument, so it’s not going to be equal, and it will run these commands
# do a bunch of local stuff here
cat $0 | ssh user@remotehost /bin/bash `hostname`else
# i’m here because i’ve been called on the remote host
REMOTEHOST=$2
# now i can run commands as if they were local. executing `hostname` now would now return the remotehost name. So any variables you want to carry over to the remote host, such as where I was called from, just add them as additional arguments when you cat the script and grab them from $2, $3, … etc. when you enter this else clause!
fi
























Recent Comments