1. #!/usr/bin/expect


  2. for {set ip 11} {$ip <= 20} {incr ip} {  # 假设有10台机器

  3. # 复制脚本到各台机器上

  4. spawn scp -P58422 /root/bin/myscript.sh "root@192.168.1.$ip:/root/bin/myscript.sh"

  5. expect "*password:" 检测到屏幕上出现这个字符串时

  6. send "123456\r"  输入以下字符

  7. send "exit\r"  


  8. # 在各台机器上执行命令

  9. spawn ssh -p58422 -t -o StrictHostKeyChecking=no "root@192.168.1.$ip"

  10. expect "*password:"

  11. send "123456\r" \r表示回车,\n表示换行

  12. expect "*]#" 检测到屏幕上的提示符为]#时

  13. send "/root/bin/myscript.sh\r"    # 执行脚本

  14. expect "*]#"

  15. send "echo \"01 */1 * * * root /root/bin/myscript.sh\" >> /etc/crontab \r"   # 放入crontab内

  16. expect "*]#"

  17. send "service crond reload \r"     # 重启crond服务

  18. send "exit\r"

  19. }