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
...
相关推荐
方竞30 分钟前
Linux空口抓包方法
linux·空口抓包
海岛日记1 小时前
centos一键卸载docker脚本
linux·docker·centos
AttackingLin2 小时前
2024强网杯--babyheap house of apple2解法
linux·开发语言·python
学Linux的语莫3 小时前
Ansible使用简介和基础使用
linux·运维·服务器·nginx·云计算·ansible
踏雪Vernon4 小时前
[OpenHarmony5.0][Docker][环境]OpenHarmony5.0 Docker编译环境镜像下载以及使用方式
linux·docker·容器·harmonyos
学Linux的语莫4 小时前
搭建服务器VPN,Linux客户端连接WireGuard,Windows客户端连接WireGuard
linux·运维·服务器
legend_jz4 小时前
【Linux】线程控制
linux·服务器·开发语言·c++·笔记·学习·学习方法
Komorebi.py4 小时前
【Linux】-学习笔记04
linux·笔记·学习
黑牛先生4 小时前
【Linux】进程-PCB
linux·运维·服务器