Chinaunix

标题: shell 同时循环两个变量 问题 [打印本页]

作者: 水底游    时间: 2013-08-27 19:59
标题: shell 同时循环两个变量 问题
  1. #!/bin/sh
  2. a=`cat ip.txt|awk '{print $1}'`
  3. b=`cat ip.txt|awk '{print $2}'`

  4. for i in $a
  5. do
  6. expect -c"
  7. set ip $i
  8. set password $j
  9. set timeout 3
  10. spawn ssh root@$ip
  11. expect {
  12. "*yes/no" {send "yes\r";exp_continue}
  13. "*Password:" {send "$password\r"}
  14. }
  15. expect eof;"
  16. done


  17. 我要怎样传入$i和$j的值的?

  18. 遇到好几次类似这样要同时循环两个变量的。。。都不知怎么搞


  19. ip.txt的内容 $i获取ip  $j获取密码
  20. [root@localhost expect]# cat ip.txt
  21. 192.16.1.211   centos
  22. 192.16.1.212   qwe123
  23. 192.16.1.213   centos
  24. 192.16.1.214   centos214
  25. 192.16.1.216   centosjava
  26. 192.16.1.240   suselinux
  27. 192.16.1.246   panabit
  28. 192.16.1.250   centos

  29. 我上面的那个脚本应该怎样传入$i和$j的值的?
复制代码

作者: 关阴月飞    时间: 2013-08-27 20:03
试试:
  1. while read i j
  2. do
  3. expect -c"
  4. set ip $i
  5. set password $j
  6. set timeout 3
  7. spawn ssh root@$ip
  8. expect {
  9. "*yes/no" {send "yes\r";exp_continue}
  10. "*Password:" {send "$password\r"}
  11. }
  12. expect eof;"
  13. done <ip.txt
复制代码

作者: seesea2517    时间: 2013-08-28 09:24
楼上的方法最简单,还有另外两个方案可以参考:
  1. [seesea@UC ~]$ cat xx.sh
  2. #!/bin/sh

  3. # 方法一

  4. a=( `cat ip.txt|awk '{print $1}'` )
  5. b=( `cat ip.txt|awk '{print $2}'` )

  6. echo "方法一"
  7. for ((i=0; i<${#a[@]}; ++i))
  8. do
  9.         echo "${a[$i]} -- ${b[$i]}"
  10. done

  11. # 方法二
  12. echo "方法二"
  13. while read -a ar_line
  14. do
  15.         echo "${ar_line[0]} -- ${ar_line[1]}"
  16. done < ip.txt

  17. [seesea@UC ~]$ bash xx.sh
  18. 方法一
  19. 192.16.1.211 -- centos
  20. 192.16.1.212 -- qwe123
  21. 192.16.1.213 -- centos
  22. 192.16.1.214 -- centos214
  23. 192.16.1.216 -- centosjava
  24. 192.16.1.240 -- suselinux
  25. 192.16.1.246 -- panabit
  26. 192.16.1.250 -- centos
  27. 方法二
  28. 192.16.1.211 -- centos
  29. 192.16.1.212 -- qwe123
  30. 192.16.1.213 -- centos
  31. 192.16.1.214 -- centos214
  32. 192.16.1.216 -- centosjava
  33. 192.16.1.240 -- suselinux
  34. 192.16.1.246 -- panabit
  35. 192.16.1.250 -- centos
复制代码

作者: waker    时间: 2013-08-28 09:45
本帖最后由 waker 于 2013-08-28 09:46 编辑
  1. #!/bin/sh \
  2. exec expect "$0" ${1+"$@"}
  3. set timeout 3
  4. set infile [ open ip.txt ]
  5. while { [ gets $infile inline ] >= 0 } {
  6. set ip [lindex $inline 0]
  7. set password [lindex $inline 1]
  8. spawn ssh root@$ip
  9. expect {
  10. "*yes/no" {send "yes\r";exp_continue}
  11. "*Password:" {send "$password\r"}
  12. }
  13. expect eof
  14. }
复制代码

作者: 水底游    时间: 2013-08-28 09:50
最后的
done<ip.txt什么作用?或者是什么意思?

回复 2# 关阴月飞


   
作者: 水底游    时间: 2013-08-28 09:58
循环读取文件内容,明白了回复 5# 水底游


   
作者: 关阴月飞    时间: 2013-08-28 09:59
回复 5# 水底游


    就是读取ip.txt的内容




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2