Using the SSH Command Line for UCI: An Introduction
Table of Contents
- Introduction: What is SSH and Why Use It at UCI?
- What is SSH? (Secure Shell)
- Key Features: Security, Remote Access, Command Execution, Tunneling
- Why is SSH Essential at UCI? (Accessing Servers, HPC, Development)
- Who is This Guide For?
- What We Will Cover
- Prerequisites: Getting Ready to Connect
- Your UCI NetID and Password
- A Computer with Internet Access
- An SSH Client (Built-in vs. Third-Party)
- macOS and Linux
- Windows (Windows Terminal/OpenSSH, PuTTY, WSL)
- Knowing Your Destination: UCI Hostnames
- Core Concepts: Understanding the Fundamentals
- The Client-Server Model
- Authentication Methods
- Password Authentication
- Public Key Authentication (Highly Recommended)
- Encryption: The “Secure” in Secure Shell
- The Command Line Interface (CLI)
- Your First Connection: Stepping Through the Process
- The Basic SSH Command Syntax:
ssh your_ucinetid@hostname
- Finding the Right Hostname (e.g.,
openlab.ics.uci.edu
, Departmental Servers) - The Host Key Verification Prompt (Crucial Security Step)
- Understanding
~/.ssh/known_hosts
- What to Do When a Host Key Changes
- Understanding
- Authenticating with Your Password
- Successfully Connected: The Remote Shell Prompt
- Disconnecting:
exit
orlogout
- The Basic SSH Command Syntax:
- Essential Command Line Skills for Remote Work
- Understanding Your Location:
pwd
- Listing Files and Directories:
ls
(and options like-l
,-a
,-h
,-t
,-r
) - Navigating the Filesystem:
cd
(absolute vs. relative paths,..
,~
,-
) - Creating Directories:
mkdir
- Removing Empty Directories:
rmdir
- Removing Files and Directories:
rm
(use with caution!-r
,-f
,-i
) - Copying Files and Directories:
cp
(-r
) - Moving and Renaming Files:
mv
- Viewing File Contents:
cat
,less
,more
,head
,tail
- Basic Text Editing:
nano
,vim
,emacs
(A brief look atnano
) - Getting Help:
man
and--help
- Checking Disk Usage:
du
anddf
- Finding Files:
find
andlocate
- Searching Within Files:
grep
- Managing Processes:
ps
,top
,htop
,kill
- Understanding Your Location:
- Secure File Transfer: Moving Data To and From UCI Servers
- SCP (Secure Copy Protocol)
- Syntax Overview
- Copying from Local to Remote
- Copying from Remote to Local
- Copying Directories (
-r
option) - Specifying Ports (
-P
option) - Preserving Attributes (
-p
option)
- SFTP (SSH File Transfer Protocol)
- Starting an Interactive SFTP Session
- Navigating Local and Remote Systems (
ls
,cd
,lls
,lcd
,pwd
,lpwd
) - Uploading Files (
put
/mput
) - Downloading Files (
get
/mget
) - Managing Remote Files (
mkdir
,rmdir
,rm
) - Getting Help (
help
or?
) - Exiting SFTP (
exit
orquit
) - Advantages of SFTP over SCP
- Choosing Between SCP and SFTP
- SCP (Secure Copy Protocol)
- Enhancing Security and Convenience: SSH Key Authentication
- Why Use SSH Keys? (Security, Convenience)
- How SSH Keys Work (Public/Private Key Pair)
- Generating Your SSH Key Pair (
ssh-keygen
)- Choosing Key Type (RSA, Ed25519 – Recommended)
- Choosing Key Size
- Setting a Strong Passphrase (Critical!)
- Default Key Location (
~/.ssh/id_ed25519
,~/.ssh/id_ed25519.pub
)
- Copying Your Public Key to the UCI Server
- The Easy Way:
ssh-copy-id
(Recommended) - The Manual Way (If
ssh-copy-id
isn’t available)
- The Easy Way:
- Connecting Using Your SSH Key
- Troubleshooting Key Authentication
- Managing Multiple Keys
- Streamlining Connections: The SSH Config File
- What is
~/.ssh/config
? - Basic Syntax:
Host
,HostName
,User
,Port
,IdentityFile
- Creating Aliases for Easy Connections
- Specifying Different Keys for Different Hosts
- Setting Default Options
- Example Configurations
- Permissions for
~/.ssh/config
- What is
- Advanced SSH Techniques for Power Users
- Running Remote Commands Directly:
ssh user@host 'command'
- SSH Agent: Managing Key Passphrases:
- Starting the Agent (
eval $(ssh-agent -s)
) - Adding Keys (
ssh-add
) - Benefits and Security Considerations (Agent Forwarding)
- Starting the Agent (
- Port Forwarding (Tunneling):
- Local Port Forwarding (
-L local_port:destination_host:destination_port
) – Accessing remote services locally. Use Case Example (Database/Web). - Remote Port Forwarding (
-R remote_port:destination_host:destination_port
) – Exposing local services remotely. Use Case Example (Development/Demo). - Dynamic Port Forwarding / SOCKS Proxy (
-D local_port
) – Tunneling general traffic. Use Case Example (Secure Browsing).
- Local Port Forwarding (
- Keeping Connections Alive:
- Client-Side (
ServerAliveInterval
,ServerAliveCountMax
in~/.ssh/config
) - Server-Side (
ClientAliveInterval
,ClientAliveCountMax
– usually admin controlled)
- Client-Side (
- Terminal Multiplexers:
tmux
andscreen
- Why Use Them? (Persistent Sessions, Multiple Windows/Panes)
- Brief Introduction to
tmux
(Starting, DetachingCtrl-b d
, Reattachingtmux attach
) - Brief Introduction to
screen
(Starting, DetachingCtrl-a d
, Reattachingscreen -r
)
- Running Remote Commands Directly:
- Security Best Practices for SSH
- Always Use Strong Passphrases for Keys
- Prefer SSH Keys Over Password Authentication
- Protect Your Private Keys (Permissions, No Sharing)
- Verify Host Keys Diligently on First Connection
- Keep Your SSH Client and System Software Updated
- Use Firewalls (Locally and Understand Server-Side Firewalls)
- Be Cautious with Agent Forwarding (
-A
) - Understand Permissions on
~/.ssh
Directory and Files - Log Out When Finished
- Consider Multi-Factor Authentication (MFA/2FA) if Offered/Required by UCI
- Troubleshooting Common SSH Issues at UCI
Connection refused
: Server down? Wrong hostname/port? Firewall blocking?Permission denied (publickey,password)
: Wrong password? Key not set up? Incorrect key permissions? Wrong username? Account disabled? MFA issues?Host key verification failed
: Potential Man-in-the-Middle attack? Server key legitimately changed? How to remove the old key fromknown_hosts
.Connection timed out
: Network problems? Server unresponsive? Firewall issue further upstream?WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
: Similar to verification failure.- Slow Connection / Lag: Network latency? High server load? Resource limits?
- “Too many authentication failures”: Check SSH client verbosity (
-v
,-vv
,-vvv
), ensure correct method/key is being tried first.
- UCI-Specific Considerations
- Official Documentation: Always refer to UCI OIT or specific departmental IT pages for the most current hostnames, policies, and support.
- Specific Hostnames:
openlab.ics.uci.edu
(ICS),hpc.oit.uci.edu
(HPC – check current name), departmental servers (e.g.,linux.server.eng.uci.edu
). These can change! - Authentication Policies: Duo MFA might be integrated with SSH logins. Follow official instructions.
- Software Environment: Understand the available software (compilers, libraries, applications) on the servers you connect to (use
module avail
,which
, etc.). - Resource Limits and Usage Policies: Be mindful of CPU time, memory, disk space quotas, and acceptable use policies, especially on shared systems like OpenLab or HPC clusters.
- Conclusion: Your Journey with SSH at UCI
- Recap of SSH’s power and utility.
- Encouragement for practice and exploration.
- Final reminder to consult official UCI resources.
1. Introduction: What is SSH and Why Use It at UCI?
Welcome to the world of remote computing at the University of California, Irvine (UCI)! Whether you’re a student in Computer Science needing to access lab servers, a researcher leveraging High-Performance Computing (HPC) clusters, or staff managing web resources, you’ll almost certainly encounter the need to connect to remote systems. The primary tool for doing this securely and efficiently is the SSH Command Line.
What is SSH? (Secure Shell)
SSH, short for Secure Shell (or sometimes Secure Socket Shell), is a network protocol that allows you to securely connect to and interact with a remote computer over an unsecured network, like the internet. Think of it as a secure tunnel through which you can send commands and receive output as if you were sitting directly in front of the remote machine.
Before SSH became widespread (standardized around 1995-2006), protocols like Telnet and RSH were commonly used for remote login. However, these older protocols transmitted data, including usernames and passwords, in plain text, making them highly vulnerable to eavesdropping. SSH was designed specifically to overcome these security flaws.
Key Features: Security, Remote Access, Command Execution, Tunneling
SSH provides several critical capabilities:
- Security: This is paramount. SSH encrypts all traffic between your local computer (the client) and the remote computer (the server). This includes your login credentials (username/password or key passphrase), the commands you type, and the output you receive. It prevents eavesdropping, connection hijacking, and other network-level attacks. It also includes mechanisms to verify the identity of the remote server you’re connecting to, preventing Man-in-the-Middle (MitM) attacks.
- Remote Access: SSH allows you to log into a remote machine and get a shell prompt (a command-line interface). From this prompt, you can execute commands, run programs, manage files, and interact with the remote operating system (typically Linux or another Unix-like system at UCI) just as if it were your local machine.
- Command Execution: You can use SSH not just for interactive sessions but also to execute single commands on the remote server without fully logging in.
- Tunneling (Port Forwarding): SSH can securely tunnel other network protocols. This allows you to, for example, securely access a database or web service running on the remote server that isn’t directly exposed to the internet, or even route your web traffic through the remote server.
- Secure File Transfer: Protocols like SCP (Secure Copy Protocol) and SFTP (SSH File Transfer Protocol) run over SSH, providing encrypted methods for transferring files between your local machine and the remote server.
Why is SSH Essential at UCI?
At a large research university like UCI, computing resources are often centralized or specialized:
- Shared Lab Servers: Departments like ICS (Information and Computer Sciences) provide shared Linux servers (e.g.,
openlab.ics.uci.edu
) for students to complete coursework, learn Unix-like environments, and host projects. SSH is the standard way to access these. - High-Performance Computing (HPC): UCI operates powerful computing clusters for research that requires significant computational resources. Researchers connect to these clusters via SSH to submit jobs, manage data, and analyze results.
- Departmental Servers: Individual departments, labs, or research groups may maintain their own servers for specific software, datasets, or tasks. SSH provides secure access for authorized users.
- Web Development & Hosting: Students and staff managing websites hosted on UCI infrastructure might use SSH (often alongside SFTP/SCP) to upload files, manage configurations, and check logs.
- Remote Work & Access: SSH enables access to essential computing environments from anywhere with an internet connection – your dorm room, home, or even while traveling.
In essence, SSH is the secure gateway to a vast array of UCI’s digital infrastructure.
Who is This Guide For?
This guide is intended primarily for UCI students, faculty, and staff who are new to using SSH or the command line, or those who need a refresher. We assume you have basic computer literacy but may not have prior experience with terminal environments or remote server access. We will start with the fundamentals and gradually introduce more advanced concepts. Even if you have some experience, you might find the sections on SSH keys, configuration files, and troubleshooting helpful.
What We Will Cover
This comprehensive introduction aims to equip you with the knowledge and skills to confidently use SSH for accessing UCI resources. We will cover:
- Necessary prerequisites and software.
- Fundamental concepts behind SSH.
- Step-by-step instructions for making your first connection.
- Essential Linux/Unix commands for navigating the remote system.
- Methods for securely transferring files (SCP and SFTP).
- Setting up and using SSH keys for enhanced security and convenience.
- Using the SSH configuration file to simplify connections.
- Briefly touching upon advanced features like port forwarding and terminal multiplexers (
tmux
/screen
). - Crucial security best practices.
- Troubleshooting common connection problems.
- Specific considerations relevant to the UCI environment.
By the end of this article, you should be able to securely connect to UCI servers, navigate the remote environment, transfer files, and manage your connections effectively.
2. Prerequisites: Getting Ready to Connect
Before you can dive into using SSH, you need a few things in place.
Your UCI NetID and Password
Your UCI NetID is your unique electronic identifier at UCI (e.g., panteater
). This, along with your associated password, is typically used for initial authentication to many UCI systems, including those accessible via SSH. Keep your password secure and never share it. You may also encounter Duo Multi-Factor Authentication (MFA) prompts during SSH login, depending on the specific server’s configuration.
A Computer with Internet Access
You need a computer (desktop or laptop) connected to the internet. SSH works over network connections, so a stable internet connection is required.
An SSH Client (Built-in vs. Third-Party)
An SSH client is the software on your local computer that initiates the connection to the remote SSH server.
-
macOS and Linux: Good news! Most Linux distributions (like Ubuntu, Fedora, CentOS) and macOS come with a powerful OpenSSH client pre-installed. You can access it through the Terminal application.
- On macOS: Go to
Applications
->Utilities
->Terminal
. - On Linux: Find the “Terminal” or “Console” application in your application menu (location varies by distribution/desktop environment).
- On macOS: Go to
-
Windows: Historically, Windows didn’t include a built-in command-line SSH client, leading to the popularity of third-party tools. Now, you have several excellent options:
- Windows Terminal with OpenSSH Client (Recommended): Modern versions of Windows 10 and Windows 11 include an optional, installable OpenSSH client. When combined with the excellent Windows Terminal (available from the Microsoft Store), this provides a user experience very similar to macOS and Linux. To check if OpenSSH client is installed, open PowerShell or Command Prompt and type
ssh
. If it’s not found, you can usually install it via:Settings
->Apps
->Optional features
->Add a feature
-> Search for and install “OpenSSH Client”. - PuTTY: A free, popular, and long-standing graphical SSH client for Windows. It’s self-contained and doesn’t require installation (though an installer is available). It manages connections through a GUI but provides a terminal window once connected. It also includes related tools like
pscp
(for SCP) andpsftp
(for SFTP). Download from the official PuTTY website (www.chiark.greenend.org.uk/~sgtatham/putty/). - Windows Subsystem for Linux (WSL): WSL allows you to run a genuine Linux environment directly on Windows, including a native Linux OpenSSH client. This is a powerful option if you prefer working within a Linux environment. You can install distributions like Ubuntu from the Microsoft Store. Once inside your WSL distribution’s terminal, SSH works exactly as it does on Linux.
- Other Graphical Clients: Tools like MobaXterm (feature-rich terminal with X11 forwarding), Solar-PuTTY (tabbed interface for PuTTY), or file transfer clients with terminal capabilities (like Bitvise SSH Client) are also available.
- Windows Terminal with OpenSSH Client (Recommended): Modern versions of Windows 10 and Windows 11 include an optional, installable OpenSSH client. When combined with the excellent Windows Terminal (available from the Microsoft Store), this provides a user experience very similar to macOS and Linux. To check if OpenSSH client is installed, open PowerShell or Command Prompt and type
For consistency, this guide will primarily use the command-line syntax common to OpenSSH clients (macOS, Linux, Windows Terminal/OpenSSH, WSL). If using PuTTY, the connection details (hostname, username) are entered into its GUI configuration window before connecting.
Knowing Your Destination: UCI Hostnames
You need to know the address, or hostname, of the specific UCI server you want to connect to. This is like the web address for a server. Common examples include:
openlab.ics.uci.edu
(Shared Linux servers for ICS students)hpc.oit.uci.edu
(or similar – check official OIT HPC documentation for the current login node address)- Department-specific servers (e.g.,
linux.server.eng.uci.edu
,sampa.ps.uci.edu
– always verify the correct hostname with your department or instructor)
Your professor, TA, research advisor, or departmental IT support will provide the correct hostname(s) you are authorized to access. Do not guess hostnames.
3. Core Concepts: Understanding the Fundamentals
Before typing commands, let’s briefly understand what’s happening behind the scenes.
The Client-Server Model
SSH operates on a client-server architecture:
- SSH Client: The software on your local machine (e.g., the
ssh
command in your terminal, PuTTY) that initiates the connection request. - SSH Server (Daemon): A program running on the remote machine (e.g., the UCI server) that listens for incoming connection requests on a specific network port (usually port 22). It’s responsible for authenticating the client, establishing the encrypted connection, and executing the commands sent by the client. This server program is often called
sshd
(SSH Daemon).
When you run the ssh
command, your client reaches out across the network to the specified server’s port 22, initiating a negotiation process to establish a secure connection.
Authentication Methods
Before granting access, the SSH server needs to verify your identity. This is called authentication. The two primary methods are:
- Password Authentication: This is the simplest method. After initiating the connection, the server prompts you for your password associated with your username on the remote system (e.g., your UCI NetID password). Your client securely transmits the password over the encrypted connection for verification by the server. While straightforward, it’s susceptible to brute-force attacks (automated guessing of passwords) if strong passwords aren’t used, and requires you to type your password frequently.
- Public Key Authentication: This is a more secure and often more convenient method. It uses a pair of cryptographic keys: a private key (kept secret on your local machine) and a public key (placed on the remote server).
- When you connect, the server uses your public key to issue a challenge.
- Your SSH client uses your corresponding private key to correctly respond to the challenge, proving you possess the private key without ever transmitting the key itself.
- You typically protect your private key with a strong passphrase on your local machine.
- This method is highly resistant to brute-force attacks and can be automated for convenience (e.g., using an SSH agent). We will cover setting this up in detail later. Using SSH keys is strongly recommended.
UCI servers may support one or both methods. Some high-security systems might only allow key-based authentication.
Encryption: The “Secure” in Secure Shell
Once authentication is successful, SSH establishes an encrypted channel. All data exchanged between your client and the server – commands, output, file transfers – is scrambled using strong cryptographic algorithms (like AES, ChaCha20). This ensures:
- Confidentiality: No one listening on the network can read your data.
- Integrity: The data cannot be secretly modified in transit without detection.
SSH also verifies the server’s identity using a host key during the initial connection, preventing you from accidentally connecting to an imposter server (Man-in-the-Middle attack).
The Command Line Interface (CLI)
When you connect via SSH, you typically get access to the remote server’s command-line interface (CLI), often referred to as the shell. Common shells on UCI’s Linux servers include bash
(Bourne Again SHell) or zsh
(Z Shell).
The CLI is a text-based way to interact with the operating system. Instead of clicking icons and menus, you type commands and press Enter. The shell interprets these commands and executes them. While it might seem intimidating at first, the CLI is incredibly powerful, efficient, and scriptable, making it the standard for server administration and development work. We will cover essential commands shortly.
4. Your First Connection: Stepping Through the Process
Let’s connect to a UCI server using the command line. We’ll use password authentication first, as it’s the most straightforward initial method.
The Basic SSH Command Syntax
Open your Terminal (macOS/Linux/WSL) or SSH-enabled command prompt (Windows Terminal with OpenSSH). The basic syntax is:
bash
ssh your_ucinetid@hostname
Replace:
your_ucinetid
with your actual UCI NetID (e.g.,panteater
).hostname
with the actual hostname of the server you want to connect to (e.g.,openlab.ics.uci.edu
).
Example: To connect to OpenLab as user panteater
:
bash
ssh [email protected]
(PuTTY users: Enter [email protected]
in the “Host Name (or IP address)” field, ensure “SSH” is selected, and click “Open”.)
Finding the Right Hostname
As mentioned, get the correct hostname from your course materials, instructor, or departmental IT. Using an incorrect hostname will result in a “Could not resolve hostname” or similar error.
The Host Key Verification Prompt (Crucial Security Step)
The very first time you connect to a specific server from your computer, your SSH client will display a message similar to this:
The authenticity of host 'openlab.ics.uci.edu (128.195.xxx.xxx)' can't be established.
ED25519 key fingerprint is SHA256:AbCdEfGhIjKlMnOpQrStUvWxYz1234567890aBcDeF.
Are you sure you want to continue connecting (yes/no/[fingerprint])?
This is important! The SSH server presents its public host key to your client. Your client checks if it has seen this key before for this hostname. Since it’s the first time, it hasn’t.
- Why it matters: This step helps prevent Man-in-the-Middle (MitM) attacks, where an attacker might try to impersonate the real server to intercept your connection.
- What to do: Ideally, you would verify this “fingerprint” (a short, unique summary of the host key) against a known, trusted source (e.g., an official UCI webpage listing the server’s key fingerprint). In practice, this is often difficult. For standard UCI servers like OpenLab, it’s generally safe to assume the key presented on your first connection is legitimate if you typed the hostname correctly.
- Action: Type
yes
and press Enter.
Your SSH client will then store the server’s hostname and public host key in a file called ~/.ssh/known_hosts
on your local machine (~
represents your home directory). On subsequent connections, your client will automatically check if the key presented by the server matches the one stored in known_hosts
. If it matches, you won’t see this prompt again.
(PuTTY users: A similar pop-up window will appear asking whether to cache the host key. Click “Yes” or “Accept”.)
What to Do When a Host Key Changes
If you connect to a server you’ve connected to before, and suddenly get a BIG SCARY WARNING like this:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ED25519 key sent by the remote host is
SHA256:NewFingerprintXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.
Please contact your system administrator.
Add correct host key in /home/your_user/.ssh/known_hosts to get rid of this message.
Offending ED25519 key in /home/your_user/.ssh/known_hosts:5
remove with:
ssh-keygen -f "/home/your_user/.ssh/known_hosts" -R "openlab.ics.uci.edu"
ED25519 host key for openlab.ics.uci.edu has changed and you have requested strict checking.
Host key verification failed.
Do not ignore this! It means the host key presented by the server does not match the one stored in your known_hosts
file. This could mean:
- Man-in-the-Middle Attack: Someone is intercepting your connection (less likely on a campus network, but possible).
-
Legitimate Key Change: The server administrators have regenerated the server’s host key (e.g., after an OS upgrade, security policy change). This is common.
-
Action:
- First, verify: Check with official sources (OIT, departmental IT, system status pages) if a known key change occurred for that server.
- If legitimate: Follow the instructions in the warning message to remove the old key from your
known_hosts
file. The command is usually provided:
bash
ssh-keygen -f "/home/your_user/.ssh/known_hosts" -R "hostname"
# Example:
ssh-keygen -f "~/.ssh/known_hosts" -R "openlab.ics.uci.edu"
Replacehostname
with the actual server name. After removing the old key, try connecting again. You will get the “first connection” prompt again; typeyes
to accept the new key. - If suspicious or unsure: Do not connect. Contact OIT or your departmental IT support.
Authenticating with Your Password
After you accept the host key (on the first connection), the server will likely prompt you for your password:
bash
[email protected]'s password:
Type your UCI NetID password carefully and press Enter. Important: For security reasons, you will not see any characters (like asterisks *
or dots .
) appear on the screen as you type your password. This is normal. Just type it correctly and press Enter.
If required, you might also receive a Duo MFA prompt on your registered device (e.g., phone push notification, request for passcode). Approve the request or enter the passcode as needed.
Successfully Connected: The Remote Shell Prompt
If your password (and MFA, if applicable) is correct, you’ll be granted access. You will typically see:
- MOTD (Message of the Day): Information messages from the server administrators (e.g., system status, usage policies, scheduled maintenance). Read these!
-
The Shell Prompt: This indicates the server is ready to receive your commands. It usually looks something like this:
[panteater@openlab ~]$
or
panteater@openlab:~$
This prompt typically shows your
username
, thehostname
of the server you’re logged into, and your currentdirectory
(~
usually represents your home directory on the server). The$
or#
indicates whether you are a regular user ($
) or the root superuser (#
– you usually won’t be root on shared UCI servers).
You are now interacting with the remote server’s command line!
Disconnecting: exit
or logout
When you are finished with your session, it’s important to log out cleanly. Type:
bash
exit
or
bash
logout
Press Enter. This will terminate the SSH connection, and you will see a message like Connection to openlab.ics.uci.edu closed.
You are now back at your local machine’s command prompt. You can also often disconnect by pressing Ctrl+d
.
5. Essential Command Line Skills for Remote Work
Now that you’re connected, you need to know how to interact with the remote system using the command line. Most UCI servers run Linux or a Unix-like operating system. Here are some fundamental commands you’ll use constantly. Remember to press Enter after each command.
-
pwd
(Print Working Directory): Shows the full path of the directory you are currently in.
bash
[panteater@openlab ~]$ pwd
/home/panteater -
ls
(List Files and Directories): Lists the contents of the current directory.ls
: Basic listing.ls -l
: Long listing format (shows permissions, owner, size, modification date).ls -a
: Shows all files, including hidden files (those starting with a dot.
). Important for finding configuration files like.bashrc
or.ssh
.ls -h
: Used with-l
to show file sizes in human-readable format (e.g.,KB
,MB
,GB
).ls -lh
is very common.ls -t
: Sorts files by modification time, newest first.ls -r
: Reverses the order of the sort (e.g.,ls -ltr
lists oldest first in long format).ls <directory_name>
: Lists contents of a specific directory instead of the current one.
-
cd
(Change Directory): Moves you to a different directory.cd <directory_name>
: Moves into a subdirectory nameddirectory_name
.cd ..
: Moves up one level to the parent directory.cd
(orcd ~
): Moves to your home directory (e.g.,/home/panteater
).cd /path/to/directory
: Moves to an absolute path (starting from the root/
).cd -
: Moves to the previous directory you were in.
-
mkdir
(Make Directory): Creates a new directory.
bash
[panteater@openlab ~]$ mkdir my_project
[panteater@openlab ~]$ ls
my_project -
rmdir
(Remove Directory): Removes an empty directory.
bash
[panteater@openlab ~]$ rmdir my_project
If the directory is not empty,rmdir
will fail. -
rm
(Remove): Deletes files or directories. USE WITH EXTREME CAUTION! There is no undelete or recycle bin on the command line!rm <filename>
: Deletes a file.rm -r <directory_name>
: Recursively removes a directory and all its contents (files, subdirectories, everything). Double-check before usingrm -r
!rm -f <filename>
: Force removal without prompting (even more dangerous). Avoid unless necessary.rm -i <filename>
: Interactive mode, prompts for confirmation before each deletion (safer). Many systems aliasrm
torm -i
by default for safety.
-
cp
(Copy): Copies files or directories.cp <source_file> <destination_file>
: Copies a file.cp <source_file> <destination_directory>
: Copies a file into a directory.cp -r <source_directory> <destination_directory>
: Recursively copies a directory and its contents.
-
mv
(Move): Moves or renames files or directories.mv <source> <destination_directory>
: Moves a file or directory into another directory.mv <old_filename> <new_filename>
: Renames a file.mv <old_directoryname> <new_directoryname>
: Renames a directory.
-
Viewing File Contents:
cat <filename>
: Concatenates and displays the entire content of a file to the screen. Best for short files.less <filename>
: Displays file content one screenful at a time. Use arrow keys, PageUp/PageDown to navigate. Pressq
to quit. Highly recommended for viewing larger files.more <filename>
: Similar toless
, but older and less flexible. Press Spacebar for the next page,q
to quit.head <filename>
: Shows the first 10 lines of a file (use-n <number>
for a different number of lines).tail <filename>
: Shows the last 10 lines of a file (use-n <number>
for a different number). Usetail -f <filename>
to continuously watch a file for new lines (useful for log files).
-
Basic Text Editing: You’ll often need to edit configuration files or code.
nano <filename>
: A simple, beginner-friendly command-line text editor. Use arrow keys to move, commands listed at the bottom (e.g.,^X
meansCtrl+X
to exit,^O
meansCtrl+O
to save).vim <filename>
(orvi
): A very powerful but modal editor with a steeper learning curve. Widely available and efficient once learned.emacs <filename>
: Another powerful, extensible editor, often considered a rival to Vim.
For beginners,
nano
is usually the easiest to start with. Typenano my_file.txt
, type some text, pressCtrl+O
then Enter to save, andCtrl+X
to exit. -
Getting Help:
man <command>
: Displays the manual page (documentation) for a command (e.g.,man ls
). Pressq
to quit the manual viewer.<command> --help
: Many commands offer a brief summary of options with the--help
flag (e.g.,ls --help
).
-
Checking Disk Usage:
df -h
: Shows disk space usage for mounted filesystems in human-readable format. Useful to check if your home directory or project space is getting full.du -sh <directory>
: Shows the total size of a directory (and its contents) in human-readable format (-s
for summary,-h
for human-readable).du -sh *
in your home directory shows sizes of top-level items.
-
Finding Files:
find <start_directory> -name "<pattern>"
: Searches for files matching a pattern (e.g.,find . -name "*.txt"
finds all.txt
files in the current directory and below).find
is very powerful with many options (man find
).locate <pattern>
: Uses a pre-built database to quickly find files matching a pattern (faster thanfind
but database might not be perfectly up-to-date). Usesudo updatedb
to update the database if you have permissions (unlikely on shared servers).
-
Searching Within Files:
grep "<pattern>" <filename(s)>
: Searches for lines containing a specific pattern within one or more files (e.g.,grep "error" logfile.log
). Use-i
for case-insensitive search,-r
to search recursively in directories.grep
is extremely useful.
-
Managing Processes:
ps aux
orps -ef
: Lists currently running processes. Often combined withgrep
to find specific processes (e.g.,ps aux | grep python
).top
orhtop
(if installed): Shows an interactive, real-time view of running processes, CPU usage, memory usage, etc. Pressq
to quit.htop
is generally more user-friendly if available.kill <PID>
: Sends a signal to terminate a process (PID is the Process ID, found usingps
ortop
). Sends TERM signal by default.kill -9 <PID>
: Forcefully kills a process (sends KILL signal). Use as a last resort if a process is unresponsive.
Practice these commands. They are the building blocks for working effectively on any Linux/Unix system, including those at UCI.
6. Secure File Transfer: Moving Data To and From UCI Servers
You’ll frequently need to move files between your local computer and the UCI server (e.g., uploading assignments, downloading results, updating web pages). SSH provides two primary command-line tools for this, both leveraging the underlying secure SSH connection: SCP and SFTP.
SCP (Secure Copy Protocol)
SCP behaves much like the local cp
command but works across the network securely. Its syntax generally follows scp [options] source destination
.
-
Syntax Overview:
- Local file/directory: Just the path (e.g.,
myfile.txt
,/path/to/local/dir
). - Remote file/directory:
user@hostname:/path/to/remote/file_or_dir
- Local file/directory: Just the path (e.g.,
-
Copying from Local to Remote:
“`bash
# Copy a single file to your home directory on the server
scp my_assignment.pdf [email protected]:~Copy a single file to a specific directory on the server
scp report.docx [email protected]:/home/panteater/project_files/
On the remote path, ‘~’ is a shortcut for your home directory
scp data.csv [email protected]:~/data/
``
panteater
*(Remember to replaceand
openlab.ics.uci.edu`)* -
Copying from Remote to Local:
“`bash
# Copy a file from the server’s home directory to your current local directory (.)
scp [email protected]:~/results.txt .Copy a file from a specific server directory to a specific local directory
scp [email protected]:/home/panteater/output/final_plot.png /Users/MyUser/Downloads/
Copy a file from the server and rename it locally
scp [email protected]:~/config.backup ~/Documents/server_config_backup.txt
“` -
Copying Directories (
-r
option): Use the-r
(recursive) option to copy entire directories and their contents.
“`bash
# Upload a local directory ‘my_project’ to the server’s home directory
scp -r my_project [email protected]:~Download a remote directory ‘simulation_results’ to the local ‘Downloads’ folder
scp -r [email protected]:~/simulation_results ~/Downloads/
“` -
Specifying Ports (
-P
option – Note: Capital P): If the remote SSH server runs on a non-standard port (not 22), use-P
.
bash
scp -P 2222 local_file.zip [email protected]:~/backups/ -
Preserving Attributes (
-p
option): Preserves modification times, access times, and modes from the original file.
bash
scp -p important_script.sh user@server:~/scripts/
SCP is simple and effective for transferring specific files or directories when you know exactly what you want to move. Authentication works the same way as SSH (password or key).
SFTP (SSH File Transfer Protocol)
SFTP provides an interactive session for file transfer, more like an FTP client but running securely over SSH. It offers more commands than SCP, allowing you to browse the remote filesystem, rename files, create directories, etc., all within the SFTP session.
-
Starting an Interactive SFTP Session:
bash
sftp your_ucinetid@hostname
Example:
bash
sftp [email protected]
You’ll authenticate (password or key) and then see ansftp>
prompt. -
Navigating Local and Remote Systems: Inside the
sftp>
prompt:- Commands like
ls
,cd
,pwd
,mkdir
,rmdir
,rm
generally work on the remote system. - To perform these actions on your local system, prefix the command with
l
(local):lls
,lcd
,lpwd
. sftp> pwd
(Show remote working directory)sftp> lpwd
(Show local working directory)sftp> ls -l
(List remote files in long format)sftp> lls -l
(List local files in long format)sftp> cd project_data
(Change remote directory)sftp> lcd ~/MyLocalProject
(Change local directory)
- Commands like
-
Uploading Files (
put
/mput
):put <local_file> [remote_file]
: Uploads a single file. Ifremote_file
is omitted, uses the same name.
bash
sftp> put my_script.py
sftp> put report.pdf reports/final_report.pdfput -r <local_directory>
: Uploads a directory recursively (support varies; some clients requiremput
).mput *.txt
: Upload multiple files matching a pattern (e.g., all.txt
files).
-
Downloading Files (
get
/mget
):get <remote_file> [local_file]
: Downloads a single file.
bash
sftp> get server_output.log
sftp> get results/data.csv downloaded_data.csvget -r <remote_directory>
: Downloads a directory recursively (support varies; some clients requiremget
).mget *.dat
: Download multiple files matching a pattern.
-
Managing Remote Files:
mkdir <directory_name>
: Create remote directory.rmdir <directory_name>
: Remove empty remote directory.rm <filename>
: Delete remote file.rename <old_name> <new_name>
: Rename remote file.
-
Getting Help: Type
help
or?
at thesftp>
prompt to see available commands. -
Exiting SFTP: Type
exit
orquit
. -
Advantages of SFTP over SCP:
- Interactive browsing and file management.
- Ability to resume interrupted transfers (client/server support required).
- More commands available (rename, delete remote files, etc.).
Choosing Between SCP and SFTP
- Use SCP for quick, non-interactive transfers of known files or directories, especially in scripts.
- Use SFTP when you need to explore the remote filesystem, transfer multiple files interactively, rename/delete remote files, or potentially resume transfers.
Many graphical file transfer clients like FileZilla, Cyberduck (macOS/Windows), and WinSCP (Windows) use SFTP or SCP protocols underneath, providing a visual interface for these operations. However, learning the command-line tools is valuable for scripting and understanding the underlying process.
7. Enhancing Security and Convenience: SSH Key Authentication
While password authentication works, it has drawbacks: you need to type your password frequently, and passwords can be guessed or stolen. SSH Key Authentication is the preferred method for secure and convenient access.
Why Use SSH Keys?
- Enhanced Security: SSH keys are much longer and more complex than human-memorable passwords, making them extremely difficult to brute-force. A compromised password grants access; a compromised public key grants nothing. The private key must be present and, ideally, protected by a strong passphrase.
- Convenience: Once set up, you can often log in without typing your password every time (especially when used with an SSH agent, covered later). This is particularly useful for automated scripts or frequent connections.
- Industry Standard: Key-based authentication is the standard practice for secure server administration and access in professional environments. Some systems (like GitHub, many cloud providers, potentially some UCI HPC systems) require SSH keys.
How SSH Keys Work (Public/Private Key Pair)
SSH key authentication relies on asymmetric cryptography using a pair of mathematically linked keys:
- Private Key: This key is kept secret and must never be shared. It resides securely on your local computer (the SSH client). It’s used to mathematically “sign” or respond to challenges from the server.
- Public Key: This key can be freely shared and is placed on the remote computer(s) you want to access (the SSH server). It’s used by the server to verify the signatures/responses created by the corresponding private key.
The Authentication Flow:
- You initiate an SSH connection.
- The server recognizes you have a public key associated with your account (usually stored in
~/.ssh/authorized_keys
on the server). - The server generates a random challenge message and encrypts it using your public key. It sends this encrypted challenge to your client.
- Your SSH client receives the challenge. Only your corresponding private key can decrypt this message correctly.
- If your private key is protected by a passphrase, your client prompts you for it now.
- Once unlocked (if necessary), your client uses the private key to decrypt the challenge.
- Your client often combines the decrypted challenge with session information and computes a hash (a unique fingerprint). It sends this response back to the server.
- The server, knowing the original challenge and having your public key, can verify that the response could only have been generated by someone possessing the correct private key.
- If verification succeeds, you are authenticated without ever sending your password or private key over the network.
Generating Your SSH Key Pair (ssh-keygen
)
You generate the key pair on your local machine. Open your terminal (or Git Bash/WSL/PowerShell with OpenSSH on Windows).
bash
ssh-keygen -t ed25519 -C "[email protected] or description"
Let’s break down this command:
ssh-keygen
: The command to generate keys.-t ed25519
: Specifies the key type. Ed25519 is a modern, secure, and efficient algorithm, generally recommended over older RSA keys unless compatibility is an issue. If you need RSA for older systems, usessh-keygen -t rsa -b 4096
. (-b 4096
specifies a strong 4096-bit key length for RSA).-C "[email protected] or description"
: Adds a comment to the key file. This helps you identify the key later (e.g., “[email protected] – MacBook Pro”). It’s not functionally critical but good practice.
The command will then prompt you:
- Enter file in which to save the key (…/.ssh/id_ed25519): Press Enter to accept the default location (
~/.ssh/id_ed25519
for the private key,~/.ssh/id_ed25519.pub
for the public key). It’s best to use the default unless you have specific reasons to change it. - Enter passphrase (empty for no passphrase): CRITICAL STEP! Enter a strong, unique passphrase here. This passphrase encrypts your private key file on your local disk. If someone gains access to your computer and steals your private key file, they still need this passphrase to use it.
- Do NOT leave this empty! An unencrypted private key is a major security risk.
- Make it strong (long, complex, different from your login password).
- You will need to enter this passphrase the first time you use the key in a session (or add it to an SSH agent).
- Enter same passphrase again: Confirm your passphrase.
If successful, it will output something like:
Your identification has been saved in /home/your_user/.ssh/id_ed25519
Your public key has been saved in /home/your_user/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:SomeFingerprintText... [email protected]
The key's randomart image is:
+--[ED25519 256]--+
| . |
| + . |
| . B . |
| . * + . |
| . + S = . |
| . * B o . |
| o = * E . |
| = = o . . |
| . o . ..o..|
+----[SHA256]-----+
You now have two new files in your ~/.ssh
directory:
id_ed25519
: Your PRIVATE key (Keep secure! Never share!).id_ed25519.pub
: Your PUBLIC key (This is what you copy to servers).
(PuTTY users: Use the PuTTYgen
tool (usually installed alongside PuTTY) to generate keys. Select the desired key type (Ed25519 or RSA), click “Generate,” move the mouse to add randomness, enter a strong passphrase, and save both the public and private keys using the respective buttons. PuTTY uses its own .ppk
format for private keys.)
Copying Your Public Key to the UCI Server
The next step is to place the contents of your public key file (id_ed25519.pub
) into a specific file on the remote UCI server: ~/.ssh/authorized_keys
. This file lists all public keys that are authorized to log into your account.
-
The Easy Way:
ssh-copy-id
(Recommended)
Most Linux, macOS, and WSL systems have thessh-copy-id
utility, designed specifically for this task. It handles permissions correctly and appends the key without overwriting existing ones.bash
ssh-copy-id your_ucinetid@hostname
Example:
bash
ssh-copy-id [email protected]
It will:
1. Prompt you for your[email protected]
password (for this one-time setup).
2. Connect to the server.
3. Create the~/.ssh
directory on the server if it doesn’t exist (with correct permissions700
).
4. Append the contents of your local~/.ssh/id_ed25519.pub
file to the remote~/.ssh/authorized_keys
file (creating it if needed, with correct permissions600
).
5. Tell you it succeeded and suggest you try logging in.If you have multiple keys and want to specify which public key to copy, use the
-i
flag:
bash
ssh-copy-id -i ~/.ssh/my_other_key.pub [email protected] -
The Manual Way (If
ssh-copy-id
isn’t available or fails)
Ifssh-copy-id
isn’t installed on your local machine (less common now, but possible on some minimal systems or older Windows without full OpenSSH utils), you can do it manually. This requires careful handling of permissions.-
Display your public key on your local machine:
bash
cat ~/.ssh/id_ed25519.pub
This will output a long string starting withssh-ed25519
orssh-rsa
. Select and copy this entire line (including the comment at the end). -
SSH into the remote server using your password:
bash
ssh [email protected] -
On the remote server, create the
.ssh
directory if it doesn’t exist and set permissions:
bash
[panteater@openlab ~]$ mkdir -p ~/.ssh
[panteater@openlab ~]$ chmod 700 ~/.ssh
(mkdir -p
creates parent directories if needed and doesn’t error if it exists;chmod 700
sets permissions to read/write/execute only for the owner). -
Append your copied public key to the
authorized_keys
file and set its permissions:
bash
# Use echo and >> to append. Paste your public key inside the quotes.
[panteater@openlab ~]$ echo "PASTE_YOUR_PUBLIC_KEY_STRING_HERE" >> ~/.ssh/authorized_keys
[panteater@openlab ~]$ chmod 600 ~/.ssh/authorized_keys
(>>
appends to the file;>
would overwrite it!chmod 600
sets permissions to read/write only for the owner). -
Log out of the server:
bash
[panteater@openlab ~]$ exit
-
Connecting Using Your SSH Key
Now, try connecting to the server again:
bash
ssh [email protected]
This time, your SSH client should automatically find your private key (~/.ssh/id_ed25519
). It will likely prompt you for the passphrase you set for the key file:
Enter passphrase for key '/home/your_user/.ssh/id_ed25519':
Enter the passphrase (again, typing might be invisible). If correct, you should be logged in without being asked for your main UCI NetID password!
If it still asks for your account password instead of the key passphrase, something went wrong in the setup (see Troubleshooting below).
Troubleshooting Key Authentication
-
Still asks for password:
- Did
ssh-copy-id
complete successfully? - If manual copy: Did you paste the entire public key string correctly? Is the remote file named exactly
authorized_keys
? - Permissions! This is the most common issue. On the remote server, check:
ls -ld ~/.ssh
(Should bedrwx------
, meaning700
)ls -l ~/.ssh/authorized_keys
(Should be-rw-------
, meaning600
)- Your home directory (
ls -ld ~
) should not be world-writable.
Usechmod
on the server to fix permissions if needed (e.g.,chmod 700 ~/.ssh
,chmod 600 ~/.ssh/authorized_keys
).
- Check SSH server logs on the remote machine (often
/var/log/auth.log
or similar – you might needsudo
access, which you likely won’t have on shared servers; ask support if needed). - Use verbose output on your client:
ssh -v [email protected]
(or-vv
,-vvv
for more detail). Look for lines related to key authentication attempts.
- Did
-
Permission denied (publickey):
- Similar permission issues as above.
- Is the public key actually in the
authorized_keys
file on the server? - Is the SSH server configured to allow key authentication (
PubkeyAuthentication yes
in/etc/ssh/sshd_config
on the server – usually enabled by default)? - Are you using the correct private key on the client (if you have multiple)? You can specify one with
ssh -i ~/.ssh/specific_key user@host
.
Managing Multiple Keys
You might generate different keys for different purposes or different machines.
* Use descriptive comments (-C
) when generating.
* Use distinct filenames (e.g., ~/.ssh/id_ed25519_work
, ~/.ssh/id_ed25519_personal
).
* Use ssh-copy-id -i ~/.ssh/keyname.pub user@host
to copy specific public keys.
* Use ssh -i ~/.ssh/private_key_file user@host
to explicitly tell the client which private key to use for a connection.
* Use the SSH Config file (next section) to associate specific keys with specific hosts automatically.
8. Streamlining Connections: The SSH Config File
Typing ssh -i ~/.ssh/some_key -p 2222 [email protected]
repeatedly gets tedious. The SSH client configuration file lets you define shortcuts and default options for your connections.
What is ~/.ssh/config
?
This is a plain text file in your local ~/.ssh
directory where you can define connection parameters for different hosts. Each host or group of hosts can have its own set of options.
Basic Syntax
The file consists of Host
blocks. Each block starts with Host <alias_or_pattern>
and is followed by indented Keyword Value
pairs.
“`
This is a comment
Host
HostName
User
Port
Host
HostName
# Uses default user, port, and key settings unless specified
Wildcards can be used
Host *.department.uci.edu
User mydept_user
IdentityFile ~/.ssh/dept_key
Default settings for all hosts not otherwise matched
Host *
ServerAliveInterval 60
# Any global defaults
“`
Common Keywords:
Host
: Defines the alias or pattern this block applies to. You’ll use this alias with thessh
command (e.g.,ssh <short_alias>
).HostName
: The actual hostname or IP address to connect to.User
: The username to use for the connection.Port
: The port number the SSH server is listening on (defaults to 22).IdentityFile
: Specifies the path to the private key file to use for this host.IdentitiesOnly
: Set toyes
to prevent the client from trying default key files (~/.ssh/id_rsa
,~/.ssh/id_ed25519
, etc.) if anIdentityFile
is specified. Useful for hosts requiring specific keys.ServerAliveInterval
: Sends a keep-alive message to the server every N seconds to prevent disconnection due to inactivity (useful for firewalls/NATs that drop idle connections). Set to60
or120
.ServerAliveCountMax
: Number of keep-alive messages to send without response before disconnecting (defaults to 3).ForwardAgent yes/no
: Controls SSH agent forwarding (see next section). Default isno
.RequestTTY force/yes/no/auto
: Controls TTY allocation. Usuallyauto
is fine.LogLevel QUIET/FATAL/ERROR/INFO/VERBOSE/DEBUG
: Controls verbosity (like the-v
flags).
Creating Aliases for Easy Connections
This is the most common use. Instead of typing the full command, you define an alias.
Example:
“`config
~/.ssh/config
Host openlab
HostName openlab.ics.uci.edu
User panteater
IdentityFile ~/.ssh/id_ed25519_uci
Host hpc
HostName hpc.oit.uci.edu # Verify actual HPC hostname!
User panteater
IdentityFile ~/.ssh/id_ed25519_uci
Port 22 # Explicitly state default port if desired
“`
Now, instead of typing ssh [email protected]
, you can simply type:
bash
ssh openlab
And instead of ssh [email protected]
, type:
bash
ssh hpc
SCP and SFTP also use this config file!
bash
scp local_file.txt openlab:~/remote_dir/
sftp hpc
Specifying Different Keys for Different Hosts
If you use different keys for different systems:
“`config
Host github
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
IdentitiesOnly yes
Host uci-server
HostName specific.server.uci.edu
User myuciid
IdentityFile ~/.ssh/id_ed25519_uci
IdentitiesOnly yes
“`
Setting Default Options
Use Host *
at the end of the file to set defaults for all connections that don’t match a more specific block.
config
Host *
User panteater # Default user if not specified
ServerAliveInterval 120 # Keep connections alive
ConnectTimeout 10 # Timeout for establishing connection
Example Configurations
A more complete example:
“`config
~/.ssh/config
Default settings for all UCI connections
Host .uci.edu !github.com # Apply to .uci.edu, but NOT github.com
User panteater
IdentityFile ~/.ssh/id_ed25519_uci
ServerAliveInterval 120
Specific Host Aliases
Host openlab
HostName openlab.ics.uci.edu
# Inherits User, IdentityFile, ServerAliveInterval from *.uci.edu block
Host hpc-login
HostName login.hpc.uci.edu # Fictional – use actual name
# Inherits User, IdentityFile, ServerAliveInterval
Host deptserv
HostName server.eng.uci.edu # Fictional – use actual name
User eng_panteater # Override default user
Port 2222 # Connect on a non-standard port
# Inherits IdentityFile, ServerAliveInterval
External service using a different key
Host github
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
IdentitiesOnly yes # Don’t try the UCI key for GitHub
Catch-all for anything else
Host *
ConnectTimeout 10
# Add any other global defaults here
# Note: The first matching ‘Host’ block is used for parameters.
# More specific hostnames/aliases should come before wildcard entries.
“`
Permissions for ~/.ssh/config
Like your private keys, your SSH config file should have restricted permissions. It doesn’t need to be as strict as the private key, but good practice is 600
(read/write for owner only).
bash
chmod 600 ~/.ssh/config
The SSH config file is incredibly powerful for organizing and simplifying your remote connections.
9. Advanced SSH Techniques for Power Users
Once you’re comfortable with the basics, SSH offers more advanced features.
Running Remote Commands Directly
You don’t always need an interactive shell. You can execute a single command remotely and see its output locally.
bash
ssh <host_alias_or_full_spec> '<command_to_run>'
Examples:
“`bash
Check disk usage on openlab home directory
ssh openlab ‘df -h ~’
List files in a specific directory on hpc
ssh hpc ‘ls -l /data/panteater/results’
Remotely monitor a log file (output streams until Ctrl+C)
ssh openlab ‘tail -f /var/log/somelog.log’
Run a script remotely
ssh hpc ‘~/scripts/run_simulation.sh –input data.txt’
“`
The command is executed in the user’s default shell on the remote server. Output (stdout and stderr) is sent back to your local terminal.
SSH Agent: Managing Key Passphrases
Entering your key passphrase every time you connect can be annoying, especially if you connect frequently or use SSH in scripts. An SSH Agent is a background program that securely holds your decrypted private keys in memory, allowing your SSH client to use them without prompting you for the passphrase repeatedly.
-
Starting the Agent: The agent needs to be running in your current session. How you start it depends on your OS and environment. Often, it’s started automatically by your desktop environment. If not, you can start it manually:
bash
eval $(ssh-agent -s)
This starts the agent and sets environment variables (SSH_AUTH_SOCK
,SSH_AGENT_PID
) so yourssh
client can find it. You typically only need to do this once per login session (e.g., in your.bash_profile
or.zshrc
). -
Adding Keys (
ssh-add
): You need to add your private key(s) to the agent and provide the passphrase once.
bash
ssh-add ~/.ssh/id_ed25519_uci
It will prompt for the passphrase forid_ed25519_uci
. Once added, the agent holds the decrypted key.ssh-add -l
: List keys currently held by the agent.ssh-add -D
: Delete all keys from the agent.ssh-add
(with no arguments): Adds default keys (~/.ssh/id_rsa
,~/.ssh/id_ed25519
, etc.).
-
Connecting: Now, when you
ssh
orscp
orsftp
, the client will automatically check the agent for a suitable key. If found, it uses the key from the agent without prompting for the passphrase.
Security Considerations (Agent Forwarding):
SSH allows agent forwarding (ssh -A
or ForwardAgent yes
in config). This lets you use your local SSH agent to authenticate for connections made from the remote server (e.g., logging from server1
to server2
using the key stored on your laptop’s agent).
Use -A
with caution! If the remote server (server1
) is compromised, an attacker could potentially use your forwarded agent connection to access other servers (server2
) as you. Only use agent forwarding when connecting to servers you trust completely.
Port Forwarding (Tunneling)
SSH can create secure tunnels for other TCP/IP connections. This is useful for accessing services that are not directly exposed to the internet or for securing otherwise unencrypted traffic.
-
Local Port Forwarding (
-L
)- Concept: Makes a service running on the remote network accessible on a port on your local machine.
- Syntax:
ssh -L <local_port>:<destination_host>:<destination_port> user@ssh_server
- Explanation:
<local_port>
: The port number you will connect to on your local machine (e.g.,8080
).<destination_host>
: The hostname or IP address of the final destination service, as seen from the ssh_server. This might belocalhost
(if the service runs on the SSH server itself) or another machine on the remote network (e.g.,internal-db.department.uci.edu
).<destination_port>
: The port the final destination service is listening on (e.g.,3306
for MySQL,80
for HTTP).user@ssh_server
: The SSH server you are connecting through.
- Use Case Example: Accessing a database (
internal-db.uci.edu
port3306
) that only allows connections from within the UCI network, viaopenlab
.
bash
ssh -L 8888:internal-db.uci.edu:3306 [email protected]
While this SSH connection is active, connecting your local database client tolocalhost
on port8888
will securely tunnel the traffic throughopenlab
tointernal-db.uci.edu:3306
. Keep the SSH session running in the background (add-fN
flags:ssh -fN -L ...
to run in background without executing remote command).
-
Remote Port Forwarding (
-R
)- Concept: Makes a service running on your local machine (or your local network) accessible on a port on the remote SSH server.
- Syntax:
ssh -R <remote_port>:<destination_host>:<destination_port> user@ssh_server
- Explanation:
<remote_port>
: The port number that will be opened on thessh_server
. Connections to this port on the server will be forwarded.<destination_host>
: The hostname or IP address of the service to forward to, usuallylocalhost
(meaning the service on your local machine).<destination_port>
: The port the local service is listening on.
- Use Case Example: Temporarily showing a web app running on your laptop (
localhost:5000
) to a colleague who can accessopenlab
.
bash
ssh -R 9090:localhost:5000 [email protected]
While this is active, your colleague could potentially accesshttp://openlab.ics.uci.edu:9090
(server firewall permitting – often restricted by default for security) and their connection would be tunneled back tolocalhost:5000
on your laptop.
-
Dynamic Port Forwarding / SOCKS Proxy (
-D
)- Concept: Creates a SOCKS proxy on your local machine. Applications configured to use this proxy will have their traffic securely tunneled through the remote SSH server.
- Syntax:
ssh -D <local_port> user@ssh_server
- Explanation:
<local_port>
: The local port number the SOCKS proxy will listen on (e.g.,1080
).
- Use Case Example: Securely browsing the web as if you were originating from the UCI network (accessing library resources, internal sites), or bypassing local network restrictions.
bash
ssh -fN -D 1080 [email protected]
Then configure your web browser’s proxy settings to use a SOCKS5 proxy atlocalhost
port1080
. All browser traffic will then go through the encrypted SSH tunnel viaopenlab
.
Port forwarding is powerful but requires understanding network concepts. Always ensure you’re not violating security policies.
Keeping Connections Alive
Network devices (firewalls, NAT routers) sometimes drop idle TCP connections. If your SSH session disconnects frequently during periods of inactivity:
-
Client-Side (Your Config): Use
ServerAliveInterval
in your~/.ssh/config
(as shown previously).
config
Host *
ServerAliveInterval 120
This makes your client send a null packet every 120 seconds, keeping the connection state active. -
Server-Side (Admin Controlled): Admins can configure
ClientAliveInterval
andClientAliveCountMax
in the server’ssshd_config
. You usually don’t control this on shared UCI servers.
Terminal Multiplexers: tmux
and screen
What happens if your SSH connection drops while a long-running process (like a compilation, simulation, or large data transfer) is executing? The process usually gets terminated. Terminal multiplexers solve this.
tmux
and screen
are programs that run on the remote server and allow you to:
- Persistent Sessions: Start a session, run commands within it, and then detach from the session, leaving it running in the background on the server even if you log out or get disconnected. You can later reattach to the same session and find your programs still running exactly where you left off.
-
Multiple Windows/Panes: Manage multiple shell prompts or programs within a single terminal window (like tabs or split screens within your SSH connection).
-
Why Use Them? Essential for any task that takes more than a few minutes to run, or if you have an unstable internet connection. Also great for organizing your workspace on the remote server.
-
Brief Introduction to
tmux
(Often preferred, more modern):- Start:
tmux
ortmux new -s <session_name>
(e.g.,tmux new -s mywork
) - Run Commands: Use the shell as normal inside
tmux
. - Detach: Press
Ctrl+b
(the prefix key), then pressd
(detach). You’ll return to the normal shell prompt, but thetmux
session continues in the background. - List Sessions:
tmux ls
- Reattach:
tmux attach
ortmux attach -t <session_name>
(e.g.,tmux attach -t mywork
) - Inside
tmux
:Ctrl+b c
: Create a new window (like a tab).Ctrl+b n
: Next window.Ctrl+b p
: Previous window.Ctrl+b %
: Split pane vertically.Ctrl+b "
: Split pane horizontally.Ctrl+b <arrow_keys>
: Navigate between panes.Ctrl+b x
: Kill current pane.Ctrl+b d
: Detach session.
- Terminate Session: Inside the session, type
exit
in all panes/windows, or usetmux kill-session -t <session_name>
.
- Start:
-
Brief Introduction to
screen
(Older, widely available):- Start:
screen
orscreen -S <session_name>
- Run Commands: Use the shell as normal.
- Detach: Press
Ctrl+a
, then pressd
. - List Sessions:
screen -ls
- Reattach:
screen -r
orscreen -r <session_name_or_pid>
- Inside
screen
: (Prefix key isCtrl+a
)Ctrl+a c
: Create window.Ctrl+a n
: Next window.Ctrl+a p
: Previous window.Ctrl+a d
: Detach.
- Terminate Session:
exit
in all windows, orscreen -X -S <session_name_or_pid> quit
.
- Start:
Learning tmux
or screen
is highly recommended for anyone doing serious work over SSH.
10. Security Best Practices for SSH
Security is paramount when accessing remote systems. Follow these practices:
- Always Use Strong Passphrases for Keys: Protect your private keys with robust passphrases. An unencrypted private key is a major liability if your local machine is compromised.
- Prefer SSH Keys Over Password Authentication: Keys are significantly more secure against brute-force attacks. Disable password authentication on servers you control, if possible (unlikely on shared UCI servers, but good practice).
- Protect Your Private Keys:
- Permissions: Ensure your private key file (
~/.ssh/id_*
) has permissions600
(read/write only for you). SSH clients often refuse to use keys with insecure permissions. - Never Share: Do not copy your private key to other machines or give it to anyone. Generate separate keys for different client machines if needed.
- Backup Securely: If you back up your private key, ensure the backup is encrypted.
- Permissions: Ensure your private key file (
- Verify Host Keys Diligently: Pay attention to the host key verification prompt on first connection and especially to warnings about changed host keys. Verify changes through official channels before accepting.
- Keep Software Updated: Keep your local SSH client, operating system, and any related tools (like PuTTY) updated to patch known vulnerabilities. Ensure the server-side software is also maintained (usually handled by UCI admins).
- Use Firewalls: Use a firewall on your local machine. Understand that UCI servers are also protected by network firewalls; you might need VPN access for some resources or encounter blocks if connecting from unexpected locations.
- Be Cautious with Agent Forwarding (
-A
): Only forward your SSH agent to servers you fully trust, as a compromised server could potentially misuse the forwarded connection. - Understand Permissions on
~/.ssh
Directory: Your~/.ssh
directory on both client and server should typically have permissions700
(read/write/execute only for you). Incorrect permissions can break key authentication. - Log Out When Finished: Use
exit
orlogout
to close your SSH sessions when you are done. - Consider Multi-Factor Authentication (MFA/2FA): If UCI requires Duo or another MFA for SSH logins, comply with the setup. MFA adds a significant layer of security, even if your password or key is compromised.
11. Troubleshooting Common SSH Issues at UCI
Even with careful setup, you might encounter connection problems. Here are some common issues and how to approach them:
-
ssh: connect to host openlab.ics.uci.edu port 22: Connection refused
- Meaning: Your client reached the server’s IP address, but the server actively refused the connection on that port.
- Causes:
- SSH server daemon (
sshd
) is not running on the remote host. (Server issue) - A firewall (either on the server or network path) is blocking your connection to port 22. (Are you on campus Wi-Fi? VPN? Home network?)
- You typed the wrong hostname, leading to the wrong IP address where nothing is listening. (Double-check hostname)
- You specified the wrong port (
-p
option). (Unlikely for standard UCI servers)
- SSH server daemon (
- Troubleshooting: Verify hostname. Check UCI system status pages or OIT announcements. Try connecting from a different network (e.g., campus vs. home, with/without VPN) to isolate firewall issues. Contact support if it persists.
-
Permission denied (publickey,password).
orPermission denied (publickey).
- Meaning: You connected successfully, but failed to authenticate. The methods listed (e.g.,
publickey
,password
) are the ones that were tried and failed. - Causes:
- Password: Incorrect UCI NetID password entered. Caps Lock? Typos?
- Public Key:
- SSH key pair not set up correctly (public key missing/incorrect on server).
- Incorrect permissions on
~/.ssh
directory or~/.ssh/authorized_keys
file on the server. (Must be700
and600
respectively). - Incorrect permissions on your private key file (
~/.ssh/id_*
) on your client. (Must be600
). - Client is offering the wrong key (if you have multiple). Use
ssh -i path/to/correct_key ...
or check SSH config. - Passphrase for the key entered incorrectly (if using agent, try
ssh-add
again).
- Account Issue: Your UCI NetID account might be locked, expired, or disabled on that specific server.
- MFA Issue: If Duo MFA is required, failure to respond to the prompt correctly.
- Server Config: Server might be configured not to allow password auth, or only allow specific users/groups.
- Troubleshooting: Carefully retype password. Double-check key setup steps (permissions!). Use
ssh -v
orssh -vvv
to see detailed authentication attempts. Check account status. Verify MFA method.
- Meaning: You connected successfully, but failed to authenticate. The methods listed (e.g.,
-
Host key verification failed.
orWARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
- Meaning: The host key presented by the server does not match the one stored in your
~/.ssh/known_hosts
file. - Causes: Legitimate server key change (common) OR potential Man-in-the-Middle attack (rare but serious).
- Troubleshooting: Do not blindly accept. Verify with OIT/departmental IT if a key change was expected. If confirmed legitimate, remove the old key using the
ssh-keygen -R hostname
command provided in the error message, then reconnect and accept the new key. If unsure, do not connect and report it.
- Meaning: The host key presented by the server does not match the one stored in your
-
ssh: connect to host some.server.uci.edu port 22: Connection timed out
- Meaning: Your client sent connection requests, but received no reply at all within the timeout period.
- Causes:
- Server is down or completely unresponsive.
- Network issue between you and the server (e.g., intermediate router down, DNS resolution failure).
- Firewall silently dropping your packets (rather than actively refusing).
- Incorrect hostname leading to a non-existent or unreachable IP.
- Troubleshooting: Check hostname spelling. Try
ping hostname
ortraceroute hostname
(if allowed by firewalls) to test basic network connectivity. Check UCI system status. Try from a different network.
-
Slow Connection / Lag:
- Causes: High network latency between you and UCI. High CPU or memory load on the remote server (especially shared systems like OpenLab). Your own computer is slow. Network bandwidth limitations.
- Troubleshooting: Use
ping hostname
to check latency. Usetop
orhtop
on the remote server to check its load. Check your local network speed. Little can be done about fundamental network latency, but avoid large graphical transfers over slow links.
-
Received disconnect from ...: 2: Too many authentication failures
- Meaning: Your client tried too many different authentication methods (e.g., multiple keys, then password) that failed, and the server disconnected you as a security measure.
- Causes: Often happens if you have many private keys in
~/.ssh
and the client tries them all before getting to the correct one or the password. - Troubleshooting: Use
ssh -v
to see which methods are being tried. Explicitly specify the correct key withssh -i path/to/key ...
. UseIdentitiesOnly yes
in your~/.ssh/config
for the host to prevent trying default keys. Ensure your~/.ssh/config
points to the correct key for the host.
When encountering issues, verbose mode (ssh -v
, -vv
, or -vvv
) is your best friend, providing detailed insight into the connection and authentication process.
12. UCI-Specific Considerations
While SSH is standard, keep these UCI-specific points in mind:
- Official Documentation: Always prioritize official documentation from UCI OIT (Office of Information Technology) or your specific school/department’s IT support. Hostnames, access policies, required software (like VPN clients), and support contacts can be found there. Documentation links might be on OIT’s website, your school’s IT page (e.g., ICS Computing Support), or HPC websites.
- Specific Hostnames: Get the exact, current hostname for the resource you need.
openlab.ics.uci.edu
is common for ICS, but HPC clusters (checkhpc.oit.uci.edu
resources) and departmental servers will have unique names. Do not rely solely on examples in this guide, as they may become outdated. - Authentication Policies (MFA): Be prepared for Duo Multi-Factor Authentication. Ensure your Duo account is set up and you know how to respond to prompts during SSH login if required by the specific server. Follow OIT’s instructions for Duo.
- Software Environment: The software available on remote servers (
gcc
,python
,java
,matlab
, specific scientific libraries) varies. Use commands likewhich <program>
,module avail
(common on HPC),apt list --installed
(Debian/Ubuntu), orrpm -qa
(RedHat/CentOS) to see what’s installed. You might need to load modules (module load <modulename>
) on HPC systems to access certain software. - Resource Limits and Usage Policies: Shared systems like OpenLab and HPC clusters have usage policies and resource limits (CPU time, memory usage, disk space quotas). Be a good citizen:
- Don’t run computationally intensive tasks on login nodes (use compute nodes on HPC via the job scheduler like Slurm).
- Monitor your disk usage (
df -h
,du -sh ~
). - Clean up temporary files.
- Adhere to any job submission guidelines on HPC.
- Read the Message of the Day (MOTD) for announcements.
Violating policies can lead to account suspension.
13. Conclusion: Your Journey with SSH at UCI
You’ve now journeyed through the fundamentals and practicalities of using the SSH command line to access UCI’s computing resources. We’ve covered the core concepts, making connections, essential navigation and file management commands, secure file transfer with SCP and SFTP, the security and convenience of SSH keys, streamlining with the config file, advanced techniques like port forwarding and terminal multiplexers, crucial security practices, and troubleshooting common issues.
SSH is more than just a tool; it’s your secure portal to powerful computing environments essential for coursework, research, and development at UCI. The command line, while initially perhaps unfamiliar, offers unparalleled efficiency and control once mastered.
Don’t be intimidated! The key is practice. Log in to OpenLab or another server you have access to. Navigate directories. View files. Try editing a file with nano
. Transfer a test file using scp
or sftp
. Set up SSH keys – the security benefits are well worth the initial effort. Explore tmux
or screen
for managing longer tasks.
This guide provides a solid foundation, but the world of SSH and the command line is vast. Use the man
pages, search online for specific command usage, and most importantly, refer to the official UCI OIT and departmental IT documentation for the most accurate and up-to-date information regarding specific servers, policies, and support channels at UCI.
Welcome to the powerful world of remote command-line access. Happy connecting!