Chinaunix
标题:
expect循环的问题
[打印本页]
作者:
onlinekof2001
时间:
2013-04-12 14:12
标题:
expect循环的问题
再shell中我可以把ip ,port 放在一个单独文件中(file)
通过 while read ip port ;do 。。。 ; done < file 的方式分别调用两个赋值变量。
现在想通过expect的方式写。如何写?
网上的expect 循环范例似乎都很简单。求帮助
作者:
wenhq
时间:
2013-04-12 14:23
挖坟吧,能找到。CU搜索。
作者:
onlinekof2001
时间:
2013-04-12 15:37
回复
2#
wenhq
我看了那些脚本都是一个参数。就ip。端口都是统一的。可是我的端口不是统一的。我的目的是讲ip和port 都列在一个文件中,调用该文件的过程中,将ip和port的变量值对应后,直接指定ssh ${ip} ${port}的方式 密码也不是统一的。
作者:
M-H-J
时间:
2013-04-12 17:20
你可以用shell 去封装一层expect 来实现该需求
[root@localhost shell]# cat ip
192.168.0.1
192.168.0.2
[root@localhost shell]# cat port
22
21
[root@localhost shell]# cat ssh.exp
#!/usr/bin/expect
set port [lindex $argv 0]
set server [lindex $argv 1]
puts "$port ====== $server"
exit 0
expect eof
[root@localhost shell]# cat test.sh
#!/bin/bash
port=(`cat port`)
ip=(`cat ip`)
tmp_key=${#port[*]}
key=`echo $(( ${tmp_key} -1 ))`
for num in `seq 0 ${key}`
do
./ssh.exp "${port[${num}]}" "${ip[${num}]}"
done
[root@localhost shell]# ./test.sh
22 ====== 192.168.0.1
21 ====== 192.168.0.2
目前只想到这个办法 。。希望大牛们批评教导 。。。
作者:
seesea2517
时间:
2013-04-12 17:21
假设文件内容为 IP 端口,一行一对,空格分隔。可以试试如下代码:
#!/usr/bin/expect --
set fid [open 文件名 r]
while {[gets $fid line] >= 0} {
set ip [lindex $line 0]
set port [lindex $line 1]
puts "IP: $ip, Port: $port\n"
}
close $fid
复制代码
未测试。
作者:
onlinekof2001
时间:
2013-04-15 18:36
回复
5#
seesea2517
#!/usr/bin/expect --
set UPLOADADR /root/file
set FID [open ${UPLOADADR} r]
set FZIP [lindex $argv 0]
while { [gets $FID line] >= 0 } {
set IP [lindex $line 0]
set PORT [lindex $line 1]
set PASSWD [lindex $line 2]
puts "IP: $IP, Port $PORT, password $PASSWD"
spawn ssh ${IP} -p ${PORT}
expect "password: " { send "${PASSWD}\r" }
expect "#" { send "sh ${UPLOADADR} ${FZIP}\r" }
expect "ename: " { send "A\r" }
sleep 2
}
嗯,按照你的尝试过了没有问题。楼上的封装,我还没试过,不过这个脚本 本来就要调用远程的shell脚本。这样应该足够了
作者:
seesea2517
时间:
2013-04-16 09:16
回复
6#
onlinekof2001
实现了就好。封闭一个 expect 脚本后在 shell 里调用也是一种方案,我也有用过,因为 expect 的语法我不是很熟悉,所以这样的方案对于熟悉 shell,而只是略熟悉 expect 的情况下是很合适的。完全在 expect 下写则要比较熟悉 expect。
作者:
onlinekof2001
时间:
2013-04-16 09:29
非常感谢楼上两位提供的思路以及实现方式。
作者:
fufelixzh
时间:
2013-04-21 18:40
回复
1#
onlinekof2001
i think you mean read file with tcl
cat 2.txt
192.168.1.1
8000
#!/opt/cool/bin/expect
if [catch {open 2.txt r} fd] {
# open failed
puts stderr "cannot open 2.txt"
exit 1
}
set lineno 0
while {[gets $fd line] >= 0} {
incr lineno
puts "$lineno
line \n"
foreach ln [split $line " "] {
puts "$lineno
ln \n"
}
}
# close both files
close $fd
=========
cat 2.txt
192.168.1.1 80
#!/opt/cool/bin/expect
if [catch {open 1.txt r} fd] {
# open failed
puts stderr "cannot open 1.txt"
exit 1
}
set lineno 0
while {[gets $fd line] >= 0} {
incr lineno
puts "$lineno
line \n"
}
# close both files
close $fd
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2