2016-03-05 69 views
0

我正在嘗試更改一羣基於Linux的路由器從列表中拉IP的用戶的密碼。 iplist.txt只是ips的列表(每行一個)。這是我想使用的代碼:期望腳本問題從文件讀取

#!/usr/bin/expect 
set timeout 20 
#Edit for User 
set user username 
#Edit for Old Password 
set old oldpassword 
#Edit for New Password 
set new newpassword 
#get IP List from iplist.txt 
set f [open "/iplist.txt"] 
set hosts [split [read $f] "\n"] 
close $f 

foreach host $hosts { 
     spawn -noecho ssh -q -o "StrictHostKeyChecking=no" [email protected]$host 
     expect "assword:" 
     send "$old\r" 
     expect ">" 
     send "user set $user password=$new\r" 
     expect ">" 
     send "quit\r" 
     expect eof 
     close 
} 

,列表上的第一個IP工程,但在第二發送此錯誤:

spawn_id: spawn id exp4 not open 

我得到了它的這種方式工作,我想:

#!/usr/bin/expect 
    set timeout 30 
    #Edit for User 
    set user user 
    #Edit for Old Password 
    set old oldpassword 
    #Edit for New Password 
    set new newpassword 
    #get IP List from iplist.txt 
    set f [open "/iplist.txt"] 
    set data [read $f] 
    close $f 

    foreach line [split $data \n] { 
      if {$line eq {}} continue 
      spawn -noecho ssh -q -o "StrictHostKeyChecking=no" [email protected]$line 
      expect "assword:" 
      send "$old\r" 
      expect ">" 
      send "user set $user password=$new\r" 
      expect ">" 
      send "\r" 
      expect ">" 
      send "quit\r" 
      send "\r" 
      expect eof 
    } 

下一個問題我碰上是,如果設備沒有舊密碼或Linux機器就無法通過SSH到達設備,它就會因錯誤使用相同的產卵ID EXP *不當它到達時打開在IP,並且不會繼續到列表中的下一個IP。無論如何,我可以發表一個聲明,說明如果「密碼:」第二次出現在下一個IP上,並且如果「>」出現像它應該繼續使用腳本,然後在spawn命令之後添加一行如果它沒有收到第一個期望的「assword:」,它將移動到列表中的下一個IP上?

任何幫助,將不勝感激。我是新的期望,但似乎是一個非常好的工具,用於在腳本中批量ssh進程。只是無法調整它,不會在1個工作中出錯,而不會在出錯時轉到下一個工作。

回答

0
#!/usr/bin/expect 
    set timeout 30 
    #Edit for User 
    set user user 
    #Edit for Old Password 
    set old oldpassword 
    #Edit for New Password 
    set new newpassword 
    #get IP List from iplist.txt 
    set f [open "/iplist.txt"] 
    set data [read $f] 
    close $f 

    foreach line [split $data \n] { 
      if {$line eq {}} continue 
      spawn -noecho ssh -q -o "StrictHostKeyChecking=no" [email protected]$line 
      expect { 
        "assword:" { 
          send "$old\r" 
          expect { 
            "assword:" { 
                close 
                continue 
                }} 
          expect { 
            "*" { 
              send "user set $user password=$new\r" 
              expect ">" 
              send "quit\r" 
              close 
              continue 
              }}}} 
      expect { 
        "*" { 
          close 
          continue 
          }} 
      expect eof 
    } 

可能有點髒的腳本,但它的工作原理。現在,如果我能弄清楚如何導出成功,錯誤的密碼和超時日誌,所以我知道是否有錯誤。