SSH login script to automatically collect information card

#!/bin/bash
#20190605

[ id -u -ne 0 ] && echo "Please use the root user to execute $0"&&exit 1
[ -f /root/auto.sh ] && rm -f /root/auto.sh
cat >> auto.sh <<-EOF
echo ------------------------ >/root/ifconfig.log
ifconfig >> /root/ifconfig.log
echo ------------------------ >>/root/ifconfig.log
EOF
shell=/root/auto.sh
ipfile=/root/list.txt
[ -f $ipfile ] || echo "No file $ipfile found"
[ -f /root/ssh.exp ] && rm -f /root/ssh.exp || echo "create ssh.exp"
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 1.sh to $ip" >>/root/copy.log
else
echo "No file 1.sh found"
exit
fi
ping -c 1 $ip >/dev/null 2>&1
[ $? -eq 0 ] && echo ping $ip seccus || exit 1
/usr/bin/expect /root/ssh.exp $pw $ip $shell
/usr/bin/expect /root/ssh2.exp $pw $ip
done <$ipfile
[ -f /root/ssh.exp ] && rm -f /root/ssh.exp
[ -f /root/ssh2.exp ] && rm -f /root/ssh2.exp
[ -f /root/auto.sh ] && rm -f /root/auto.sh
echo $0 End && date +"%Y/%m/%d %H:%M.%S" >> $0.log
ls *.log

Guess you like

Origin blog.51cto.com/junhai/2405573