auto-ssh-keygen.exp 

  1. #!/usr/bin/expect -f 
  2.  
  3. # optionally set key passwd 
  4. set pw  ""  
  5. set timeout 5 
  6.  
  7. spawn ssh-keygen -q 
  8. expect "*save*id_rsa*" 
  9. send "\n" 
  10. # file is exist tip 
  11. expect "*y/n*"        { send "y\n" } 
  12.  
  13. expect "*passphrase*" 
  14. send "$pw\n" 
  15.  
  16. expect "*passphrase*" { send "$pw\n" }  
  17. #expect "*#|$*" 
  18. expect eof 

nopwdlogin.exp

 

  1. #!/usr/bin/expect -f 
  2.  
  3. ## generate public/private key 
  4. exec ./auto-ssh-keygen.exp 
  5.  
  6. ## send public keys to target 
  7.  
  8. set ip [lindex $argv 0] 
  9. set pwd [lindex $argv 1] 
  10. #set usr root 
  11. set filecontent [exec cat /root/.ssh/id_rsa.pub] 
  12. set destdir ~/.ssh 
  13. set timeout 3 
  14.  
  15. spawn ssh $ip 
  16.  
  17. # exp_continue # 继续下一个 
  18. expect {     
  19.     "(yes/no)?" {send "yes\r";exp_continue} 
  20.         "password:" {send  "$pwd\r"
  21.  
  22. # handle dir .ssh 
  23. expect "*#*" {send "if ! test -d $destdir; then mkdir $destdir; fi\n"
  24. expect "*#*" {send "echo -n $filecontent >> $destdir/authorized_keys \n"
  25.  
  26. expect eof