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

Alan Storm picture Alan Storm · Jul 20, 2009 · Viewed 77.8k times · Source

Borderline ServerFault question, but I'm programming some shell scripts, so I'm trying here first :)

Most *nixes 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 anyway 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.

Answer

Dominykas Mostauskis picture Dominykas Mostauskis · Sep 19, 2013

My favorite way is ssh [remote-machine] "cat log.txt" | xclip -selection c. This is most useful when you don't want to (or can't) ssh from remote to local.

Edit: on Cygwin ssh [remote-machine] "cat log.txt" > /dev/clipboard.

Edit: A helpful comment from nbren12:

It is almost always possible to setup a reverse ssh connection using SSH port forwarding. Just add RemoteForward 127.0.0.1:2222 127.0.0.1:22 to the server's entry in your local .ssh/config, and then execute ssh -p 2222 127.0.0.1 on the remote machine, which will then redirect the connection to the local machine. – nbren12