Skip to main content

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 at 192.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
  • 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.
  • 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.
  • Using Key-Based Authentication

    Avoid password prompts by using SSH keys.

    Setup:

    1. Generate a key pair locally:
    ssh-keygen -t rsa -b 4096
    • Press Enter for defaults (saves to ~/.ssh/id_rsa).

    1. Copy the public key to the remote server:
    ssh-copy-id alice@192.168.1.100
    • Enter the password once to set it up.

    1. 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 like ServerAliveInterval 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.

Common Options

OptionDescription
-pSpecify a port
-vVerbose output for debugging
-iSpecify an identity file (e.g., -i ~/.ssh/mykey)
-oSet configuration options
-XEnable X11 forwarding (GUI apps)
-tForce a TTY (e.g., for sudo remotely)