Networking from the shell: ip, ss, curl, dig, SSH keys, scp and rsync
In this lesson
Find a server's address, see which process owns a port, call an API with curl, check DNS with dig, log in with SSH keys and copy files with scp and rsync.
On this page
Servers live on networks, and most of your debugging starts with a few questions. What is this machine's address? Is my app listening? Does the domain point where I think? Can I reach the API? This lesson gives you one tool for each question, plus the tools to log in and copy files securely.
Why this matters#
"The site is down" can mean the app crashed, the app is running on the wrong port, DNS points at the wrong server, a firewall blocks traffic, or the old process still holds the port. Each cause has a quick check from the shell, and checking in order saves you from restarting things at random. SSH and rsync are also how you will deploy in the capstone lesson.
We ran these on a Linux machine. The SSH examples were tested against an SSH server running on 127.0.0.1 port 2222 for the test, as the user deploy. On a real server you would use its address, written here as 203.0.113.10, which is a reserved documentation address.
ip: what addresses does this machine have?#
ip -brief addr
ip routelo UNKNOWN 127.0.0.1/8
eth0 UP 192.0.2.2/24
default via 192.0.2.1 dev eth0
192.0.2.0/24 dev eth0 proto kernel scope link src 192.0.2.2 We removed some virtual interfaces from the list. lo is the loopback interface, 127.0.0.1, which only the machine itself can reach. eth0 is the real network card (names such as ens3 are common on cloud servers), and UP means it is active. The address after the name is the machine's own address with its subnet size. The default via line is the gateway where traffic for other networks goes.
On older tutorials you will see ifconfig and netstat. They still exist on some systems but ip and ss replace them.
ss: what is listening on which port?#
A port is a number that picks one program on a machine, so one address can host many services: SSH on 22, HTTP on 80, HTTPS on 443, PostgreSQL on 5432, and in this course the API on 5100. A program that waits for connections is listening.
ss -ltnpState Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 128 127.0.0.1:2222 0.0.0.0:* users:(("sshd",pid=2146,fd=3))
LISTEN 0 5 127.0.0.1:5100 0.0.0.0:* users:(("python3",pid=2309,fd=3))We trimmed the output to the two relevant lines. The flags are -l listening sockets, -t TCP, -n numbers instead of names, and -p the process that owns each socket. Seeing the process usually needs sudo for sockets that belong to other users; we ran as root.
Read the Local Address carefully. 127.0.0.1:5100 means the app accepts connections only from the same machine, so nginx on that server can reach it but the internet cannot. 0.0.0.0:5100 or *:5100 means all network interfaces, which is reachable from outside unless a firewall blocks it. A very common deploy bug is an app bound to 127.0.0.1 inside a container, or bound to 0.0.0.0 when you meant it to be private.
This is also the answer to "what is using port 5100?". Filter for the port:
ss -ltnp 'sport = :5100'State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 5 127.0.0.1:5100 0.0.0.0:* users:(("python3",pid=2309,fd=3))Process 2309, python3, holds the port. lsof -i :5100 gives the same answer with the owner's name. If you try to start a second server on the same port, it fails:
OSError: [Errno 98] Address already in useIn a Node app the same error reads EADDRINUSE. Now you know the fix: find the PID with ss, then stop the old process with kill PID (lesson 8) or stop its service (lesson 9), and start the new one.
curl: talk to an HTTP server#
curl makes a request and prints the response. It is the quickest way to test an API without a browser.
curl -s http://127.0.0.1:5100/health{"status":"ok","version":"1.4.2"}-s hides the progress meter. Options you will use daily:
-Ishows only the response headers.-ishows headers and body.-vshows the full conversation, including the request your client sent.-o /dev/null -w '%{http_code}\n'throws away the body and prints only the status code, handy in scripts.-X POST -H 'Content-Type: application/json' -d '{"a":1}'sends a JSON body.-Lfollows redirects.-fmakes curl fail (exit code 22) on a 4xx or 5xx response instead of printing the error page.
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5100/health
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5100/missing
curl -s http://127.0.0.1:5999/ ; echo "exit=$?"
curl -sf http://127.0.0.1:5100/missing ; echo "exit=$?"200
404
exit=7
exit=22Exit code 7 means curl could not connect at all: nothing is listening on that port. A 404 means the server answered and the path was wrong. Telling these two apart is the first step in every "the API is down" investigation. Exit code 22 appears only with -f, which a health check in a deploy script should always use.
dig: what does this name resolve to?#
Domain names are turned into addresses by DNS. dig asks a DNS server directly and shows the answer.
dig example.com A +noall +answer
dig example.com MX +shortexample.com. 300 IN A 203.0.113.10We replaced the real address in this output with the documentation address, but the layout is exact. The columns are the name, the TTL (how many seconds resolvers may cache the answer), the class IN, the record type A (an IPv4 address) and the value. Use +short for just the values and dig @8.8.8.8 example.com to ask a specific resolver, for instance to compare your server's answer with a public one. After you change a DNS record, the old answer can stay in caches for the length of its TTL, so a low TTL before a migration helps. AAAA is the record type for IPv6, MX for mail and TXT for text such as domain verification.
SSH and keys#
SSH gives you an encrypted shell on a remote machine: ssh deploy@203.0.113.10. Passwords work but are weak against guessing. Keys are better. You create a key pair: a private key that stays on your laptop and a public key that you place on the server. The server checks that you hold the private key without it ever being sent.
ssh-keygen -t ed25519 -C "deploy@laptop"Generating public/private ed25519 key pair.
Your identification has been saved in /home/deploy/.ssh/id_ed25519
Your public key has been saved in /home/deploy/.ssh/id_ed25519.pubAccept the default file name. Set a passphrase on a real key, so a stolen laptop does not mean a stolen server. Never share the file without .pub. Never put a private key in a Git repository or a chat message.
Install the public key by appending it to ~/.ssh/authorized_keys on the server. The easy way is ssh-copy-id deploy@203.0.113.10 from your laptop. The permissions matter, as lesson 7 taught:
700 /home/deploy/.ssh
-rw------- 1 deploy deploy 95 Dec 2 20:50 /home/deploy/.ssh/authorized_keysIf .ssh or authorized_keys is writable by others, the server ignores the key. The client side checks too. We made the private key world-readable and tried to connect:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/home/deploy/.ssh/id_ed25519' are too open.
This private key will be ignored.The fix is chmod 600 ~/.ssh/id_ed25519. Without the key, the connection ends with Permission denied (publickey).
The first time you connect to a host, SSH shows its fingerprint and asks you to trust it, and then saves it in ~/.ssh/known_hosts. If the fingerprint later changes, SSH warns loudly, because it may mean someone is impersonating the server. Do not silence that warning without understanding why it appeared.
To avoid long commands, save settings in ~/.ssh/config:
Host web1
HostName 203.0.113.10
User deploy
IdentityFile ~/.ssh/id_ed25519Then ssh web1 is enough, and scp and rsync accept the same name. In our test the config pointed at the test server, and ssh web1 "echo via alias" printed via alias. You can also run a single command remotely: ssh web1 'systemctl status myapp'.
scp and rsync: copying files#
scp copies files over SSH, with cp-like syntax and host:path for the remote side.
scp /tmp/app.tar.txt web1:/tmp/app.copy
scp web1:/tmp/app.copy /tmp/back.txt
scp -r /tmp/src web1:/tmp/src_copyThe first copies up, the second copies down and the third copies a folder. (The port option for scp is a capital -P; for ssh it is a lowercase -p.)
rsync is better for deploys because it sends only what changed.
rsync -av /tmp/src/ web1:/tmp/dst/sending incremental file list
index.html
public/
public/app.js
sent 235 bytes received 62 bytes 594.00 bytes/sec
total size is 4 speedup is 0.01-a keeps permissions, times and folders, and -v lists what was sent. After we changed one file and added another, the second run sent only those two. The trailing slash on the source matters: src/ means "the contents of src", while src means "the folder src itself", which would create dst/src. With --delete, rsync also removes files on the destination that no longer exist in the source. Always preview that with -n (dry run), which printed deleting new.txt without doing it. A wrong source path plus --delete can empty a folder.
Try it#
- Run
ip -brief addrand note your machine's address. Runss -ltnand list the ports with something listening. Which ones accept only local connections? - Start a test server with
python3 -m http.server 5100 --bind 127.0.0.1. In a second terminal, find its PID withss -ltnp 'sport = :5100', test it withcurl -I http://127.0.0.1:5100/, then stop it withkill. - Run
curl -s -o /dev/null -w '%{http_code}\n'against a working URL and against a missing path on the same server. What doescurlprint and return for a port where nothing is listening? - Run
dig example.com +shortanddig example.com MX +short. Then trydig @8.8.8.8 example.com +shortand compare. - Generate a key pair with
ssh-keygen -t ed25519into a temporary path, look at the permissions of both files, then change the private key to644and read whatssh -isays.
Sign in to keep track of the lessons you finish.