Search code examples
linuxmacosunixshellclipboard

How to send data to local clipboard from a remote SSH session


Most Unix-like systems have a command that will let you pipe/redirect output to the local clipboard/pasteboard, and retrieve from same. On OS X, these commands are

pbcopy, pbpaste 

Is there a way to replicate this functionality while SSHed into another server? That is,

  1. I'm using Computer A.
  2. I open a terminal window
  3. I SSH to Computer B
  4. I run a command on Computer B
  5. The output of Computer B is redirected or automatically copied to Computer A's clipboard.

And yes, I know I could just (shudder) use my mouse to select the text from the command, but I've gotten so used to the workflow of pipping output directly to the clipboard that I want the same for my remote sessions.

Code is useful, but general approaches are appreciated as well.


Solution

  • I'm resurrecting this thread because I've been looking for the same kind of solution, and I've found one that works for me. It's a minor modification to a suggestion from OSXDaily.

    In my case, I use Terminal on my local OS X machine to connect to a Linux server via SSH. Like the OP, I wanted to be able to transfer small bits of text from terminal to my local clipboard, using only the keyboard.

    The essence of the solution:

    commandThatMakesOutput | ssh desktop pbcopy
    

    When run in an SSH session to a remote computer, this command takes the output of commandThatMakesOutput (e.g., ls, pwd) and pipes the output to the clipboard of the local computer (the name or IP of "desktop"). In other words, it uses nested SSH: you're connected to the remote computer via one SSH session, you execute the command there, and the remote computer connects to your desktop via a different SSH session and puts the text to your clipboard.

    It requires your desktop to be configured as an SSH server (which I leave to you and Google). It's much easier if you've set up ssh keys to facilitate fast ssh usage, preferably using a per-session passphrase, or whatever your security needs require.

    Other examples:

    ls  | ssh desktopIpAddress pbcopy
    pwd | ssh desktopIpAddress pbcopy
    

    For convenience, I've created a Bash file to shorten the text required after the pipe:

    #!/bin/bash
    ssh desktop pbcopy
    

    In my case, I'm using a specially-named key.

    I saved it with the file name cb (my mnemonic (ClipBoard). Put the script somewhere in your path, make it executable and voilà:

    ls | cb