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

是否有任何聪明的方法可以通过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

是的,我知道这行不通,但是有办法实现吗?


慕田峪4524236
浏览 966回答 3
3回答

HUWWW

您可以使用该typeset命令通过来使功能在远程计算机上可用ssh。有多个选项,具体取决于您要如何运行远程脚本。#!/bin/bash# Define your functionmyfn () {&nbsp; 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&nbsp; &nbsp; $(typeset -f myfn)&nbsp; &nbsp; myfnEOF如果要发送脚本中定义的所有函数,而不仅仅是发送myfn,请typeset -f像这样使用:ssh user@host "$(typeset -f); myfn"说明typeset -f myfn将显示的定义myfn。cat将以文本形式接收该函数的定义,$()并将在当前的shell中执行它,该shell将成为远程shell中的已定义函数。最后,该功能可以执行。最后的代码将在ssh执行之前将函数的定义内联。

喵喔喔

我个人不知道您问题的正确答案,但是我有很多安装脚本只是使用ssh复制自身。让命令复制文件,加载文件功能,运行文件功能,然后删除文件。ssh user@host "scp user@otherhost:/myFile ; . myFile ; f ; rm Myfile"

跃然一笑

另一种方式:#!/bin/bash# Definition of the functionfoo () {&nbsp; ls -l; }# Use the function locallyfoo# Execution of the function on the remote machine.ssh user@host "$(declare -f foo);foo"declare -f foo 打印功能的定义
打开App,查看更多内容
随时随地看视频慕课网APP