Linux SSH远程执行脚本

magicCmd.sh

shell 复制代码
#!/bin/bash
#######################################################################
## Shell Script: Remote Command Executor
## Usage: sh magicCmd.sh "commands". 
##   e.g:  sh magicCmd.sh "pwd; ls -l -a"
## Author: kuro@jiayeli.com
#######################################################################
EXECMD=$1

function executorCMD() {
  cmdStr=$1

  OLDIFS=$IFS
  IFS=';'
  read -ra cmds <<< "$cmdStr"
  IFS=$OLDIFS

  for cmd in "${cmds[@]}"
  do
    printf "[`whoami`@'localhost']# $cmd\n"
    #$cmd
  done

}


function remoteExecutor() {
  for i in {1..5}; do
    node="node0$i"
    ssh "$node" <<EOF
      echo "--------------------------------------------------------"
      echo "登录 $node"
      echo "--------------------------------------------------------"

      IFS=';' read -ra cmds <<< "$EXECMD"
      for cmd in "\${cmds[@]}"; do
        printf "[\$(whoami)@${node}]# \$cmd \n"
        eval "\$cmd"
        printf "\n"
      done

      exit
EOF
  done
}
remoteExecutor

最终效果如下:

shell 复制代码
[kuro@node01 scripts]# sh magicCmd.sh "pwd;ls /opt"
Pseudo-terminal will not be allocated because stdin is not a terminal.
--------------------------------------------------------
登录 node01
--------------------------------------------------------
[kuro@node01]# pwd 
/root

[kuro@node01]# ls /opt 
cloudera
data
datax
doris
druid-0.22.1
jmxPromExported
prometheus-2.52.0
root
software

Pseudo-terminal will not be allocated because stdin is not a terminal.
--------------------------------------------------------
登录 node02
--------------------------------------------------------
[kuro@node02]# pwd 
/root

[kuro@node02]# ls /opt 
cloudera
doris-1.0.0.tar.gz
output

Pseudo-terminal will not be allocated because stdin is not a terminal.
--------------------------------------------------------
登录 node03
--------------------------------------------------------
[kuro@node03]# pwd 
/root

[kuro@node03]# ls /opt 
cloudera
doris
doris-1.0.0.tar.gz

Pseudo-terminal will not be allocated because stdin is not a ter
...
相关推荐
Felven2 分钟前
华为鲲鹏920s芯片serdestool工具使用说明
linux·运维·服务器·华为·鲲鹏920·serdestool
莫晓燚17 分钟前
mall 电商项目完整部署---实战
linux·运维·docker·容器
咋的啥名都用不了呢~21 分钟前
Linux项目部署5(安装Nginx的插件)
linux
CodeYp201941 分钟前
第11讲:应用层协议 HTTP
linux·http
爱和冰阔落42 分钟前
【Linux网络】JsonCpp 怎么实现序列化?从 Request/Response 到网络计算器消息设计
linux·运维·网络·php
我是koten6 小时前
【运维杂谈】K8s遇到Terminating的名称空间删除不了怎么办?(解决方案亲测有效)
linux·运维·服务器·云原生·kubernetes·k8s·名称空间
2601_9679873714 小时前
安装 Redis 或 Redis Stack
linux·windows·redis·macos·安装
feng_you_ying_li14 小时前
linux之数据链路层
linux·网络·智能路由器
GeW16 小时前
高端化走到深处,是数据库和Linux的事
linux
程序员初一17 小时前
Linux 远程桌面有四种做法
linux·ssh