shell脚本批量ssh登陆主机并执行命令

今天在客户现场遇到了这个问题,客户没有管理工具,无法批量登陆主机下发命令,几个个C段啊,让我一个一个登陆,。。。。。。。。。。。。。。。。。。

所以写了个shell脚本,批量使用用户名密码方式登陆Linux主机,执行命令,并判断是否执行成功。

目前主要有两个功能:

根据给出的C段,生成对应的IP地址,保存。

读取IP地址文件,循环登陆主机执行命令,根据返回结果判断是否执行成功。

#!/bin/sh

# Date : 2018-09-14 14:56:09

# Author: b4zinga

# Email : [email protected]

# Func : 批量登陆Linux主机并执行命令

username="root"

password="centos"

port="22"

timeout=3

cmd="ip a" # the command to be executed

succ_flag="eth0" # Characteristics of the return value after exec the cmd

iplist="ip_list.txt" # the ip list

succ_ip="success_ip_list.txt" # ip,successfuly exec

Failed_ip="Failed_ip_list.txt" # ip,Failed exec

c=192.168.27. # ip segment

#---------------------------------------------------

# make ip address by ip segment

mkip(){

for((i=1;i<256;i++))

do

echo "$c$i" >> $iplist

done

echo "ip finished ! see $iplist"

echo ""

}

# login and exec cmd

login(){

echo "-------------------------------------------------------- "

echo "username: $username password: $password port: $port timeout=$timeout"

echo "command: $cmd"

echo "--------------------------------------------------------"

echo ""

for host in `cat $iplist`;

do

result=`sshpass -p "$password" ssh -p $port -o StrictHostKeyChecking=no -o ConnectTimeout=$timeout [email protected]$host $cmd`

if [[ $result =~ $succ_flag ]]

then

echo $host >> $succ_ip

else

echo $host >> $Failed_ip

fi

done

}

help(){

echo "----------------------------------------------------------------"

echo "bash remote.sh"

echo ""

echo "bash remote.sh mkip make IP list"

echo "bash remote.sh login login to exec command "

echo "bash remote.sh all make IP list and login to exec command"

echo "-----------------------------------------------------------------"

exit 1

}

#-----------------------------start-------------------------------------------

[ $# -gt 0 ] || help $*

echo $1

case $1 in

mkip)

mkip

exit 0

;;

login)

login

exit 0

;;

all)

mkip

login

exit 0

;;

*)

help $*

exit 0

;;

esac

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐