SSH to a host

Some notes for setting up SSH connection to a remote computer.

The most straightforward way is apparently

1
ssh user@host

For frequent access, it would be nice to create an alias in the .bashrc file,

1
alias myssh='ssh user@host'

Naive connection to host would require the password of username. So a better way is to setup the public key authentication, i.e. a security key pair on the local and the remote computers.

The steps are simple. First, run ssh-keygen to generate the private and the public keys using the specified algorithm, which by default is the RSA. Then, the public key needs to be copied to the host and installed in the authorized_keys file. One can either do it manually, or using a handy tool,

1
ssh-copy-id -i path_to_key user@host

Finally, scp can be used to transfer files to and from the host. The usage is just like the cp command,

1
2
scp user@host:path_to_file_to_copy path_to_copied_file
scp path_to_file_to_copy user@host:path_to_copied_file

Again, for frequent access to a particular host, it would be nice to avoid user@host in the scp command. Something like below is expected,

1
2
myscp -d path_to_file_to_copy path_to_copied_file
myscp -u path_to_file_to_copy path_to_copied_file

The myscp command can be implemented as follows,

1
2
3
4
function myscp() {
user="user@host:"
scpwrapper $user "$@"
}

And the scpwrapper function is defined as,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function scpwrapper() {
user=$1
# Default: file from local to server
opt=""
u1=""
u2=$user
if [ $# -le 5 ]; then
if [ "$1" == "-h" ]; then
echo "Wrapper for scp to a given server"
echo " -u Upload to server"
echo " -d Download from server"
echo " -* Options for scp"
return 0
fi
while [[ $# > 3 ]]
do
key="$2"
case $key in
-u)
u1=""
u2=$user
shift
;;
-d)
u1=$user
u2=""
shift
;;
*)
opt=$key
shift
;;
esac
done
else
echo "Too many arguments"
echo "Exiting"
return 1
fi
f1=$2
f2=$3
echo "Executing: scp $opt $u1$f1 $u2$f2"
scp $opt $u1$f1 $u2$f2
}

References:

  1. ssh-keygen
  2. RSA