#bash/python命令语法
#ssh语法同bash/python不同,避免混淆
bash script.sh params4script
python script.py params4script
bash -c ""
bash -c ''
python -c ''
python -c ""
- 一行和多行只是写法不同
- 打包成函数和文件没有本质区别
- 注意Shell会解释输入,转译字符、变量生效
- 推荐服用本地代码,完全本地执行代码,完全远程执行代码(在本地准备好函数和变量),最大程度复用代码
- 嵌套多层ssh
- 执行、日志分离
#ssh远程执行命令,直接输入
ssh ${user}@${host} 'cmd;cmd;'
ssh ${user}@${host} "cmd;cmd;"
ssh ${user}@${host} '
cmd
cmd
'
ssh ${user}@${host} "
cmd
cmd
"
#ssh远程执行命令,函数,在本地准备好变量和函数,注意Shell解释会解释输入
var1=foo
var2=bar
function getHostName() {
echo $(hostname)
echo ${var1}
echo ${var2}
}
getHostName
#双引号
ssh ${user}@${host} "
#经Shell解释输入,执行内容获得本地变量值
var1=${var1}
var2=${var2}
#获取函数定义,执行函数定义
$(typeset -f getHostName)
#远程执行函数,复用本地函数代码
getHostName
"
#单引号
ssh ${user}@${host} '
var1='${var1}'
var2='${var2}'
function getHostName() {
echo $(hostname)
echo ${var1}
echo ${var2}
}
getHostName
$(typeset -f getHostName)
getHostName
#ssh远程执行命令,重定向标准输入到文件输入
ssh ${user}@${host} bash -s < script.sh hello world
ssh ${user}@${host} bash -s hello world < script.sh
ssh ${user}@${host} bash -s hello < script.sh world
:script.sh
echo $(hostname)
echo $1
echo $2
script.sh
#SSH嵌套执行函数
#无需顾及单双引号(脚本即函数,函数即脚本)
host4 > host3 > host2 > host1(execute cmd)
#多行
function fromhost1 () { ... }
function fromhost2 () { ssh u1@host1 "x=${x}; y=${y}; z=${z}; $(declare -f);fromhost1;" }
function fromhost3 () { ssh u2@host2 "x=${x}; y=${y}; z=${z}; $(declare -f);fromhost2;" }
function fromhost4 () { ssh u3@host3 "x=${x}; y=${y}; z=${z}; $(declare -f);fromhost3;" }
fromhost4
#一行命令;
#一条命令&&
function fromhost1 () { timeout 2s ls -al /data > tmplog;cat tmplog; } && function fromhost2 { timeout 10s ssh [email protected] "$(declare -f);fromhost1;"; } && function fromhost3 { timeout 10s ssh [email protected] "$(declare -f);fromhost2;"; }
标签:function,Shell,user,cmd,echo,host,SSH,Linux,ssh
From: https://www.cnblogs.com/redfoxatasleep/p/17521418.html