自动化运维脚本
前提条件——nmap、expect、sshpass
1.安装nmap扫描工具
eg. https://blog.csdn.net/smli_ng/article/details/105964486
└─
2.安装expect自动化交互语言
└─
eg. https://www.jianshu.com/p/32de653aa05a
3.安装sshpass非交互式登录工具
└─
eg. sshpass -p 123456 ssh -p 1000 root@远程服务器IP地址
端口探测——scan_hosts
#!/bin/bash
DATE=`date +%F-%R`
read -p "please input tager host: " host
nmap -sS -p 22 -T4 $host | grep "Nmap scan report for" | awk '{print $5}' >>./host_status/scan_host_$DATE.txt && cp ./host_status/scan_host_$DATE.txt ip.txt
while read host_up
do
echo "$host_up:22 is_up"
done<./host_status/scan_host_$DATE.txt
创建目录——hosts_status
1.创建hosts_status目录
└─
目标执行——ssh_login_exec
#!/bin/bash
source scan_port.sh
echo "--------------------------------------------------------"
DATE=`date +%F-%R`
username="xxx"
password="xxx"
port="22"
timeout=3
read -p "input your command(command1|command2): " command
cmd="echo -e '#!/usr/bin/expect\nspawn sudo su' > test2.sh && echo -E 'expect \"*的密码:\" {send \"$password\r\"}' >> test2.sh && echo -E 'expect \"#\" {send \"$command\r\"}' >> test2.sh && echo -E 'expect \"#\" {send \"cat /dev/null > /var/log/lastlog\r\"}' >> test2.sh && echo -E 'expect \"#\" {send \"cat /dev/null > /var/log/wtmp\r\"}' >> test2.sh && echo -E 'expect \"#\" {send \"cat /dev/null > /var/log/btmp\r\"}' >> test2.sh && echo -E 'expect \"#\" {send \"cat /dev/null > /var/run/utmp\r\"}' >> test2.sh && echo -E 'expect \"#\" {send \"cat /dev/null > /var/log/messages\r\"}' >> test2.sh && echo -E 'expect \"#\" {send \"history -c\r\"}' >> test2.sh && echo 'expect eof' >> test2.sh && chmod +x test2.sh && ./test2.sh && rm -rf test2.sh"
ssh_login_exec(){
echo "Automatic operation and maintenance script"
echo "Task execution time: $DATE"
echo "--------------------------------------------------------"
echo "Remote command execution:"
echo "username: $username password: $password port: $port timeout=$timeout"
echo "command: $cmd"
echo "--------------------------------------------------------"
for host in `cat ip.txt`;
do
result=`sshpass -p "$password" ssh -p $port -o StrictHostKeyChecking=no -o ConnectTimeout=$timeout $username@$host $cmd`
if
[ $? -eq 0 ]
then
echo "$host:Target host connected successfully"
echo "--------------------------------------------------------"
else
echo "$host:Destination host connection failed"
echo "--------------------------------------------------------"
fi
echo $host >> result_host.txt
echo $result >> result_command.txt
done
echo "Successful execution of automatic operation and maintenance script"
}
ssh_login_exec