Shell脚本实现远程服务启停(无需做SSH免密配置)

可以先参考Linux SSH非交互式登录执行命令了解一下expect和sshpass


然后这里主要是想记录一下使用expect实现的方式,sshpass方式的话没什么好说的,下列脚本以Kafka的启停为例

#!/bin/bash
passwd="123"                        
iparray="node1 node2 node3"  #这里我放的是域名,也可以放IP地址

case $1 in 
"start"){
    for i in $iparray
    do 
        startKafka $i
    done
};; 
"stop"){
    for i in $iparray
    do 
        stopKafka $i
    done
};;
esac

function startKafka(){
expect << EOF
  set timeout 10
  spawn ssh root@$1
  expect {
  "(yes/no)" {send "yes\r";exp_continue}
  "password:" {send "$passwd\r"}
  }
  expect "root@*" {send "/usr/local/kafka_2.13-3.1.1/bin/kafka-server-start.sh -daemon /usr/local/kafka_2.13-3.1.1/config/server.properties\r"}
  expect "root@*" {send "exit\r"}
  expect eof
EOF
}

function stopKafka(){
expect << EOF
  set timeout 10
  spawn ssh root@$1
  expect {
  "(yes/no)" {send "yes\r";exp_continue}
  "password:" {send "$passwd\r"}
  }
  expect "root@*" {send "/usr/local/kafka_2.13-3.1.1/bin/kafka-server-stop.sh\r"}
  expect "root@*" {send "exit\r"}
  expect eof
EOF
} 

缺点呢,也很明显,需要明文显示密码

posted @ 2022-05-20 16:43  RFAA  阅读(194)  评论(0编辑  收藏  举报