Skip to content

SSH

Estimated time to complete this lab: 30 mins

Objectives

At the end of this self-learning lab, you should be able to:

  • Use network utilities like ifconfig
  • Use ssh to login to a remote Linux system
  • Use tmux to split a terminal window
  • Use sftp to transfer files from and to a remote server

Why do we need SSH?

SSH allows terminal-based remote connection to other computers.

  • We need to run commands on our robots. There may not always be screens or keyboards attached to our robots. Even if they do, it is impractical to type commands on a moving robot.
  • SSH is also used for transferring files between computers.

The side to be remote-controlled needs to run an SSH server, and the side to control needs to run an SSH client. In this lab we will focus on using SSH clients.

Installing an SSH client

Most distributions come with SSH by default. Try the ssh -V command on terminal to check.

If the ssh command is not already installed, run the following:

sudo apt-get update
sudo apt-get install openssh-client

Git Bash comes with the ssh command by default. See the installation guide for Git Bash in the Git section.

In some public computer in HKU campus where Git Bash is not installed, you can also look for a program called "PuTTY".

It is installed by default. Check out the brew command if it doesn't work.

Use the Termius app.

SSH keys

SSH keys are used to authenticate yourself to an SSH server so that you don't need to type the password every time.

To generate an SSH key, just run the ssh-keygen command. It is fine to leave passphrase empty if you don't leak the key file. The generated SSH key is stored in ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub.

Attention

Treat SSH keys like your personal passwords. Do not upload your private SSH key to computers on robots. The SSH keys on robots correspond to our team accounts.

Note

SSH keys are also used to authenticate on Git. We will use the SSH key again in the Git tutorial.

Obtaining the IP address

To tell SSH which computer to connect to, we need to know its IP address.

How do I know the IP address of a machine if I haven't connected to it yet?

Method 0: You don't have to.

If you are connecting to a computer in M2, there is a chance that the IP address is already stuck on the machine.

Method 1: Access the machine physically.

Attach a keyboard and display to the machine directly so that you can access the system terminal.

Run the command ifconfig to display the network configuration.

$ ifconfig
eno1      Link encap:Ethernet  HWaddr 1c:69:7a:63:fa:da
          ...
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          ...
wlp0s20f3 Link encap:Ethernet  HWaddr 98:af:65:e5:d6:a2
          inet addr:192.168.1.8  Bcast:192.168.1.255  Mask:255.255.255.0
          ...

Each inet addr corresponds to a network interfaace. Usually wired networks start with e (e.g. eth0, enp2s0), and wireless networks start with w. In M2, usually, IP addresses start with 192.168.. Look at the address starting with inet addr: (not broadcast).

Method 2: Use the router web interface.

If both local and reomte machines are connected to the same network, you can find the IP address from the router.

How do I access the router web interface?

Look at the default gateway address.

Use ip route show and look for the default line.

$ ip route show | grep "default"
default via 192.168.1.1 dev wlp0s20f3  proto static  metric 600

Method 3: Scan the local network for the device. (Optional)

Connecting to a server

Use the command ssh <remote username>@<remote hostname>.

If you are prompted for "authenticity cannot be established", type "yes".

To avoid typing the password every time, run this command the first time:

ssh-copy-id <remote-username>@<remote-hostname>

This will copy your .ssh/id_rsa.pub (your public key) to the list of authorized users on the server. Alternatively, just append the contents of your local ~/.ssh/id_rsa.pub to the remote ~/.ssh/authorized_keys on the server manually (ask someone who can access the server to do it for you if you don't know the account psasword on the server).

Info

RSA fingerprint of SSH servers are used to prevent man-in-the-middle attacks in the real world. However in M2, if you see an error that says RSA fingerprint is changed, it is most likely because the IP address changed, and you should check if the IP address is correct.

Simply delete the corresponding lines (or all lines) in ~/.ssh/known_hosts if you confirmed everything is going right.

.ssh/config (optional)

You can create a file .ssh/config to prevent typing the full address every time:

Host tr
Hostname 192.168.1.5
User m2

Host pr
Hostname 192.168.1.6
User m2

Then typing the command ssh tr is equivalent to ssh [email protected].

Tip: Setting a default personal bashrc

Using .ssh/config, you can customize your SSH shell. For example, if there is a shell script /home/m2/.sofe-bashrc on the server, and you want to run it after your SSH connection is created before you type other commands, put these two lines in your .ssh/config at the corresponding host entry:

RequestTTY yes
RemoteCommand bash --rcfile /home/m2/.sofe-bashrc -i

Use this to avoid changing the .bashrc on robots in a way that could interfere with others' workflow.

Installing an SSH server (optional)

On Linux,

sudo apt-get update
sudo apt-get install openssh-client

User accounts on SSH are same as user accounts on the operating system, so no extra setup is required.

Try it yourself!

You can actually SSH to yourself if you have both SSH server and client installed on the same machine. Try running ssh-copy-id localhost and see if your id_rsa.pub is copied to your ~/.ssh/authorized_keys file. (localhost is the hostname for your own machine)

Using tmux

tmux is a tool to manage terminal windows, so that you can

  • run multiple commands in the same session
  • split your window into multiple shells
  • share your shell session with other users
  • keep your command running even after your SSH connection is closed

Try it yourself

  • Run tmux to start a new tmux session.
    • A tmux session is a shell managed by tmux.
    • You can tell that your shell is a tmux session by the green bar at the bottom of the terminal window.
  • To split a tmux session horizontally (one top one bottom), type Ctrl-B, then "
    • All tmux hotkeys start with Ctrl-B.
  • To split a tmux session vertical (one left one right), type Ctrl-B, then %
  • To change the split pane you are controlling, type Ctrl-B, then an arrow key.
  • You can scroll up to view older output in a tmux session.
    • Type Ctrl-B then [ to enter scroll mode. Then scroll using arrow keys and PgUp/PgDn keys.
    • In some terminals you can also use the mouse to scroll after entering scroll mode.
    • Type q to quit scrolling.
  • You can detach terminal sessions, so that the command keeps running in the background. You can go back to the session by attaching the session again.
    • Type Ctrl-B then d to detach.
    • Run the tmux a command to attach.
tmux cheatsheet

SFTP

SFTP uses the SSH layer to transfer files. Any server supporting SSH also supports SFTP.

Command interface

You can upload/download files using the sftp command, which comes together with openssh-client.

sftp also supports using Host names in .ssh/config as well as SSH keys, and has similar syntax to ssh:

$ sftp [email protected]
Connected to 192.168.1.5.
sftp> help
Available commands:
bye                                Quit sftp
cd path                            Change remote directory to 'path'
chgrp grp path                     Change group of file 'path' to 'grp'
chmod mode path                    Change permissions of file 'path' to 'mode'
chown own path                     Change owner of file 'path' to 'own'
df [-hi] [path]                    Display statistics for current directory or
                                   filesystem containing 'path'
exit                               Quit sftp
get [-afPpRr] remote [local]       Download file
reget [-fPpRr] remote [local]      Resume download file
reput [-fPpRr] [local] remote      Resume upload file
help                               Display this help text
lcd path                           Change local directory to 'path'
lls [ls-options [path]]            Display local directory listing
lmkdir path                        Create local directory
ln [-s] oldpath newpath            Link remote file (-s for symlink)
lpwd                               Print local working directory
ls [-1afhlnrSt] [path]             Display remote directory listing
lumask umask                       Set local umask to 'umask'
mkdir path                         Create remote directory
progress                           Toggle display of progress meter
put [-afPpRr] local [remote]       Upload file
pwd                                Display remote working directory
quit                               Quit sftp
rename oldpath newpath             Rename remote file
rm path                            Delete remote file
rmdir path                         Remove remote directory
symlink oldpath newpath            Symlink remote file
version                            Show SFTP version
!command                           Execute 'command' in local shell
!                                  Escape to local shell
?                                  Synonym for help

In particular, use the put and get commands to upload and download files.

Try it yourself

If you have an SSH server running locally, you can try uploading files to your own machine.

First run sftp localhost from the home directory. In the sftp interface, run lls and ls respectively. They should both show the same contents, which is your home directory listing.

Run lcd Downloads to enter your Downloads folder (Or any other directory you like). Then run get .bash_history. Now you have copied your ~/.bash_history to ~/Downloads/.bash_history via SFTP!

Ubuntu file manager

In Ubuntu's file manager, you can also type sftp://[email protected] in the address bar to access the files as if they are a local directory. However, sftp:// is just a special extension to Ubuntu's file manager. It works in some scenarios, but does not in most cases.

sshfs

If you want to conveniently access remote files as if they are on the local filesystem, you can mount them using the sshfs command. See their GitHub page for details.

WSL support

sshfs uses libfuse, which is not supported on Windows Subsystem for Linux.

FileZilla

On Windows, the FileZilla FTP client can also be used to access SFTP servers.

However, it is in general discouraged to transfer files between Windows and Linux because of the following reasons:

Line endings

Windows uses CRLF line endings by default while MacOS/Linux uses LF line endings. This will result in errors such as /usr/bin/env: ‘python\r’: No such file or directory.

File modes

Windows does not have the concept of "file mode" as in Linux. Downloading a file then uploading back would lead to loss of file mode data. This will result in errors such as "Permission denied", or weird errors such as rosrun reporting that a file is not found (you will learn this in the ROS Tutorials).