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执行之前将函数的定义放入内联.
小智 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打印函数的定义
| 归档时间: |
|
| 查看次数: |
29527 次 |
| 最近记录: |