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

发布于 2024-07-27 15:25:44 字数 546 浏览 4 评论 0原文

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

pbcopy, pbpaste 

SSHed 到另一台服务器? 也就是说,

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

是的,我知道我可以(不寒而栗)使用鼠标从命令中选择文本,但我已经习惯了将输出直接传送到剪贴板的工作流程,我希望远程会话也能如此。

代码很有用,但通用方法也值得赞赏。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

葮薆情 2024-08-03 15:25:45

这是我的解决方案,基于 SSH 反向隧道、netcatxclip

首先在您的工作站上创建一个脚本(例如,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

并在后台启动它。

./clipboard-daemon.sh &

它将启动 nc 将输出传输到 xclip 并在之后重新生成进程接收部分数据。

然后启动与远程主机的 SSH 连接:

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

登录远程主机后,尝试以下操作:

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

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

当然,您可以编写一个包装器脚本,首先启动 clipboard-daemon.sh,然后启动 SSH 会话。 这对我来说就是这样的。

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

First create a script (for example, clipboard-daemon.sh) on your workstation:

#!/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 the background.

./clipboard-daemon.sh &

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

Then start the SSH connection to the remote host:

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

While logged in on the remote box, try this:

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

Then try to paste on your workstation.

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

寒尘 2024-08-03 15:25:45

请允许我添加一个解决方案,如果我没有记错的话,之前没有建议过。

它不需要客户端暴露在互联网上(无反向连接),也不使用服务器上的任何xlib,并且完全使用ssh自己的功能实现(无第3方bins)

  1. 打开到远程主机的连接,然后在其上创建一个 fifo 文件并并行等待该 fifo(所有内容都具有相同的实际 TCP 连接)。
  2. 您回显到该 fifo 文件的任何内容最终都会出现在您的本地剪贴板中。
  3. 会话完成后,删除服务器上的 fifo 文件并彻底终止连接。

该解决方案利用 ssh 的 ControlMaster 功能,只需使用一个 TCP 连接即可完成所有操作,因此它甚至可以支持需要密码登录的主机,并提示您输入密码一次。

编辑:根据要求,代码本身:

将以下内容粘贴到您的 bashrc 中并使用 sshx host 进行连接。

在远程机器上 echo SOMETHING > ~/clip 希望某些内容最终会出现在本地主机的剪贴板中。

您将需要本地主机上的xclip实用程序。

_dt_term_socket_ssh() {
    ssh -oControlPath=$1 -O exit DUMMY_HOST
}
function sshx {
    local t=$(mktemp -u --tmpdir ssh.sock.XXXXXXXXXX)
    local f="~/clip"
    ssh -f -oControlMaster=yes -oControlPath=$t $@ tail\ -f\ /dev/null || return 1
    ssh -S$t DUMMY_HOST "bash -c 'if ! [ -p $f ]; then mkfifo $f; fi'" \
        || { _dt_term_socket_ssh $t; return 1; }
    (
    set -e
    set -o pipefail
    while [ 1 ]; do
        ssh -S$t -tt DUMMY_HOST "cat $f" 2>/dev/null | xclip -selection clipboard
    done &
    )
    ssh -S$t DUMMY_HOST \
        || { _dt_term_socket_ssh $t; return 1; }
    ssh -S$t DUMMY_HOST "rm $f"
    _dt_term_socket_ssh $t
}

更详细的说明位于我的网站上:

https://xicod.com/2021/02/09/clipboard-over-ssh.html

Allow me to add a solution that if I'm not mistaken was not suggested before.

It does not require the client to be exposed to the internet (no reverse connections), nor does it use any xlibs on the server and is implemented completely using ssh's own capabilities (no 3rd party bins)

It involves:

  1. Opening a connection to the remote host, then creating a fifo file on it and waiting on that fifo in parallel (same actual TCP connection for everything).
  2. Anything you echo to that fifo file ends up in your local clipboard.
  3. When the session is done, remove the fifo file on the server and cleanly terminate the connections together.

The solution utilizes ssh's ControlMaster functionality to use just one TCP connection for everything so it will even support hosts that require a password to login and prompt you for it just once.

Edit: as requested, the code itself:

Paste the following into your bashrc and use sshx host to connect.

On the remote machine echo SOMETHING > ~/clip and hopefully, SOMETHING will end up in the local host's clipboard.

You will need the xclip utility on your local host.

_dt_term_socket_ssh() {
    ssh -oControlPath=$1 -O exit DUMMY_HOST
}
function sshx {
    local t=$(mktemp -u --tmpdir ssh.sock.XXXXXXXXXX)
    local f="~/clip"
    ssh -f -oControlMaster=yes -oControlPath=$t $@ tail\ -f\ /dev/null || return 1
    ssh -S$t DUMMY_HOST "bash -c 'if ! [ -p $f ]; then mkfifo $f; fi'" \
        || { _dt_term_socket_ssh $t; return 1; }
    (
    set -e
    set -o pipefail
    while [ 1 ]; do
        ssh -S$t -tt DUMMY_HOST "cat $f" 2>/dev/null | xclip -selection clipboard
    done &
    )
    ssh -S$t DUMMY_HOST \
        || { _dt_term_socket_ssh $t; return 1; }
    ssh -S$t DUMMY_HOST "rm $f"
    _dt_term_socket_ssh $t
}

More detailed explanation is on my website:

https://xicod.com/2021/02/09/clipboard-over-ssh.html

娇柔作态 2024-08-03 15:25:45

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

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

2) cat 显示文件内容

3) Cmd-S 到保存终端输出

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

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:

1) Cmd-K to clear the output of the terminal

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

3) Cmd-S to save the Terminal Output

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.

黯然#的苍凉 2024-08-03 15:25:45

它不是单行代码,但它不需要任何额外的 SSH 连接

  • 如果需要,请安装 netcat
  • 使用 termbincat ~/some_file.txt | nc termbin.com 9999。 这会将输出复制到 termbin 网站,并将 URL 打印到输出中。
  • 从您的计算机访问该 URL,您将获得输出。

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

It is not a one-liner, but it doesn't require any extra SSH connection.

  • install netcat if necessary
  • use termbin: cat ~/some_file.txt | nc termbin.com 9999. This will copy the output to the termbin website and prints the URL to your output.
  • visit that URL from your computer, and you get your output

Of course, do not use it for sensitive content.

请止步禁区 2024-08-03 15:25:45

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

该答案讨论了一般形式,

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

可能缺乏安全性的地方是 ssh 权限允许 host B> 上 < code>ssh 进入主机 A 并执行任何命令。

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

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

下面的解决方案显示了通用表单解决方案以及强制执行的 ssh 命令限制

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

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

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

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

设置ssh命令限制

假设B上的用户帐户是user-B,并且B有一个ssh密钥id-clip< /code>,已以通常方式创建 (ssh-keygen)。

然后,在user-A的ssh目录中,有一个文件

/home/user-A/.ssh/authorized_keys

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

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

但是,为了强制执行命令限制,公钥内容需要在要执行的命令前面(在同一行上)。
在我们的例子中:

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>

指定的命令“/home/user-A/.ssh/allowed-commands.sh id-clip”,并且指定的命令被执行每当使用密钥 id-clip 时,都会启动与 host-Assh 连接 - 无论写入什么命令,ssh 命令行

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

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

Id=${1}

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

机器B上对ssh的原始调用was

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

字符串 to-clipboard 通过环境变量 SSH_ORIGINAL_COMMAND 传递给 allowed-commands.sh
此外,我们还从 authorized_keys 中的行传递了密钥名称 id-clip,该密钥只​​能由 id-clip 访问。

该行

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

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

在行中

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

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

host-A /etc/ssh/sshd_config 参数

最后是主机 A/etc/ssh/sshd_config 中的一些参数code> 应设置为确保连接权限,以及仅在没有密码的情况下使用 ssh 密钥的权限:

PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
AllowUsers user-A

要使 sshd 服务器重新读取配置

sudo systemctl restart sshd.service

sudo service sshd.service restart

结论

,需要付出一些努力来设置它,但是除了 to-clipboard 之外的其他功能可以与同一框架并行构建。

This answer develops both upon the chosen answer by 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 ssh permissions allowing <user B> on host B> to ssh into host A and execute any command.

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

Fortunately, ssh has a built-in feature called command restriction or forced command. See ssh.com, or
this Server Fault question.

The solution below shows the general form solution along with ssh command restriction enforced.

Example solution with command restriction added

This security enhanced solution follows the general form - the call from the ssh session on host-B is simply:

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

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

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

/home/user-A/.ssh/authorized_keys

that recognizes the key id-clip and allows ssh connection.

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

However, to enforce command restriction that 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 only that designated command, is executed whenever key id-clip is used initiate an ssh connection to host-A - no matter what command is written the ssh command line.

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

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

Id=${1}

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 ssh on machine B was

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

The string to-clipboard is passed to allowed-commands.sh by 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.

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-send works on Ubuntu 18.04, and maybe not others).

In the line

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

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

host-A /etc/ssh/sshd_config parameters

Finally a few parameters in /etc/ssh/sshd_config on host A that should be set to ensure permission to connect, and permission to use an ssh-key only without a password:

PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
AllowUsers user-A

To make the sshd server reread the configuration

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-clipboard can be constructed in parallel with the same framework.

毅然前行 2024-08-03 15:25:45

对于任何通过谷歌搜索找到此内容的人:
如今最好的解决方案似乎是 lemonade

neovim 中也提到了各种解决方案剪贴板工具的帮助文本

For anyone googling their way to this:
The best solution in this day and age seem to be lemonade

Various solutions is also mentioned in the neovim help text for clipboard-tool

心舞飞扬 2024-08-03 15:25:45

rhileighalmgren的解决方案 很好,但是 pbcopy 会烦人地复制最后一个“\n”字符。 我使用 head 删除最后一个字符以防止出现这种情况:

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

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

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

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

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

莫多说 2024-08-03 15:25:45

Far Manager Linux 端口 支持在本地和远程主机之间同步剪贴板。 您只需打开本地far2l,在里面执行“ssh somehost”,在该ssh会话中运行远程far2l并让远程far2l与本地剪贴板一起使用。

它支持Linux、*BSD和OS X; 我制作了一个特殊的 putty 构建来从 Windows 中利用此功能。

Far Manager Linux port supports synchronizing clipboard between local and remote host. You just open local far2l, do "ssh somehost" inside, run remote far2l in that ssh session and get remote far2l working with your local clipboard.

It supports Linux, *BSD and OS X; I made a special putty build to utilize this functionality from windows also.

享受孤独 2024-08-03 15:25:45

如果您正在 Kubernetes 集群中的 pod 上工作,而不是直接 SSH,那么您无法进行文件传输,您可以使用 cat ,然后将终端输出保存为文本。 例如,在 macOS 中,您可以执行 Shell -> 导出为文本。

If you're working over e.g. a pod in a Kubernetes cluster and not direct SSH, so that there is no way for your to do a file transfer, you could use cat and then save the terminal output as text. For example in macOS you can do Shell -> Export as text.

橘虞初梦 2024-08-03 15:25:45

Sridhar 的答案类似,但使用本地转发
这是因为远程转发会在远程计算机上留下绑定和打开的端口,我认为这是不好的做法。
对我来说,其逻辑也是倒退的,远程应该提供内容,本地则请求内容。

  1. 在 SSH 会话中转发端口,可以在配置中永久转发,也可以动态转发:
    输入
    ~
    Shift + C
    -L127.0.0.4:7777:127.0.0.8:7777
    Enter
  2. 重定向或通过管道将内容复制到远程上的 netcat,例如:
    nc -lN 127.0.0.8 7777 nc -lN 127.0.0.8 7777 <   某些文件.ext 
      


    或者你可以从编辑器写入它,例如在 Vim 中:
    <前><代码>:w !nc -lN 127.0.0.8 7777

  3. 从本地计算机获取内容(带有空请求正文)并将其通过管道传输到本地剪贴板命令,例如 xclippbcopy
    <预><代码>nc 127.0.0.4 7777 < /dev/null | xclip-sel c

    或者只是将输出重定向到文件。

.4 & .8 地址并不特殊,可以更改。
它们有助于区分每个的使用位置。

Similar to Sridhar's answer but uses a local forward.
This is because remote forwards leave a port bound and open on the remote machine, which I think is bad practice.
To me, the logic of that is also backwards, it's the remote that should be serving the content, and the local requesting it.

  1. Forward the port in your SSH session, either permanently in config, or on-the-fly:
    Enter
    ~
    Shift + C
    -L127.0.0.4:7777:127.0.0.8:7777
    Enter
  2. Redirect or pipe the content to copy to netcat on the remote, e.g.:
    nc -lN 127.0.0.8 7777 < some-file.ext
    

    or you can write to it from an editor, e.g. in Vim:

    :w !nc -lN 127.0.0.8 7777
    
  3. Fetch the content (with an empty request body) from your local machine and pipe it to a local clipboard command like xclip or pbcopy:
    nc 127.0.0.4 7777 < /dev/null | xclip -sel c
    

    or just redirect output to a file.

The .4 & .8 addresses are not special and can be changed.
They help differentiate where each is used.

花开柳相依 2024-08-03 15:25:44

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

在 Cygwin 上,ssh [remote-machine] "cat log.txt" > /dev/剪贴板

来自 nbren12 的有用评论:

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

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.

On Cygwin, ssh [remote-machine] "cat log.txt" > /dev/clipboard.

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

逐鹿 2024-08-03 15:25:44

我复活这个线程是因为我一直在寻找同样的解决方案,并且我找到了一个适合我的解决方案。 这是对 OSXDaily

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

解决方案的本质:

commandThatMakesOutput | ssh desktop pbcopy

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

它需要将您的桌面配置为 SSH 服务器(我将其留给您和 Google)。 如果您设置了 ssh 密钥以促进快速 ssh 使用,最好使用每个会话密码,或者您的安全需求所需的任何内容,那就容易得多。

其他示例:

ls  | ssh desktopIpAddress pbcopy
pwd | ssh desktopIpAddress pbcopy

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

#!/bin/bash
ssh desktop pbcopy

在我的例子中,我使用了一个专门命名的键。

我使用文件名 cb(我的助记符 (ClipBoard))保存它。将脚本放在路径中的某个位置,使其可执行,然后瞧:

ls | cb

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
甜`诱少女 2024-08-03 15:25:44

我找到了一个很好的解决方案,不需要反向 SSH 连接!

您可以在远程主机上使用 xclip,以及在远程主机上使用 SSH X11 转发和 XQuartz OS X 系统。

要进行此设置:

  1. 安装 XQuartz (我使用 soloist +pivotal_workstation::xquartz 配方,但你不必)
  2. 运行 XQuartz.app
  3. 打开 XQuartz 首选项 (kb_command+,)
  4. 确保“启用同步”“在剪贴板时更新粘贴板”更改” 被选中
    XQuartz 首选项窗口示例
  5. ssh -X 远程主机 "echo '来自远程主机的问候' | xclip -selection剪贴板”

I 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 and XQuartz on the OS X 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"
浸婚纱 2024-08-03 15:25:44

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

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

  • 客户端上的 X11(如果有的话,服务器上的 xclip 效果很好),或者
  • 客户端和服务器位于同一网络中(这如果您在工作中尝试访问您的家用计算机,则情况并非如此)。

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

我已经开始使用这个,它远没有看起来那么令人生畏,所以尝试一下。

客户端(ssh 会话启动)

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

(提示:将其设置为键绑定,这样您就不必键入它)

客户端(另一个选项卡)

nc -l 2000 | pbcopy

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

服务器(在 SSH 会话内)

cat some_useful_content.txt | nc localhost 2000

其他说明

实际上,即使您处于 ssh 会话中间,也有一种方法可以启动隧道,但我不想吓跑人们,让他们远离实际上并不像看起来那么糟糕的情况。 但如果我看到有人感兴趣,我会在稍后添加详细信息

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

壹場煙雨 2024-08-03 15:25:44

如果您在 Mac 上使用 iTerm2,还有一种更简单的方法。 此功能通过 it2copyShell 集成 功能中> 命令:

Usage: it2copy
          Copies to clipboard from standard input
       it2copy filename
          Copies to clipboard from file

要使其工作,

  1. 在登录远程主机时选择iTerm2-->Install Shell Integration菜单项(以便它运行curl -L https:// iterm2.com/shell_integration/install_shell_integration_and_utilities.sh | bash),将其安装到您自己的帐户。

  2. 按照说明刷新您的环境(例如 source ~/.iterm2_shell_integration.zsh)。

完成后,您将可以访问 ~/.iterm2/it2copy 以及许多其他提供出色功能的别名命令。

这里的其他解决方案都是很好的解决方法,但相比之下,这个解决方案非常轻松。

If you use iTerm2 on the Mac, there is an easier way. This functionality is built into iTerm2's Shell Integration capabilities via the it2copy command:

Usage: it2copy
          Copies to clipboard from standard input
       it2copy filename
          Copies to clipboard from file

To make it work,

  1. choose iTerm2-->Install Shell Integration menu item while logged into the remote host (so that it runs curl -L https://iterm2.com/shell_integration/install_shell_integration_and_utilities.sh | bash), to install it to your own account.

  2. Follow the instructions to refresh your environment (e.g. source ~/.iterm2_shell_integration.zsh).

Once that is done, you'll have access to ~/.iterm2/it2copy, as well as a bunch of other aliased commands that provide cool functionality.

The other solutions here are good workarounds but this one is so painless in comparison.

乙白 2024-08-03 15:25:44

有多种工具可以访问 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]>.

简而言之,您应该尝试 xclip -i/xclip -o< /code> 或 xclip -i -sel 剪辑/xclip -o -sel 剪辑xsel -i/xsel -o< /code> 或 xsel -i -b/xsel -o -b,具体取决于您的需求。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文