Shell script that makes it so you don't need a password to login to a Linux server.

Tested for Red Hat Linux 6.0 Bash Shell sh-4.1

This script only works if the username on your the box where you install the script is the same as the username on the remote box to which you which to connect. If you want to use a different user on each box then use the script I provide in my article titled "Script installs an RSA key on the local machine and a remote machine" you could search it in Google.

Instructions:

Create the directory named setup

Create in that directory a directory named "includes"

In the directory "includes" create a file called run_remote.sh

In run_remote.sh copy the following code:

#!/bin/bash
# run_remote.sh
# usage: run_remote.sh localscript remoteuser remotehost arg1 arg2 ...

realscript=$1
user=$2
host=$3
shift 3

declare -a args

count=0
for arg in "$@"; do
args[count]=$(printf '%q' "$arg")
count=$((count+1))
done

ssh $user@$host 'cat | bash /dev/stdin' "${args[@]}" < "$realscript"

Thank you to waldner for the code in run_remote.sh. (source:http://backreference.org/2011/08/10/running-local-script-remotely-with-arguments/)

Put the following in a file named set_up.sh under the setup directory:

#!/bin/bash
host=yourhost.com;
base_path=/where/the/script/is/located;
rsa_name=yourhost_rsa;
echo "Are you logged in as a user that exists both on $host and on your local box";
select yn in "Yes" "No"; do
case $yn in
Yes ) echo "Okay here we go"; break;;
No ) exit;;
esac
done
read -p "Enter your user name:" un;
#check if user exists on system
if [ -d "/home/$un/" ]; then
# Control will enter here if directory exists.
cd ~;
if [ -d "/home/$un/.ssh" ]; then
chmod 700 .ssh;
else
mkdir .ssh;
chmod 700 .ssh;

fi
cd .ssh;
echo "Don't enter a password below just hit enter:";
ssh-keygen -t rsa -f $rsa_name;
echo "Enter password to $host:";
set rsa_contents = `cat ~/.ssh/$rsa_name.pub`;
sh $base_path/includes/run_remote.sh $base_path/includes/set_up_ssh_on_server.sh $un $host $un $rsa_name;
ssh $un@$host "echo `cat ~/.ssh/$rsa_name.pub` >> ~/.ssh/authorized_keys";
exit;
else
echo "Sorry, you must use an existing user on the sytem.";
fi

Replace the variables rsa_name, host and base_path in set_up.sh

Then run set_up.sh from the command line with sh setup.sh

Now you should be able to run things like scp and ssh to login remotely and it won't ask you for your password.

to test it

ssh username@yourhost.com

comments powered by Disqus