Passa al contenuto principale

3. Networking: ssh

  1. Another network tool is ssh, which can be used to login to a remote system, execute commands remotely, and more.

    First let's create a user account:

    sudo useradd -m -s /bin/bash user01
    echo user01:pass01 | sudo chpasswd

    Let's login to it:

    ssh user01@localhost
    ls -al
    exit

    We can also use ssh to just run a command remotely:

    ssh user01@localhost ls -al
    ssh user01@localhost whoami
    ssh user01@localhost ls .*
    ssh user01@localhost 'ls .*'
  2. Writing a password each time that we use ssh quickly becomes tedious. We can use keys instead, which is easier and more secure.

    First let's generate a public/private key pair:

    ssh-keygen --help
    ssh-keygen -t ecdsa -q -N '' -f ~/.ssh/key1

    The option -N '' makes it generate a key that does not have a passphrase.

    ls -al ~/.ssh/key1*
    cat ~/.ssh/key1
    cat ~/.ssh/key1.pub

    In order to be able to login to the server with this key, we need to send the public part of it to the server:

    ssh-copy-id -i ~/.ssh/key1.pub user01@localhost

    Now let's try to login using the private key as an identity file:

    ssh -i ~/.ssh/key1 user01@localhost
    ls -al
    cat .ssh/authorized_keys
    exit
    cat ~/.ssh/key1.pub

    You may notice that the public key has been appended to .ssh/authorized_keys on the server.

    It gets even better. Let's add this configuration to ~/.ssh/config:

    cat <<EOF >> ~/.ssh/config
    Host server1
    HostName 127.0.0.1
    User user01
    IdentityFile ~/.ssh/key1
    EOF
    cat ~/.ssh/config

    Now we can just use ssh with the name server1, without having to specify the hostname (or IP) of the server, the username, the identity file etc. It will get them automatically from the config file.

    ssh server1
    exit
    ssh server1 whoami
  3. Using scp, sftp, rsync etc.

    All these tools use an SSH tunnel for a secure communication with the server. Now that we have an easy ssh access to the server, we can also use easily these tools:

    touch foo.txt
    scp foo.txt server1:
    ssh server1 ls -l
    ssh server1 touch bar.txt
    ssh server1 ls -l
    scp server1:bar.txt .
    ls -l bar.txt

    sftp:

    sftp server1
    ls
    help
    quit

    rsync:

    ls testdir
    rsync -av testdir server1:
    ssh server1 ls
    ssh server1 ls testdir
Loading asciinema cast...