ssh command
ssh
- OpenSSH remote login client
The ssh
command in Linux (Secure Shell) is a powerful tool used to securely connect to and manage remote systems over a network. It provides an encrypted connection for running commands, transferring files, or accessing a remote shell.
Usage: ssh [options] [user@]hostname [command]
user
: The username on the remote system (optional if same as local user).hostname
: The remote machine’s IP address or domain name.command
: An optional command to run remotely (if omitted, you get a shell).options
: Flags that modify how ssh behaves.
Examples
-
Basic Connection
Connect to a remote machine with your username and its hostname or IP.
ssh alice@192.168.1.100
- Connects as user
alice
to the machine at192.168.1.100
. - You’ll be prompted for
alice
’s password unless key-based authentication is set up.
Default User:
If your local username matches the remote one:
ssh 192.168.1.100
- Connects as user
-
Running a Remote Command
Execute a single command on the remote system without starting a full shell.
ssh alice@192.168.1.100 "ls -l"
- Runs
ls -l
on the remote machine and displays the output locally. - The session closes after the command finishes.
- Runs
-
Specifying a Port
Use
-p
to connect to a non-default SSH port (default is 22).ssh -p 2222 alice@192.168.1.100
- Connects to port
2222
instead of 22.
- Connects to port
-
Using Key-Based Authentication
Avoid password prompts by using SSH keys.
Setup:
- Generate a key pair locally:
ssh-keygen -t rsa -b 4096
-
Press
Enter
for defaults (saves to~/.ssh/id_rsa
).
- Copy the public key to the remote server:
ssh-copy-id alice@192.168.1.100
-
Enter the password once to set it up.
- Connect:
ssh alice@192.168.1.100
- No password needed now.
-
Verbose Output
Use
-v
(verbose) to debug connection issues.ssh -v alice@192.168.1.100
- Shows detailed steps (e.g., authentication attempts).
-
Keeping Sessions Alive
Use
-o
to set options likeServerAliveInterval
to prevent timeouts.ssh -o ServerAliveInterval=60 alice@192.168.1.100
- Sends a keep-alive signal every 60 seconds.
-
SSH Config File
Simplify connections with a
~/.ssh/config
file.Edit
~/.ssh/config
:Host myserver
HostName 192.168.1.100
User alice
Port 2222- Then connect with:
ssh myserver
- No need to type the full command.
- Then connect with:
Common Options
Option | Description |
---|---|
-p | Specify a port |
-v | Verbose output for debugging |
-i | Specify an identity file (e.g., -i ~/.ssh/mykey ) |
-o | Set configuration options |
-X | Enable X11 forwarding (GUI apps) |
-t | Force a TTY (e.g., for sudo remotely) |