Bash
從 /etc/hosts 到對話框的 cat 特定行範圍
例如,我喜歡列出 /etc/hosts 中的所有乙太網交換機,並在對話框中顯示它們。之後,我想從列表中連接選定的交換機。
該列表應列在特定註釋行之間,例如:
/etc/主機:
... # ETHERNET SWITCHES 192.168.0.2 SW1 192.168.0.3 SW2 192.168.0.4 SW3 # END SWITCHES ...
以及如何使用列出的交換機名稱連接變數 $HOST 以從 /etc/hosts 與它的 IP 進行 ssh 連接?有可能是這樣的嗎?
對話框腳本:
#!/bin/bash DIALOG_CANCEL=1 DIALOG_ESC=255 HEIGHT=0 WIDTH=0 HOST=`cat /scripts/dialog.out` IP=`grep '$HOST' /etc/hosts | awk '{print $1}'` display_result() { dialog --title "$1" \ --no-collapse \ --msgbox "$result" 0 0 } while true; do exec 3>&1 selection=$(dialog \ --backtitle "" \ --title "MENU" \ --clear \ --cancel-label "EXIT" \ --menu "SELECT OPTION:" $HEIGHT $WIDTH 6 \ "1" "SW1" \ "2" "SW2" \ "3" "SW3" \ 2>&1>/scripts/dialog.out 1>&3) exit_status=$? exec 3>&- case $exit_status in $DIALOG_CANCEL) clear exit ;; $DIALOG_ESC) clear echo "Program aborted." >&2 exit 1 ;; esac case $selection in 0 ) clear echo "Program terminated." ;; 1 ) ssh admin@$IP ;; esac done
當使用 with 編寫腳本
--menu
時dialog
,菜單中的第一列是一個標籤,您可以選擇是否顯示。當菜單正常時,dialog
將這些標籤寫入其輸出(通常為標準錯誤,但該--stdout
選項有幫助)。如果將 IP 地址設置為標籤,則可以直接從 running 獲取地址
dialog
。在手冊中,此處描述了此可選功能:
--no-items Some widgets (checklist, inputmenu, radiolist, menu) display a list with two columns (a "tag" and "item", i.e., "description"). This option tells dialog to read shorter rows, omitting the "item" part of the list. This is occasionally useful, e.g., if the tags provide enough information. See also --no-tags. If both options are given, this one is ig- nored.
和
--no-tags Some widgets (checklist, inputmenu, radiolist, menu) display a list with two columns (a "tag" and "description"). The tag is useful for scripting, but may not help the user. The --no-tags option (from Xdialog) may be used to suppress the column of tags from the display. Unlike the --no-items option, this does not affect the data which is read from the script. Xdialog does not display the tag column for the analogous buildlist and treeview widgets; dialog does the same. Normally dialog allows you to quickly move to entries on the displayed list, by matching a single character to the first character of the tag. When the --no-tags option is given, dia- log matches against the first character of the description. In either case, the matchable character is highlighted.
您可以通過各種方式選擇行
/etc/hosts
,例如,使用sed
:sed -e '1,/# ETHERNET SWITCHES/d' -e '/# END SWITCHES/,9999d' /etc/hosts
你可以將它重定向到你的命令行中,方法
dialog
是把它放在$(
and中)
。通過將快捷方式 1、2、3 與描述中的 SW1、SW2、SW3 組合併使用該
--no-tags
選項,您可以保持 IP 地址和描述相關聯。您想到的範例可能是這樣的:
#!/bin/bash INPUT=/etc/hosts let i=0 # define counting variable W=() # define working array while read -r addr line; do # process file by file let i=$i+1 W+=($addr "$i $line") done < <( sed -e '1,/# ETHERNET SWITCHES/d' -e '/# END SWITCHES/,9999d' $INPUT ) FILE=$(dialog --stdout --no-tags --title "List of Switches in /etc/hosts file" --menu "Chose one" 24 80 17 "${W[@]}" ) # show dialog and store output clear if [ $? -eq 0 ]; then # Exit with OK ssh $FILE fi