expect 脚本:文件名:expect_ssh
#!/usr/bin/expect set host [lindex $argv 0] set username [lindex $argv 1] set password [lindex $argv 2] spawn ssh $username@$host expect { "(yes/no)?" { send "yes\n" expect "*assword:" { send "$password\n"} } "*assword:" { send "$password\r" } } set pwd 1234567 expect "$" send "su -\r" expect "Password:" send "$pwd\r" expect "*]#" send "kill -9 `ps -ef|grep java|grep -v grep|awk '{print \$2}'`&& su - tomcat -c /usr/local/tomcat6/bin/startup.sh &&su - tomcat7 -c /usr/local/tomcat7/bin/startup.sh\r" send "\r" send "exit\r" send "exit\r" expect eof
bash 脚本:调用 expect 脚本,bash 文件名:bash_ssh.sh
#!/bin/sh rpm -q expect &>/dev/null if [ $? -ne 0 ]; then echo "install expect......" yum install -y expect > /dev/null fi list_file=$1 cat $list_file | while read line do host_name=`echo $line | awk '{print $1}'` username=`echo $line | awk '{print $2}'` password=`echo $line | awk '{print $3}'` ./expect_ssh $host_name $username $password done
建立 host.list 文件
# touch host.list 192.168.66.130 tom 123456 192.168.66.131 tom 123456
使用方法:
sh bash_ssh.sh host.list
调试中的错误:
read "2": no such variable
原因:
expect 脚本远程 kill 进程,需要对特殊字符进行转义,$2 需要 \ 转义,否则会把 2 是当作一个变量。
解决方法:
send "kill -9 `ps -ef|grep java|grep -v grep|awk '{print \$2}'`\r"