在bash脚本中通过ssh在远程主机上执行命令

前端之家收集整理的这篇文章主要介绍了在bash脚本中通过ssh在远程主机上执行命令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了一个bash脚本,它应该从文件中读取用户名和IP地址,并通过ssh对它们执行命令.

这是hosts.txt:

  1. user1 192.168.56.232
  2. user2 192.168.56.233

这是myScript.sh:

  1. cmd="ls -l"
  2.  
  3. while read line
  4. do
  5. set $line
  6. echo "HOST:" $1@$2
  7. ssh $1@$2 $cmd
  8. exitStatus=$?
  9. echo "Exit Status: " $exitStatus
  10. done < hosts.txt

问题是执行似乎在第一个主机完成后停止.这是输出

  1. $./myScript.sh
  2. HOST: user1@192.168.56.232
  3. total 2748
  4. drwxr-xr-x 2 user1 user1 4096 2011-11-15 20:01 Desktop
  5. drwxr-xr-x 2 user1 user1 4096 2011-11-10 20:37 Documents
  6. ...
  7. drwxr-xr-x 2 user1 user1 4096 2011-11-10 20:37 Videos
  8. Exit Status: 0
  9. $

为什么会这样,我该如何解决

在您的脚本中,ssh作业获取与读取行相同的标准输入,并且在您的情况下恰好在第一次调用时占用所有行.因此读取线只能看到
输入的第一行.

解决方案:关闭sdin的stdin,或者从/ dev / null更好地重定向. (有些计划
不喜欢stdin关闭)

  1. while read line
  2. do
  3. ssh server somecommand </dev/null # Redirect stdin from /dev/null
  4. # for ssh command
  5. # (Does not affect the other commands)
  6. printf '%s\n' "$line"
  7. done < hosts.txt

如果您不想为/ dev / null重定向循环中的每个作业,您还可以尝试以下方法之一:

  1. while read line
  2. do
  3. {
  4. commands...
  5. } </dev/null # Redirect stdin from /dev/null for all
  6. # commands inside the braces
  7. done < hosts.txt
  8.  
  9.  
  10. # In the following,let's not override the original stdin. Open hosts.txt on fd3
  11. # instead
  12.  
  13. while read line <&3 # execute read command with fd0 (stdin) backed up from fd3
  14. do
  15. commands... # inside,you still have the original stdin
  16. # (maybe the terminal) from outside,which can be practical.
  17.  
  18. done 3< hosts.txt # make hosts.txt available as fd3 for all commands in the
  19. # loop (so fd0 (stdin) will be unaffected)
  20.  
  21.  
  22. # totally safe way: close fd3 for all inner commands at once
  23.  
  24. while read line <&3
  25. do
  26. {
  27. commands...
  28. } 3<&-
  29. done 3< hosts.txt

猜你在找的Bash相关文章