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

98,505

Solution 1

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 OSX Daily.

In my case, I use Terminal on my local OSX 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 voila:

ls | cb

Solution 2

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

Solution 3

Found a great solution that doesn't require a reverse ssh connection!

You can use xclip on the remote host, along with ssh X11 forwarding & XQuartz on the OSX system.

To set this up:

  1. Install XQuartz (I did this with soloist + pivotal_workstation::xquartz recipe, but you don't have to)
  2. Run XQuartz.app
  3. Open XQuartz Preferences (kb_command+,)
  4. Make sure "Enable Syncing" and "Update Pasteboard when CLIPBOARD changes" are checked XQuartz Preferences window example
  5. ssh -X remote-host "echo 'hello from remote-host' | xclip -selection clipboard"

Solution 4

Reverse tunnel port on ssh server

All the existing solutions either need:

  • X11 on the client (if you have it, xclip on the server works great) or
  • the client and server to be in the same network (which is not the case if you're at work trying to access your home computer).

Here's another way to do it, though you'll need to modify how you ssh into your computer.

I've started using this and it's nowhere near as intimidating as it looks so give it a try.

Client (ssh session startup)

ssh [email protected] -R 2000:localhost:2000

(hint: make this a keybinding so you don't have to type it)

Client (another tab)

nc -l 2000 | pbcopy

Note: if you don't have pbcopy then just tee it to a file.

Server (inside SSH session)

cat some_useful_content.txt | nc localhost 2000

Other notes

Actually even if you're in the middle of an ssh session there's a way to start a tunnel but i don’t want to scare people away from what really isn’t as bad as it looks. But I'll add the details later if I see any interest

Solution 5

There are various tools to access X11 selections, including xclip and XSel. Note that X11 traditionally has multiple selections, and most programs have some understanding of both the clipboard and primary selection (which are not the same). Emacs can work with the secondary selection too, but that's rare, and nobody really knows what to do with cut buffers...

$ xclip -help
Usage: xclip [OPTION] [FILE]...
Access an X server selection for reading or writing.

  -i, -in          read text into X selection from standard input or files
                   (default)
  -o, -out         prints the selection to standard out (generally for
                   piping to a file or program)
  -l, -loops       number of selection requests to wait for before exiting
  -d, -display     X display to connect to (eg localhost:0")
  -h, -help        usage information
      -selection   selection to access ("primary", "secondary", "clipboard" or "buffer-cut")
      -noutf8      don't treat text as utf-8, use old unicode
      -version     version information
      -silent      errors only, run in background (default)
      -quiet       run in foreground, show what's happening
      -verbose     running commentary

Report bugs to <[email protected]>
$ xsel -help
Usage: xsel [options]
Manipulate the X selection.

By default the current selection is output and not modified if both
standard input and standard output are terminals (ttys).  Otherwise,
the current selection is output if standard output is not a terminal
(tty), and the selection is set from standard input if standard input
is not a terminal (tty). If any input or output options are given then
the program behaves only in the requested mode.

If both input and output is required then the previous selection is
output before being replaced by the contents of standard input.

Input options
  -a, --append          Append standard input to the selection
  -f, --follow          Append to selection as standard input grows
  -i, --input           Read standard input into the selection

Output options
  -o, --output          Write the selection to standard output

Action options
  -c, --clear           Clear the selection
  -d, --delete          Request that the selection be cleared and that
                        the application owning it delete its contents

Selection options
  -p, --primary         Operate on the PRIMARY selection (default)
  -s, --secondary       Operate on the SECONDARY selection
  -b, --clipboard       Operate on the CLIPBOARD selection

  -k, --keep            Do not modify the selections, but make the PRIMARY
                        and SECONDARY selections persist even after the
                        programs they were selected in exit.
  -x, --exchange        Exchange the PRIMARY and SECONDARY selections

X options
  --display displayname
                        Specify the connection to the X server
  -t ms, --selectionTimeout ms
                        Specify the timeout in milliseconds within which the
                        selection must be retrieved. A value of 0 (zero)
                        specifies no timeout (default)

Miscellaneous options
  -l, --logfile         Specify file to log errors to when detached.
  -n, --nodetach        Do not detach from the controlling terminal. Without
                        this option, xsel will fork to become a background
                        process in input, exchange and keep modes.

  -h, --help            Display this help and exit
  -v, --verbose         Print informative messages
  --version             Output version information and exit

Please report bugs to <[email protected]>.

In short, you should try xclip -i/xclip -o or xclip -i -sel clip/xclip -o -sel clip or xsel -i/xsel -o or xsel -i -b/xsel -o -b, depending on what you want.

Share:
98,505

Related videos on Youtube

Alan Storm
Author by

Alan Storm

Portland based Web Developer/Programmer/Engineer. Projects include No Frills Magento Layout, the only Magento layout book you'll ever need and Commerce Bug, the debugging extension for the Magento Ecommerce system. If you're interested in low cost, in-depth mentoring/tutoring, checkout my Patreon campaign.

Updated on September 11, 2021

Comments

  • Alan Storm
    Alan Storm over 2 years

    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.

    • Pablo Bianchi
      Pablo Bianchi over 2 years
      I answered a similar question here, alike to @TrinitronX one but without XQuartz, on Linux.
  • TrinitronX
    TrinitronX almost 13 years
    To add to @ephemient 's post: In order to use xclip & xsel with a remote host, you can use X11 Forwarding like so: ssh -C -X user@remote-host. If running xclip on the remote side doesn't seem to be working, make sure X11Forwarding yes is set in the remote /etc/ssh/sshd_config file. Also make sure xauth is installed on the remote side. For a headless machine, you can install xauth and xvfb.
  • Tim Bunce
    Tim Bunce over 11 years
    Here's a description with extra details plus vim key bindings.
  • Mike Brennan
    Mike Brennan over 11 years
    I often to this in vim. To do so, select what you want to copy in visual mode, then type: :'<,'>w !ssh desktop pbcopy
  • Petr Peller
    Petr Peller almost 11 years
    @MikeBrennan When you have the text selected, why don't you just press cmd+C (or whatever copy key you have set)? ...
  • John Dibling
    John Dibling over 10 years
    +1: So much easier than other solutions when a reverse SSH connection isn't possible!
  • Kamil Dziedzic
    Kamil Dziedzic about 10 years
    You deserve more likes for that extremely simple solution!
  • chowey
    chowey almost 10 years
    For those of us on Mac OSX, ssh [remote-machine] "cat log.txt" | pbcopy
  • the
    the over 9 years
    Like this it only really works when your desktop has a static IP and is reachable from the box you ssh'd into. That's never the case for me.
  • the
    the over 9 years
    How is this any different from ssh remote-host "echo 'hello from remote-host' | pbcopy? This would be an excellent answer if it would work something like this: ssh -X remote-host then on the remote host: echo 'hello from remote-host' | xclip -selection clipboard
  • rulio
    rulio over 9 years
    Wouldn't the other way around be easier? ssh user@remote 'commandThatMakesOutput' |pbcopy
  • gdw2
    gdw2 about 9 years
    @KasperSouren. I believe it does work how you are hoping. The ` | xclip` is inside the double quotes.
  • tiby
    tiby over 8 years
    As per this report here, I had to use cat to get this to work on cygwin Windows 8: ssh [remote-machine] "cat log.txt" | cat > /dev/clipboard (of course, my remote command wasn't cat; it was something else inside a vagrant virtual machine so I actually ran vagrant ssh -c "command" | cat > /dev/clipboard)
  • Sumit Jain
    Sumit Jain about 8 years
    Top answer, better then reverse ssh.
  • nbren12
    nbren12 about 8 years
    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 servers 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.
  • shivams
    shivams almost 8 years
    In 2016, this is obviously THE best, no-frill solution. Forget other, reverse-ssh based solutions.
  • Cam
    Cam almost 8 years
    @TrinitronX oh wow - banging my head against a wall, thanks for the xvfb mention. I was running a headless server, so X11 must not have been running!
  • Dap
    Dap over 7 years
    awesome! this is great. just note that the log.txt is the file on the remote host, i am unsure if you can specify the file path but most likely
  • Kvass
    Kvass over 7 years
    Is there a way to do this w/o it just being a one-off command? I want to be logged into my remote server in an interactive session over ssh and then be able to send to my local clipboard arbitrarily. Does that require reverse ssh?
  • TrinitronX
    TrinitronX over 7 years
    @Kvass: As long as you're using -X for X11 Forwarding over SSH, X11 programs will be able to update your clipboard via the XQuartz settings above. The one-off command is to demonstrate that sending something via echo to the remote host's clipboard via xclip does work & should sync to your local SSH client host. Note as @gdw2 says, "The | xclip is inside the double quotes". As such, it will execute as a command on the remote server to send something to it's clipboard.
  • Marcel Valdez Orozco
    Marcel Valdez Orozco over 6 years
    This solution is the one that worked the best for me. it is not too complicated and works properly.
  • Alan Storm
    Alan Storm about 6 years
    +1 -- that's pretty neat. However -- the cat some_useful_content.txt | nc localhost 2000 command seems to hang when I do this. I need to manually ctr-c to stop it, and it's only then that the content gets to my client clip/pasteboard
  • Sridhar Sarnobat
    Sridhar Sarnobat about 6 years
    It will wait until someone dequeues the data at the other end.
  • Sridhar Sarnobat
    Sridhar Sarnobat about 6 years
    Actually I think I misunderstood your question. I'm not sure why that happens.
  • Pat Myron
    Pat Myron almost 6 years
    I needed the -e none ssh flag described here: unix.stackexchange.com/questions/210615/…
  • Alan Storm
    Alan Storm almost 6 years
    +1 for a useful technique I've used myself, bit it does force you to lose your terminal history and (as mentioned) the first/last line problem is a little fiddly.
  • tw0000
    tw0000 almost 6 years
    Agreed @AlanStorm
  • Christian
    Christian almost 6 years
    In case you want to use it on Windows, (I know the OP didn't ask), you can also use commandThatMakesOutput | clip (eg; ssh -t root@$host "cat /your/file" | clip).
  • HappyFace
    HappyFace over 5 years
    nc -l -p works for me, but just nc -l does not. And I have the problem of @AlanStorm, too.
  • HappyFace
    HappyFace over 5 years
    I solved the problem of hanging netcat by specifying -c. I use GNU netcat installed by brew.
  • Sridhar Sarnobat
    Sridhar Sarnobat over 5 years
    Wow that’s a very creative solution.
  • Pramit
    Pramit over 5 years
    Was recently trying and using pbcopy worked fine for me ssh <remote host_name> "cat <remote file_name_with_path>" | pbcopy
  • Sridhar Sarnobat
    Sridhar Sarnobat over 5 years
    The more significant problem with this approach is that it will only save the number of lines that your terminal buffer retains. Often that’s not a problem but if you’re trying to grab the contents of a log file then you may run out of capacity,
  • Sridhar Sarnobat
    Sridhar Sarnobat over 5 years
    Like I said, you can’t do that if you’re at work sshing into your home computer.
  • tw0000
    tw0000 over 5 years
    That's true @Sridhar-Sarnobat , it's not a very good solution in general. I just use scp!
  • Jay Stanley
    Jay Stanley almost 5 years
    The Xsel with remoteforwarding was the only answer that worked for me on Ubuntu 18.04 running i3 locally. No X11 forwarding needed.
  • Alan
    Alan almost 5 years
    It works for me perfectly. I suggest ssh'ing from your client machine to host machine first, before doing | ssh desktop pbcopy.
  • n8henrie
    n8henrie over 4 years
    For anyone having trouble getting this to work on MacOS, you may need to use reattach-to-user-namespace pbcopy instead of just pbcopy. github.com/ChrisJohnsen/tmux-MacOSX-pasteboard
  • Bharat
    Bharat over 4 years
    But what to do when the file is very deep like inside two nested sshs which require passwords and then inside a user account which again require a password ?
  • R. Taukulis
    R. Taukulis about 4 years
    Best solution in my opinion. You don't have to worry about allowing reverse ssh connection which has security implications, and the infinite loop is a nice touch.
  • Jamy Mahabier
    Jamy Mahabier about 4 years
    On WSL: ssh [remote-machine] "cat log.txt" | clip.exe
  • radrow
    radrow about 3 years
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
  • xicod
    xicod about 3 years
    @radrow thanks for the comment, I updated the answer
  • Br.Bill
    Br.Bill over 2 years
    This solution works, but XQuartz hammers the CPU. Burns a lot of extra power all the time for the occasional benefit of copying to the clipboard.
  • Br.Bill
    Br.Bill over 2 years
    pbcopy is not meant to make judgments about what it copies, so it makes sense that it includes everything you give it.
  • Johnny Wong
    Johnny Wong over 2 years
    Replace step 3 with Cmd-A (select-all) and Cmd-C to copy to clipboard. At first, I think Cmd-A will just select visible screen's text, but it does select all instead.
  • Chris
    Chris over 2 years
    Thank you! I was able to automate most of this in my ~/.ssh/config! Just add these lines under the host:RemoteForward 2000 localhost:2000 \n LocalCommand /bin/bash -c 'nc -z localhost 2000 && echo "pasteboard port 2000 listener already active" || while true; do nc -l localhost 2000 | pbcopy; echo updated_pasteboard; done' & \n PermitLocalCommand yes. That starts the port forwarding automatically when you ssh to the host and runs the listener in the background. The listener never exits by itself but that seems okay and it checks to prevent duplicates listeners.
  • TrinitronX
    TrinitronX over 2 years
    @Br.Bill Yes, of course, the X11 Forwarding + XQuartz setup is providing more than just clipboard sync capability. (Hint for readers: Try running an X11 program like xeyes on the remote system) This could be desired or not, depending on your use case. If you don't require full X11 client + server support, and just want a no-frills local LAN network-based clipboard you might try remotestash instead.