亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 1085 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號