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

Ala*_*orm 134 unix linux macos shell clipboard

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

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

pbcopy, pbpaste 
Run Code Online (Sandbox Code Playgroud)

无论如何在SSH连接到另一台服务器时复制此功能?那是,

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

是的,我知道我可以(颤抖)使用我的鼠标从命令中选择文本,但我已经习惯了将输出直接压缩到剪贴板的工作流程,我希望我的远程会话也一样.

代码很有用,但也可以采用一般方法.

Dom*_*kis 103

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

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

编辑:来自nbren12的有用评论:

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

  • 对于我们这些在Mac OSX上的人来说,`ssh [remote-machine]"cat log.txt"| pbcopy` (28认同)
  • 对于这个非常简单的解决方案,你应该得到更多的喜欢 (8认同)
  • +1:当无法进行反向SSH连接时,比其他解决方案容易得多! (5认同)
  • 始终可以使用SSH端口转发设置反向ssh连接.只需将`RemoteForward 127.0.0.1:2222 127.0.0.1:22`添加到本地`.ssh/config`中的servers条目,然后在远程机器上执行`ssh -p 2222 127.0.0.1`,然后重定向与本地计算机的连接. (4认同)

小智 78

我正在复活这个帖子,因为我一直在寻找同样的解决方案,而且我找到了一个对我有用的解决方案.这是对OSX Daily建议的一个小修改.

在我的例子中,我使用本地OSX机器上的终端通过SSH连接到Linux服务器.和OP一样,我希望能够仅使用键盘将少量文本从终端传输到本地剪贴板.

解决方案的本质:

commandThatMakesOutput | ssh desktop pbcopy
Run Code Online (Sandbox Code Playgroud)

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

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

其他例子:

ls  | ssh desktopIpAddress pbcopy
pwd |  ssh desktopIpAddress pbcopy
Run Code Online (Sandbox Code Playgroud)

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

#!/bin/bash
ssh desktop pbcopy
Run Code Online (Sandbox Code Playgroud)

就我而言,我使用的是一个特别命名的密钥

我用文件名cb(我的助记符(ClipBoard))保存它.把脚本放在路径的某个地方,让它可执行,然后瞧:

ls | cb
Run Code Online (Sandbox Code Playgroud)

  • 像这样它只有当您的桌面具有静态IP并且可以从您输入的框中访问时才能真正起作用.对我来说,情况从未如此. (29认同)
  • 反过来会不会更容易?ssh user @ remote'commandThatMakesOutput'| pbcopy (6认同)
  • 非常聪明.谢谢. (2认同)
  • 我经常在vim这个.为此,请在可视模式下选择要复制的内容,然后键入:`:'<,'> w!ssh desktop pbcopy` (2认同)

Tri*_*onX 28

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

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

要设置它:

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

  • @KasperSouren.我相信它确实有用你的希望.`| xclip`在双引号内. (5认同)
  • @Kvass:只要您使用-X来通过SSH进行X11转发,X11程序就可以通过上面的XQuartz设置更新剪贴板。一次性命令是演示通过`echo`通过`xclip`发送到远程主机的剪贴板确实有效并且应该同步到本地SSH客户端主机。注意,如@ gdw2所说,“`| xclip`位于双引号内”。这样,它将作为远程服务器上的命令执行,以将某些内容发送到剪贴板。 (2认同)

Sri*_*bat 13

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

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

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

这是另一种方法,虽然你需要修改你的计算机的方式.

我已经开始使用它了,它看起来并不像它看起来那么令人生畏,所以试一试.

客户端(ssh会话启动)

ssh username@server.com -R 2000:localhost:2000
Run Code Online (Sandbox Code Playgroud)

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

客户(另一个标签)

nc -l 2000 | pbcopy
Run Code Online (Sandbox Code Playgroud)

注意:如果你没有,pbcopy那就tee把它放到一个文件中.

服务器(在SSH会话中)

cat some_useful_content.txt | nc localhost 2000
Run Code Online (Sandbox Code Playgroud)

其他说明

实际上,即使你正处于一个ssh会话的中间,也有一种方法可以启动隧道,但我不想让人们远离那些看起来并不那么糟糕的东西.但如果我发现任何兴趣,我会在稍后添加细节

  • +1——这非常整洁。然而——`cat some_useful_content.txt | 当我这样做时, nc localhost 2000` 命令似乎挂起。我需要手动按 ctr-c 来停止它,只有这样内容才会到达我的客户端剪辑/粘贴板 (3认同)
  • 我通过指定`-c`解决了netcat挂起的问题。我使用由brew安装的GNU netcat。 (2认同)
  • 谢谢你!我能够在我的“~/.ssh/config”中自动执行大部分操作!只需在主机下添加这些行:`RemoteForward 2000 localhost:2000 \n LocalCommand /bin/bash -c 'nc -z localhost 2000 &amp;&amp; echo "pasteboard port 2000 Listener already active" || 虽然真实;执行 nc -l 本地主机 2000 | PB复制;回显更新的粘贴板;完成' &amp; \n PermitLocalCommand yes`。当您 ssh 到主机并在后台运行侦听器时,会自动启动端口转发。侦听器永远不会自行退出,但这似乎没问题,并且它会检查以防止重复的侦听器。 (2认同)

Br.*_*ill 12

如果您在 Mac 上使用iTerm2,还有一种更简单的方法。此功能通过以下命令内置到 iTerm2 的Shell 集成功能中it2copy

Usage: it2copy
          Copies to clipboard from standard input
       it2copy filename
          Copies to clipboard from file
Run Code Online (Sandbox Code Playgroud)

为了使其发挥作用,

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

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

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

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


eph*_*ent 7

有多种工具可以访问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 <astrand@lysator.liu.se>
$ 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 <conrad@vergenet.net>.

简而言之,您应该尝试xclip -i/ xclip -oxclip -i -sel clip/ xclip -o -sel clipxsel -i/ xsel -oxsel -i -b/ xsel -o -b,具体取决于您的需求.

  • 要添加到@ephemient的帖子:为了将xclip&xsel与远程主机一起使用,你可以像这样使用X11 Forwarding:`ssh -C -X user @ remote-host`.如果在远程端运行xclip似乎不起作用,请确保在远程`/ etc/ssh/sshd_config`文件中设置了"X11Forwarding yes".还要确保远程端安装了`xauth`.对于无头机器,您可以安装`xauth`和`xvfb`. (4认同)

xic*_*cod 7

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

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

它涉及:

  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
}
Run Code Online (Sandbox Code Playgroud)

更详细的解释在我的网站上:

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


小智 6

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

首先在您的工作站上创建脚本(例如 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
Run Code Online (Sandbox Code Playgroud)

并在后台启动它。

./clipboard-daemon.sh&
Run Code Online (Sandbox Code Playgroud)

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

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

ssh user@host -R127.0.0.1:3333:127.0.0.1:3333
Run Code Online (Sandbox Code Playgroud)

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

echo "this is test" >/dev/tcp/127.0.0.1/3333
Run Code Online (Sandbox Code Playgroud)

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

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


tw0*_*000 5

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

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

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

3)Cmd-S保存终端输出

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