shell脚本自动输入用户名和密码如何实现

其他教程   发布日期:2023年07月10日   浏览次数:530

今天小编给大家分享一下shell脚本自动输入用户名和密码如何实现的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

场景:

shell脚本中,scp和ssh连接时,自动输入用户名和密码。

解决方案:

例:

  1. #!/bin/bash
  2. remoteIp=IP
  3. remoteUser=用户名
  4. remotePw=密码
  5. function download(){
  6. remoteFile=$1
  7. localDir=$2
  8. expect << EOF
  9. set timeout 1200;
  10. spawn scp -r -p $remoteUser@$remoteIp:"$remoteFile" "$localDir"
  11. expect{
  12. "*yes/no*" {send "yes
  13. ";exp_continue}
  14. "*Permission denied*" {exit 1}
  15. "*password*" {send "$remotePw
  16. ";exp_continue}
  17. "*Killed by signal 1" {exit 1}
  18. }
  19. EOF
  20. }
  21. fucntion remoteCmd(){
  22. cmd=$1
  23. expect << EOF
  24. set timeout 1200;
  25. spawn ssh $remoteUser@$remoteIp
  26. expect{
  27. "*yes/no*" {send "yes
  28. ";exp_continue}
  29. "*Permission denied*" {exit 1}
  30. "*password*" {send "$remotePw
  31. ";exp_continue}
  32. "*$ " {send "
  33. "}
  34. }
  35. expect "*$ " {send "$cmd
  36. "}
  37. expect "*$ " {send "exit
  38. "}
  39. EOF
  40. }
  41. remoteCmd "ls -l"

以上就是shell脚本自动输入用户名和密码如何实现的详细内容,更多关于shell脚本自动输入用户名和密码如何实现的资料请关注九品源码其它相关文章!