2017-10-16 117 views
0

我有一個IP列表,我正在循環ssh到他們每個人並捕獲一些日誌。目前,它會循環遍歷所有的IP並做我想做的事情,當它遇到最後一行後,它遇到最後一個IP時會發生問題,它會嘗試產生另一個空行,導致出錯。 (spawn ssh [email protected]期望腳本閱讀空行

如何防止發生此錯誤?

myexpect.sh

set user user 
set pass pass 
set timeout 600 

# Get the list of hosts, one per line ##### 
set f [open "/my/ip/list.txt"] 
set hosts [split [read $f] "\n"] 
close $f 

# Iterate over the hosts 
foreach host $hosts { 
    spawn ssh [email protected]$host 
    expect { 
      "connecting (yes/no)? " {send "yes\r"; exp_continue} 
      "assword: " {send "$pass\r"} 
    } 

    expect "# " 
    send "myscript.sh -x\r" 
    expect "# " 
    send "exit\r" 
    expect eof 
} 

myiplist.txt

172.17.255.255 
172.17.255.254 
... 

錯誤:

[[email protected]: ]# exit //last ip in the list 
Connection to 172.17.255.255 closed. 
spawn ssh [email protected] 
ssh: Could not resolve hostname : Name or service not known 
expect: spawn id exp5 not open 
+0

-nonewline選項,我認爲這已經回答了這裏:https://stackoverflow.com/questions/4165135/how-to-use-while-read-bash-to-read-the-last-line-in-a-file-if-there-s-no-新 –

+0

另外 - 我通常認爲使用'expect + ssh'是一種痛苦。你可能想嘗試像Ansible這樣的工具,它會讓你的生活變得更加輕鬆。 –

回答

2

文本文件用新行結束

first line\n 
... 
last line\n 

所以,當你閱讀整個文件到一個變量,然後分裂的換行符,您的名單看起來是這樣的:

{first line} {...} {last line} {} 

,因爲是最後一個換行後一個空字符串。

慣用的方式來遍歷在Tcl的文件/預期的線路是這樣的:

set f [open file r] 
while {[gets $f host] != -1} { 
    do something with $host 
} 
close $f 

或者,使用的the read command

set f [open file] 
set hosts [split [read -nonewline $f] \n] 
close $f 
foreach host $hosts {...} 
+0

謝謝,我使用了'-nonewline',它的功能就像一個魅力! – kkmoslehpour