为了账号安全,请及时绑定邮箱和手机立即绑定

Shell脚本:通过ssh从脚本运行功能

Shell脚本:通过ssh从脚本运行功能

慕田峪4524236 2019-12-26 08:45:21
是否有任何聪明的方法可以通过ssh在远程主机上运行本地Bash功能?例如:#!/bin/bash#Definition of the functionf () {  ls -l; }#I want to use the function locallyf#Execution of the function on the remote machine.ssh user@host f#Reuse of the same function on another machine.ssh user@host2 f是的,我知道这行不通,但是有办法实现吗?
查看完整描述

3 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

您可以使用该typeset命令通过来使功能在远程计算机上可用ssh。有多个选项,具体取决于您要如何运行远程脚本。


#!/bin/bash

# Define your function

myfn () {  ls -l; }

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


typeset -f myfn | ssh user@host "$(cat); myfn"

typeset -f myfn | ssh user@host2 "$(cat); myfn"

更好的是,为什么还要麻烦管道:


ssh user@host "$(typeset -f myfn); myfn"

或者,您可以使用HEREDOC:


ssh user@host << EOF

    $(typeset -f myfn)

    myfn

EOF

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


ssh user@host "$(typeset -f); myfn"

说明


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


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


最后的代码将在ssh执行之前将函数的定义内联。


查看完整回答
反对 回复 2019-12-26
?
喵喔喔

TA贡献1735条经验 获得超5个赞

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


让命令复制文件,加载文件功能,运行文件功能,然后删除文件。


ssh user@host "scp user@otherhost:/myFile ; . myFile ; f ; rm Myfile"


查看完整回答
反对 回复 2019-12-26
?
跃然一笑

TA贡献1826条经验 获得超6个赞

另一种方式:


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

declare -f foo 打印功能的定义


查看完整回答
反对 回复 2019-12-26
  • 3 回答
  • 0 关注
  • 956 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信