我正在嘗試用一些嵌入式Expect腳本編寫一個小型bash腳本。我需要更換大約3500臺交換機的主機名。我有一個帶有我的IP地址和新主機名的csv文件,以及我的期望腳本。如果連接到交換機沒有問題,腳本似乎運行得很好。如果我從交換機獲得「超時」或「拒絕訪問」,腳本將停止退出。我需要腳本去下一個IP地址。如果一個登錄失敗,期望腳本停止多個設備
我確實使用rancid clogin進行自動登錄。
我是新來的期待和bash,並搜索我最好的朋友「谷歌」可能的答案,但無法找到答案。
該腳本如下:
hostnames.exp
#!/usr/bin/expect -f
# Set variables
set DATE [exec date +%F]
set timeout 10
# Log results
log_file -a hostnames-$DATE.log
# Let's go to configure mode
## Read the file
set fid [open ./hostnames.csv]
set content [read $fid]
close $fid
## Split into records on newlines
set records [split $content "\n"]
## Iterate over the records
foreach rec $records {
## Split into fields on comma
set fields [split $rec ","]
## Assign fields to variables and print some out...
lassign $fields\ hostname newname
puts "$hostname"
puts "$newname"
if {$hostname == ""} continue
# Announce which device we are working on and at what time
send_user "\n"
send_user ">>>>> Working on $hostname @ [exec date] <<<<<\r"
send_user "\n"
spawn clogin "$hostname\r"
expect {
timeout { send_user "\n Failed to get login prompt\n"; exit 1 }
eof { send_user "\nSSH failure for hostname\n"; exit 1 }
"*-> $"
}
sleep 2
send "conf t\n"
expect "#"
send "hostname $newname\n"
expect "#"
send "exit\n"
expect "(config)#"
send "write mem\n"
expect "*#"
send "exit\n"
expect ":~\$" exit
# Announce which device we are working on and at what time
send_user "\n"
send_user ">>>>> Done working on $hostname @ [exec date] <<<<<\r"
send_user "\n"
}
這裏是我的csv文件
hostnames.csv
10.10.1.1,newhostname1
172.16.1.2,newhostname2
192.168.45.150,newhostname3
我會APPR提供任何幫助。
謝謝
嗨迪內希
謝謝您的答覆。
我用你提供的第一個代碼,沒有「句柄」部分。如果登錄失敗,它現在會轉到下一個IP地址,但它不會在良好的登錄中運行我的命令。登錄到172.16.1.2是唯一的工作連接。其他人將測試故障轉移。
$**expect hostnames.exp**
10.10.1.1
newhostname1
>>>>> Working on 10.10.1.1 @ Wed Oct 1 11:59:09 SAST 2014 <<<<<
spawn clogin 10.10.1.1
10.10.1.1
in /home/*****/.cloginrc.0.1.1
SSH failure for hostname for 10.10.1.1
172.16.1.2
newhostname2
>>>>> Working on 172.16.1.2 @ Wed Oct 1 11:59:09 SAST 2014 <<<<<
spawn clogin 172.16.1.2
172.16.1.2
spawn telnet 172.16.1.2
Trying 172.16.1.2...
.onnected to 172.16.1.2
Escape character is '^]'.
User Access Verification
Username: *****
Password:
SR_Test_SW#
SR_Test_SW#
Failed to get login prompt for 172.16.1.2
192.168.45.150
newhostname3
>>>>> Working on 192.168.45.150 @ Wed Oct 1 11:59:11 SAST 2014 <<<<<
spawn clogin 192.168.45.150
192.168.45.150
spawn telnet 192.168.45.150
Trying 192.168.45.150...
Failed to get login prompt for 192.168.45.150
$
我沒有嘗試你的第二個代碼的「處理」部分,這也給了我錯誤。
如果您需要我,我會爲您提供輸出。
謝謝你的時間。
我對第一個代碼段進行了更改,並將**「* - > $」**部分替換爲**「*#」{} **現在看起來好了。謝謝。 – 2014-10-03 08:18:29
@ Evan van Zyl,是的,在我的答案評論部分更新錯誤輸出。 – Dinesh 2014-10-03 14:07:23