代码之家  ›  专栏  ›  技术社区  ›  Mr.Eddart

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

  •  61
  • Mr.Eddart  · 技术社区  · 11 年前

    有什么巧妙的方法可以通过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
    

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

    3 回复  |  直到 8 年前
        1
  •  128
  •   zekel lepture    7 年前

    您可以使用 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 将显示的定义 我的fn .

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

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

        2
  •  7
  •   user2836202    11 年前

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

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

    ssh user@host "scp user@otherhost:/myFile ; . myFile ; f ; rm Myfile"
    
        3
  •  4
  •   Ushakov Vasilii    7 年前

    另一种方式:

    #!/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 打印函数定义