批量登入SSH 自動執行shell腳本收集網卡信息

#!/bin/bash
#20190605
#list.txt存放IP和密碼

shell=/root/auto.sh
ipfile=/root/list.txt

[ `id -u` -ne 0 ] && echo "Please use the root user to execute $0"&&exit 1
[ -f $ipfile ] || echo "No file /root/list.txt found"
[ -f /root/auto.sh ] && rm -f /root/auto.sh || echo "create auto.sh"
[ -f /root/ssh.exp ] && rm -f /root/ssh.exp || echo "create ssh.exp"

cat >> auto.sh <<-EOF
#auto.sh腳本替換成自己需要的腳本,這邊是收集網卡信息
echo ------------------------ >/root/ifconfig.log
ifconfig >> /root/ifconfig.log
echo ------------------------ >>/root/ifconfig.log
EOF

cat >> ssh.exp <<-EOF
#!/usr/bin/expect
set passwd [lindex \$argv 0]
set host [lindex \$argv 1]
set shell [lindex \$argv 2]
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 "sh $shell && date >>$shell.log\r"
expect "]*"
send "\[ -f $shell \] && rm -f $shell\r"
expect "]*"
send "exit\r"
spawn scp root@\$host:/root/ifconfig.log /root/\$host-ifconfig.log
expect {
    "yes/no" { send "yes\r"; exp_continue}
    "password:" { send "\$passwd\r" }
}
expect eof
EOF


while read line 
do
    ip=`echo $line|awk '{print $1}'`
    pw=`echo $line|awk '{print $2}'`
	if [ -f $shell ]; then
		echo "copy $shell to $ip" >>/root/copy.log
	else	  
		echo "No file $shell found" 
		exit
	fi
	ping -c 1 $ip >/dev/null 2>&1
	[ $? -eq 0 ] && echo ping $ip success || exit 1
    /usr/bin/expect /root/ssh.exp $pw $ip $shell	
done <$ipfile

[ -f /root/ssh.exp ] && rm -f /root/ssh.exp
[ -f /root/auto.sh ] && rm -f /root/auto.sh

echo $0 End && date +"%Y/%m/%d %H:%M.%S" >> $0.log
ls *.log


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章