如何使用expect取代遠端主機上的IP位址

如何使用expect取代遠端主機上的IP位址

我編寫了以下expect腳本來替換遠端 Linux 機器上的 IP 位址

我使用perl單行線來完成這項任務

我收到有關無法讀取“HOME”的錯誤:沒有這樣的變量,

請告知我需要在腳本中更改哪些內容expect以便更改請求的 IP?

 #!/bin/ksh


 expect_transfer=`cat << EOF
 set timeout -1
 spawn  ssh  12.219.102.43
       expect {
                 ")?"   { send "yes\r"  ; exp_continue  }

                 word:  {send pass123\r}
              }
  expect #  {send "export OLD=10.10.10.10 ; export NEW=1.1.1.1 ; perl -i -pe 's/\Q$ENV{OLD}\E/$1$ENV{NEW}$2/' /etc/hosts\r"}
  expect #    {send exit\r}
  expect eof
  EOF`


  expect -c  "$expect_transfer" 

結果:

  spawn ssh 12.219.102.43
  [email protected]'s password: 
  Last login: Sun Aug  4 12:29:25 2013 from 12.219.102.43
  [root@localhost ~]# can't read "HOME": no such variable
  while executing
   "send "export OLD=10.10.10.10 ; export NEW=1.1.1.1 ; perl -i -pe 's/\Q$HOME/.kshrc{OLD}\E/$HOME/.kshrc{NEW}/' /etc/hosts\r""
  invoked from within
  "expect #  {send "export OLD=10.10.10.10 ; export NEW=1.1.1.1 ; perl -i -pe 's/\Q$HOME/.kshrc{OLD}\E/$HOME/.kshrc{NEW}/' /etc/hosts"
  • 我很樂意在 ksh 腳本下獲得任何其他解決方案

答案1

顯然$ENV擴展$HOME/.kshrc

send "export OLD=10.10.10.10 ; export NEW=1.1.1.1 ; perl -i -pe 's/\Q$HOME/.kshrc{OLD}\E/$HOME/.kshrc{NEW}/' /etc/hosts\r

你可以

  1. 在 Perl 行中嘗試 $OLD 和 $NEW,

  2. 放棄期望,轉而使用普通 ssh:ssh [email protected] -- sed -i s/$OLD/$NEW/ /etc/hosts

    透過正確的密鑰設置,您也不需要密碼。

相關內容