3. Networking: ssh
-
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 user01echo user01:pass01 | sudo chpasswdLet's login to it:
ssh user01@localhostls -alexitWe can also use
sshto just run a command remotely:ssh user01@localhost ls -alssh user01@localhost whoamissh user01@localhost ls .*ssh user01@localhost 'ls .*' -
Writing a password each time that we use
sshquickly becomes tedious. We can use keys instead, which is easier and more secure.First let's generate a public/private key pair:
ssh-keygen --helpssh-keygen -t ecdsa -q -N '' -f ~/.ssh/key1The option
-N ''makes it generate a key that does not have a passphrase.ls -al ~/.ssh/key1*cat ~/.ssh/key1cat ~/.ssh/key1.pubIn 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@localhostNow let's try to login using the private key as an identity file:
ssh -i ~/.ssh/key1 user01@localhostls -alcat .ssh/authorized_keysexitcat ~/.ssh/key1.pubYou may notice that the public key has been appended to
.ssh/authorized_keyson 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
EOFcat ~/.ssh/configNow we can just use
sshwith the nameserver1, 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 server1exitssh server1 whoami -
Using
scp,sftp,rsyncetc.All these tools use an SSH tunnel for a secure communication with the server. Now that we have an easy
sshaccess to the server, we can also use easily these tools:touch foo.txtscp foo.txt server1:ssh server1 ls -lssh server1 touch bar.txtssh server1 ls -lscp server1:bar.txt .ls -l bar.txtsftp:sftp server1lshelpquitrsync:ls testdirrsync -av testdir server1:ssh server1 lsssh server1 ls testdir