How to send data to local clipboard from a remote SSH session
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 executessh -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:
- Install XQuartz (I did this with soloist + pivotal_workstation::xquartz recipe, but you don't have to)
- Run XQuartz.app
- Open XQuartz Preferences (+
,
) - Make sure "Enable Syncing" and "Update Pasteboard when CLIPBOARD changes" are checked
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.
Related videos on Youtube
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, 2021Comments
-
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,
- I'm using Computer A.
- I open a terminal window
- I SSH to Computer B
- I run a command on Computer B
- 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 over 2 yearsI answered a similar question here, alike to @TrinitronX one but without XQuartz, on Linux.
-
TrinitronX almost 13 yearsTo 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 sureX11Forwarding yes
is set in the remote/etc/ssh/sshd_config
file. Also make surexauth
is installed on the remote side. For a headless machine, you can installxauth
andxvfb
. -
Tim Bunce over 11 yearsHere's a description with extra details plus vim key bindings.
-
Mike Brennan over 11 yearsI 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 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 over 10 years+1: So much easier than other solutions when a reverse SSH connection isn't possible!
-
Kamil Dziedzic about 10 yearsYou deserve more likes for that extremely simple solution!
-
chowey almost 10 yearsFor those of us on Mac OSX,
ssh [remote-machine] "cat log.txt" | pbcopy
-
the over 9 yearsLike 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 over 9 yearsHow 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 over 9 yearsWouldn't the other way around be easier? ssh user@remote 'commandThatMakesOutput' |pbcopy
-
gdw2 about 9 years@KasperSouren. I believe it does work how you are hoping. The ` | xclip` is inside the double quotes.
-
tiby over 8 yearsAs 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'tcat
; it was something else inside a vagrant virtual machine so I actually ranvagrant ssh -c "command" | cat > /dev/clipboard
) -
Sumit Jain about 8 yearsTop answer, better then reverse ssh.
-
nbren12 about 8 yearsIt 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 executessh -p 2222 127.0.0.1
on the remote machine, which will then redirect the connection to the local machine. -
shivams almost 8 yearsIn 2016, this is obviously THE best, no-frill solution. Forget other, reverse-ssh based solutions.
-
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 over 7 yearsawesome! 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 over 7 yearsIs 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 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 viaecho
to the remote host's clipboard viaxclip
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 over 6 yearsThis solution is the one that worked the best for me. it is not too complicated and works properly.
-
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 about 6 yearsIt will wait until someone dequeues the data at the other end.
-
Sridhar Sarnobat about 6 yearsActually I think I misunderstood your question. I'm not sure why that happens.
-
Pat Myron almost 6 yearsI needed the
-e none
ssh flag described here: unix.stackexchange.com/questions/210615/… -
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 almost 6 yearsAgreed @AlanStorm
-
Christian almost 6 yearsIn 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 over 5 years
nc -l -p
works for me, but justnc -l
does not. And I have the problem of @AlanStorm, too. -
HappyFace over 5 yearsI solved the problem of hanging netcat by specifying
-c
. I use GNU netcat installed by brew. -
Sridhar Sarnobat over 5 yearsWow that’s a very creative solution.
-
Pramit over 5 yearsWas recently trying and using pbcopy worked fine for me
ssh <remote host_name> "cat <remote file_name_with_path>" | pbcopy
-
Sridhar Sarnobat over 5 yearsThe 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 over 5 yearsLike I said, you can’t do that if you’re at work sshing into your home computer.
-
tw0000 over 5 yearsThat's true @Sridhar-Sarnobat , it's not a very good solution in general. I just use
scp
! -
Jay Stanley almost 5 yearsThe Xsel with remoteforwarding was the only answer that worked for me on Ubuntu 18.04 running i3 locally. No X11 forwarding needed.
-
Alan almost 5 yearsIt works for me perfectly. I suggest ssh'ing from your client machine to host machine first, before doing
| ssh desktop pbcopy
. -
n8henrie over 4 yearsFor anyone having trouble getting this to work on MacOS, you may need to use
reattach-to-user-namespace pbcopy
instead of justpbcopy
. github.com/ChrisJohnsen/tmux-MacOSX-pasteboard -
Bharat over 4 yearsBut 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 about 4 yearsBest 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 about 4 yearsOn WSL:
ssh [remote-machine] "cat log.txt" | clip.exe
-
radrow about 3 yearsWhile 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 about 3 years@radrow thanks for the comment, I updated the answer
-
Br.Bill over 2 yearsThis 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 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 over 2 yearsReplace step 3 with
Cmd-A
(select-all) andCmd-C
to copy to clipboard. At first, I thinkCmd-A
will just select visible screen's text, but it does select all instead. -
Chris over 2 yearsThank 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 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 tryremotestash
instead.