Shell脚本:通过ssh从脚本运行函数

Mr.*_*art 39 linux bash shell sh

有什么聪明的方法可以通过ssh在远程主机上运行本地Bash功能吗?

例如:

#!/bin/bash
#Definition of the function
f () {  ls -l; }

#I want to use the function locally
f

#Execution of the function on the remote machine.
ssh user@host f

#Reuse of the same function on another machine.
ssh user@host2 f
Run Code Online (Sandbox Code Playgroud)

是的,我知道它不起作用,但有没有办法实现这一目标?

alv*_*its 87

您可以使用该typeset命令通过远程计算机使您的功能可用ssh.根据您希望如何运行远程脚本,有几个选项.

#!/bin/bash
# Define your function
myfn () {  ls -l; }
Run Code Online (Sandbox Code Playgroud)

要在远程主机上使用该功能:

typeset -f myfn | ssh user@host "$(cat); myfn"
typeset -f myfn | ssh user@host2 "$(cat); myfn"
Run Code Online (Sandbox Code Playgroud)

更好的是,为什么要打扰管道:

ssh user@host "$(typeset -f myfn); myfn"
Run Code Online (Sandbox Code Playgroud)

或者您可以使用HEREDOC:

ssh user@host << EOF
    $(typeset -f myfn)
    myfn
EOF
Run Code Online (Sandbox Code Playgroud)

如果你想发送脚本中定义的所有函数myfn,不仅仅是这样使用typeset -f:

ssh user@host "$(typeset -f); myfn"
Run Code Online (Sandbox Code Playgroud)

说明

typeset -f myfn将显示的定义myfn.

cat将接收函数的定义作为文本,$()并将在当前shell中执行它,该shell将成为远程shell中的已定义函数.最后,可以执行该功能.

最后一个代码将在ssh执行之前将函数的定义放入内联.

  • @HenkLangeveld - 它取决于是否有f()调用所需的函数.在我的假设中,函数f()可能需要其他函数.否则你的建议是最好的. (9认同)
  • 最好使用`typeset -ff`并仅发送一个函数的定义 (4认同)
  • 与任何命令相同.如果函数是`f()`那么你可以传递像`f param1 param2 ...`这样的参数.在`f()`里面你会引用参数`$ 1,$ 2,... $ n`. (2认同)
  • 优秀!我在 Bash 中使用了 `declare -f` 而不是 `typeset -f`。谢谢。 (2认同)
  • 使用“declare -f”或“typset -f”时,我在意外标记附近收到“语法错误” (2认同)

小智 5

我个人不知道你的问题的正确答案,但我有很多安装脚本只是使用ssh复制自己.

让命令复制文件,加载文件函数,运行文件函数,然后删除文件.

ssh user@host "scp user@otherhost:/myFile ; . myFile ; f ; rm Myfile"
Run Code Online (Sandbox Code Playgroud)


小智 5

其他方式:

#!/bin/bash
# Definition of the function
foo () {  ls -l; }

# Use the function locally
foo

# Execution of the function on the remote machine.
ssh user@host "$(declare -f foo);foo"
Run Code Online (Sandbox Code Playgroud)

declare -f foo打印函数的定义