#!/bin/bash #20190606 #qq450433231 用戶設置新密碼要用expect傳參,設置密碼要用單引號,裁了幾回坑才懂 #list.txt文件格式:IP 登入密碼 新密碼 createsh(){ echo "開始建立腳本auto.sh " cat >> auto.sh <<-EOF !/bin/bash echo "開始執行腳本" release=\$(cat /etc/system-release|sed -r 's/.* ([0-9]+)\..*/\1/') dns=\$(grep 172.26.4.193 /etc/resolv.conf|wc -l) if [ \$dns -eq 1 ] ;then echo "DNS配置已存在" else echo "nameserver 172.26.4.193" > /etc/resolv.conf echo "nameserver 172.26.4.194" >> /etc/resolv.conf echo "DNS配置已更新" fi case \$release in 7 ) systemctl disable firewalld.service systemctl stop firewalld.service echo "防火牆已關閉" ;; 6 ) service iptables stop chkconfig iptables off echo "防火牆已關閉" ;; * ) echo "防火牆未關閉" ;; esac setenforce 0 && sed -i 's/enforcing/disabled/g' /etc/selinux/config echo "selinux已關閉" chage -d 0 root echo "用戶下一次登入必須修改密碼" echo "腳本執行成功" && exit 0 EOF echo "建立腳本auto.sh完成" } createexp(){ echo "開始建立自動登入腳本ssh.exp" cat >> ssh.exp <<-EOF #!/usr/bin/expect set passwd [lindex \$argv 0] set host [lindex \$argv 1] set shell [lindex \$argv 2] set newpasswd [lindex \$argv 3] spawn scp $shell root@\$host:$shell expect { "yes/no" { send "yes\r"; exp_continue} "password:" { send "\$passwd\r" } } spawn ssh root@\$host expect { "yes/no" { send "yes\r"; exp_continue} "password:" { send "\$passwd\r" } } expect "]*" send "echo '\$newpasswd'|passwd --stdin root || exit 1 \r" expect "]*" send "sh $shell \r" expect "]*" send "\[ -f $shell \] && rm -f $shell \r" expect "]*" send "exit\r" expect eof EOF echo "建立腳本ssh.exp完成" } shell=/root/auto.sh ipfile=/root/list.txt [ `id -u` -ne 0 ] && echo "請使用root用戶執行 $0"&&exit 1 [ -f $ipfile ] || echo "/root/list.txt路徑下文件不存在 list.txt文件格式:IP 登入密碼 新密碼" && exit 1 [ -f /root/auto.sh ] && rm -f /root/auto.sh && echo "刪除舊auto.sh文件" [ -f /root/ssh.exp ] && rm -f /root/ssh.exp && echo "刪除舊ssh.exp文件" createsh createexp while read line do ip=`echo $line|awk '{print $1}'` pw=`echo $line|awk '{print $2}'` newpw=`echo $line|awk '{print $3}'` if [ -z $ip ]||[ -z $pw ]||[ -z $newpw ];then echo "list.txt文件在$ip $pw $newpw有錯誤 文件格式:IP 登入密碼 新密碼" exit 1 elif [ -f $shell ]; then ping -c 1 $ip >/dev/null 2>&1 if [ $? -eq 0 ] ;then echo "登入主機 $ip " else echo "主機$ip沒法訪問 請檢查網絡鏈接" exit 1 fi echo "複製到主機$ip自動運行腳本auto.sh 日誌$0.log" |tee -a /root/$0.log else echo "腳本文件auto.sh未找到" exit 1 fi /usr/bin/expect /root/ssh.exp $pw $ip $shell $newpw done <$ipfile echo "刪除本地腳本文件" [ -f /root/ssh.exp ] && rm -f /root/ssh.exp [ -f /root/auto.sh ] && rm -f /root/auto.sh echo "$(date +"%Y/%m/%d %H:%M.%S") $0腳本執行結束" |tee -a /root/$0.log echo "顯示日誌" ls /root/*.log exit 0