Linux 如何从远程 SSH 会话将数据发送到本地剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1152362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:32:09  来源:igfitidea点击:

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

linuxmacosunixshellclipboard

提问by Alan Storm

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

Borderline ServerFault 问题,但我正在编写一些 shell 脚本,所以我先在这里尝试 :)

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

大多数 *nix 都有一个命令,可以让您通过管道/重定向输出到本地剪贴板/粘贴板,并从中检索。在 OS X 上,这些命令是

pbcopy, pbpaste 

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

在通过 SSH 连接到另一台服务器时,是否可以复制此功能?那是,

  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.
  1. 我正在使用计算机 A。
  2. 我打开一个终端窗口
  3. 我通过 SSH 连接到计算机 B
  4. 我在计算机 B 上运行命令
  5. 计算机 B 的输出被重定向或自动复制到计算机 A 的剪贴板。

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.

代码很有用,但一般方法也很受欢迎。

采纳答案by rhileighalmgren

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.

我正在复活这个线程,因为我一直在寻找同样的解决方案,我找到了一个适合我的解决方案。这是对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.

就我而言,我在本地 OSX 机器上使用终端通过 SSH 连接到 linux 服务器。像 OP 一样,我希望能够仅使用键盘将少量文本从终端传输到我的本地剪贴板。

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.

当在与远程计算机的 ssh 会话中运行时,此命令获取commandThatMakesOutput的输出(例如 ls、pwd)并将输出通过管道传输到本地计算机的剪贴板(“桌面”的名称或 IP)。换句话说,它使用嵌套的 ssh:您通过一个 ssh 会话连接到远程计算机,在那里执行命令,远程计算机通过另一个 ssh 会话连接到您的桌面并将文本放入剪贴板。

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.

它需要将您的桌面配置为 ssh 服务器(我留给您和谷歌)。如果您已设置 ssh 密钥以促进 ssh 的快速使用,最好使用每个会话的密码短语,或者您的安全需要,则更容易。

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:

为方便起见,我创建了一个 bash 文件来缩短管道后所需的文本:

#!/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:

我用文件名cb(我的助记符(剪贴板))保存了它。把脚本放在你路径的某个地方,让它可执行,瞧:

ls | cb

回答by ephemient

There are various tools to access X11 selections, including xclipand 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...

有多种工具可以访问 X11 选择,包括xclipXSel。请注意,X11 传统上具有多个选择,并且大多数程序对剪贴板和主选择(它们是不一样的)都有一些了解。Emacs 也可以使用二级选择,但这种情况很少见,而且没有人真正知道如何处理剪切缓冲区......

$ 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 -oor xclip -i -sel clip/xclip -o -sel clipor xsel -i/xsel -oor xsel -i -b/xsel -o -b, depending on what you want.

简而言之,您应该尝试xclip -i/xclip -oxclip -i -sel clip/xclip -o -sel clipxsel -i/xsel -oxsel -i -b/ xsel -o -b,这取决于您想要什么。

回答by TrinitronX

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

找到了一个不需要反向 ssh 连接的绝佳解决方案!

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

您可以在远程主机上使用 xclip,在 OSX 系统上使用 ssh X11 转发和 XQuartz。

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"
  1. 安装XQuartz(我用soloist + pivotal_workstation::xquartz recipe做了这个,但你不必)
  2. 运行 XQuartz.app
  3. 打开 XQuartz 首选项 ( kb_command+ ,)
  4. 确保选中 “启用同步”“剪贴板更改时更新粘贴板”XQuartz 首选项窗口示例
  5. ssh -X remote-host "echo 'hello from remote-host' | xclip -selection clipboard"

回答by Dominykas Mostauskis

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.

我最喜欢的方式是ssh [remote-machine] "cat log.txt" | xclip -selection c。当您不想(或不能)从远程到本地 ssh 时,这是最有用的。

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

编辑:在 Cygwin 上ssh [remote-machine] "cat log.txt" > /dev/clipboard

Edit: A helpful comment from nbren12:

编辑:来自 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:22to the server's entry in your local .ssh/config, and then execute ssh -p 2222 127.0.0.1on the remote machine, which will then redirect the connection to the local machine. – nbren12

几乎总是可以使用 SSH 端口转发来设置反向 ssh 连接。只需RemoteForward 127.0.0.1:2222 127.0.0.1:22在本地添加到服务器的条目.ssh/config,然后ssh -p 2222 127.0.0.1在远程机器上执行,然后将连接重定向到本地机器。– nbren12

回答by Taylor Hawkes

@rhileighalmgren solution is good, but pbcopy will annoyingly copy last "\n" character, I use "head" to strip out last character to prevent this:

@rhileighalmgren 解决方案很好,但是 pbcopy 会烦人地复制最后一个 "\n" 字符,我使用 "head" 去掉最后一个字符以防止出现这种情况:

#!/bin/bash
head -c -1 |  ssh desktop pbcopy

My full solution is here : http://taylor.woodstitch.com/linux/copy-local-clipboard-remote-ssh-server/

我的完整解决方案在这里:http: //taylor.woodstitch.com/linux/copy-local-clipboard-remote-ssh-server/

回答by Krzysztof Ksi??yk

This is my solution based on SSH reverse tunnel, netcat and xclip.

这是我基于SSH反向隧道、netcat和xclip的解决方案。

First create script (eg. clipboard-daemon.sh) on your workstation:

首先在您的工作站上创建脚本(例如 clipboard-daemon.sh):

#!/bin/bash
HOST=127.0.0.1
PORT=3333

NUM=`netstat -tlpn 2>/dev/null | grep -c " ${HOST}:${PORT} "`
if [ $NUM -gt 0 ]; then
    exit
fi

while [ true ]; do
    nc -l ${HOST} ${PORT} | xclip -selection clipboard
done

and start it in background.

并在后台启动它。

./clipboard-daemon.sh&

It will start nc piping output to xclip and respawning process after receiving portion of data

在接收到部分数据后,它将启动 nc 管道输出到 xclip 和重生过程

Then start ssh connection to remote host:

然后启动到远程主机的 ssh 连接:

ssh user@host -R127.0.0.1:3333:127.0.0.1:3333

While logged in on remote box, try this:

登录远程框后,试试这个:

echo "this is test" >/dev/tcp/127.0.0.1/3333

then try paste on your workstation

然后尝试在您的工作站上粘贴

You can of course write wrapper script that starts clipboard-daemon.sh first and then ssh session. This is how it works for me. Enjoy.

您当然可以编写包装脚本,先启动 clipboard-daemon.sh,然后 ssh 会话。这就是它对我的工作方式。享受。

回答by maxbellec

Not a one-liner, but requires no extra ssh.

不是单行的,但不需要额外的 ssh

  • install netcatif necessary
  • use termbin: cat ~/some_file.txt | nc termbin.com 9999. This will copy the output to the termbinwebsite and prints the URL to your output.
  • visit that url from your computer, you get your output
  • netcat必要时安装
  • 使用termbin: cat ~/some_file.txt | nc termbin.com 9999. 这会将输出复制到termbin网站并将 URL 打印到您的输出。
  • 从您的计算机访问该网址,您将获得输出

Of course, do not use it for sensitive content.

当然,请勿将其用于敏感内容。

回答by Sridhar Sarnobat

Reverse tunnel port on ssh server

ssh 服务器上的反向隧道端口

All the existing solutions either need:

所有现有的解决方案都需要:

  • X11 on the client (if you have it, xclipon 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).
  • 客户端上的 X11(如果有,xclip服务器上的 X11效果很好)或
  • 客户端和服务器在同一个网络中(如果你在工作时试图访问你的家用电脑,情况就不是这样)。

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

这是另一种方法,尽管您需要修改 ssh 进入计算机的方式。

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 会话启动)

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 pbcopythen just teeit to a file.

注意:如果您没有,pbcopy则将tee其保存到文件中。

Server (inside SSH session)

服务器(在 SSH 会话中)

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

实际上,即使您正在 ssh 会话中,也有一种方法可以启动隧道,但我不想吓唬人们远离真正没有看起来那么糟糕的东西。但如果我看到任何兴趣,我会稍后添加详细信息

回答by tw0000

The simplest solution of all, if you're on OS X using Terminal and you've been ssh'ing around in a remote server and wish to grab the results of a text file or a log or a csv, simply:

最简单的解决方案,如果您使用终端在 OS X 上并且您一直在远程服务器中使用 ssh 并希望获取文本文件或日志或 csv 的结果,只需:

1) Cmd-Kto clear the output of the terminal

1)Cmd-K清除终端的输出

2) cat <filename>to display the contents of the file

2)cat <filename>显示文件内容

3) Cmd-Sto save the Terminal Output

3)Cmd-S保存终端输出

You'll have the manually remove the first line and last line of the file, but this method is a bit simpler than relying on other packages to be installed, "reverse tunnels" and trying to have a static IP, etc.

您将手动删除文件的第一行和最后一行,但这种方法比依赖要安装的其他软件包、“反向隧道”和尝试使用静态 IP 等要简单一些。

回答by Craig Hicks

This answer develops both upon the chosen answerby adding more security.

通过增加更多的安全性,此答案在所选答案的基础上发展。

That answer discussed the general form

该答案讨论了一般形式

<command that makes output> | \
    ssh <user A>@<host A> <command that maps stdin to clipboard>

Where security may be lacking is in the sshpermissions allowing <user B>on host B>to sshinto host Aand execute anycommand.

当安全可能会缺乏的是在ssh允许的权限<user B>host B>,以ssh进入host A并执行任意命令。

Of course Bto Aaccess may already be gated by an sshkey, and it may even have a password. But another layer of security can restrict the scope of allowable commands that Bcan execute on A, e.g. so that rm -rf /cannot be called. (This is especially important when the sshkey doesn'thave a password.)

当然BA访问可能已经被ssh密钥门控,甚至可能有密码。但是另一层安全性可以限制B可以在 上执行的允许命令的范围A,例如rm -rf /不能被调用。(当ssh密钥没有密码时,这一点尤其重要。)

Fortunately, sshhas a built-in feature called command restrictionor forced command. See ssh.com, or this serverfault.com question.

幸运的是,ssh有一个称为命令限制强制命令的内置功能。请参阅ssh.com或此serverfault.com 问题

The solution below shows the general form solution along with sshcommand restrictionenforced.

下面的解决方案显示了一般形式的解决方案以及强制执行的ssh命令限制

Example Solution with command restrictionadded

添加了命令限制的示例解决方案

This security enhanced solution follows the general form - the call from the sshsession on host-Bis simply:

这个安全增强的解决方案遵循一般形式 - 来自ssh会话的调用host-B很简单:

cat <file> | ssh <user-A>@<host A> to_clipboard

The rest of this shows the setup to get that to work.

其余部分显示了使其工作的设置。

Setup of ssh command restriction

设置ssh 命令限制

Suppose the user account on Bis user-B, and B has an ssh key id-clip, that has been created in the usual way (ssh-keygen).

假设用户帐户Buser-B,并且 B 有一个 ssh 密钥id-clip,该密钥已以通常的方式 ( ssh-keygen)创建。

Then in user-A's ssh directory there is a file

然后在user-Assh 目录下有一个文件

/home/user-A/.ssh/authorized_keys

that recognizes the key id-clipand allows sshconnection.

识别密钥id-clip并允许ssh连接。

Usually the contents of each line authorized_keysis exactly the public key being authorized, e.g., the contents of id-clip.pub.

通常每一行的内容authorized_keys正是被授权的公钥,例如, 的内容id-clip.pub

However, to enforce command restrictionthat public key content is prepended (on the same line) by the command to be executed.
In our case:

但是,要强制执行命令限制,即要执行的命令预先(在同一行)公钥内容。
在我们的例子中:

command="/home/user-A/.ssh/allowed-commands.sh id-clip",no-agent-forwarding,no-port-forwarding,no-user-rc,no-x11-forwarding,no-pty <content of file id-clip.pub>

The designated command "/home/user-A/.ssh/allowed-commands.sh id-clip", and onlythat designated command, is executed whenever key id-clipis used initiate an sshconnection to host-A- no matter what command is written the sshcommand line.

指定的命令"/home/user-A/.ssh/allowed-commands.sh id-clip",并且执行指定的命令,无论何时使用 keyid-clip启动ssh连接host-A-无论什么命令写入ssh命令行

The command indicates a script file allowed-commands.sh, and the contents of that that script file is

该命令表示一个脚本文件allowed-commands.sh,该脚本文件的内容是

#/bin/bash
#
# You can have only one forced command in ~/.ssh/authorized_keys. Use this
# wrapper to allow several commands.

Id=

case "$SSH_ORIGINAL_COMMAND" in
    "to-clipboard")
          notify-send "ssh to-clipboard, from ${Id}"
        cat | xsel --display :0 -i -b
          ;;
    *)
        echo "Access denied"
        exit 1
        ;;
esac

The original call to sshon machine Bwas

ssh对机器的原始调用B

... | ssh <user-A>@<host A> to_clipboard

The string to-clipboardis passed to allowed-commands.shby the environment variable SSH_ORIGINAL_COMMAND. Addition, we have passed the name of the key, id-clip, from the line in authorized_keyswhich is only accessed by id-clip.

该字符串由环境变量to-clipboard传递。此外,我们已经从只能由 访问的行中传递了密钥的名称。allowed-commands.shSSH_ORIGINAL_COMMANDid-clipauthorized_keysid-clip

The line

线

          notify-send "ssh to-clipboard, from ${Id}"

is just a popup messagebox to let you know the clipboard is being written - that's probably a good security feature too. (notify-sendworks on Ubuntu 18.04, maybe not others).

只是一个弹出消息框,让您知道剪贴板正在写入 - 这也可能是一个很好的安全功能。(notify-send适用于 Ubuntu 18.04,可能不适用于其他)。

In the line

在行中

cat | xsel --display :0 -i -b

the parameter --display :0is necessary because the process doesn't have it's own X display with a clipboard, so it must be specificied explicitly. This value :0happens to work on Ubuntu 18.04 with Wayland window server. On other setups it might not work. For a standard X server this answermight help.

该参数--display :0是必需的,因为该进程没有自己的带有剪贴板的 X 显示,因此必须明确指定。该值:0恰好适用于带有 Wayland 窗口服务器的 Ubuntu 18.04。在其他设置上它可能不起作用。对于标准 X 服务器,此答案可能会有所帮助。

host-A/etc/ssh/sshd_configparameters

host-A/etc/ssh/sshd_config参数

Finally a few parameters in /etc/ssh/sshd_configon host Athat should be set to ensure permission to connect, and permission to use ssh-key only without password:

最后/etc/ssh/sshd_config在主机A上设置一些参数以确保连接权限,以及ssh仅在没有密码的情况下使用-key 的权限:

PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
AllowUsers user-A

To make the sshdserver re-read the config

使sshd服务器重新读取配置

sudo systemctl restart sshd.service

or

或者

sudo service sshd.service restart

conclusion

结论

It's some effort to set it up, but other functions besides to-clipboardcan be constructed in parallel the same framework.

设置它需要一些努力,但除此之外的其他功能to-clipboard可以在同一框架中并行构建。