有些誤解認為 shell 腳本僅用于 CLI 環(huán)境。實際上在 KDE 或 Gnome 桌面下,你可以有效的使用各種工具編寫 GUI 或者網(wǎng)絡(luò)(socket)腳本。shell 腳本可以使用一些 GUI 組件(菜單、警告框、進度條等),你可以控制終端輸出、光標(biāo)位置以及各種輸出效果等等。利用下面的工具,你可以構(gòu)建強壯的、可交互的、對用戶友好的 UNIX/Linuxbash 腳本。
制作 GUI 應(yīng)用不是一項困難的任務(wù),但需要時間和耐心。幸運的是,UNIX 和 Linux 都帶有大量編寫漂亮 GUI 腳本的工具。以下工具是基于 FreeBSD 和 Linux 操作系統(tǒng)做的測試,而且也適用于其他類 UNIX 操作系統(tǒng)。
1、notify-send 命令
notify-send命令允許你借助通知守護進程發(fā)送桌面通知給用戶。這種避免打擾用戶的方式,對于通知桌面用戶一個事件或顯示一些信息是有用的。在 Debian 或 Ubuntu 上,你需要使用apt 命令[1]或apt-get 命令[2]安裝的包:
sudo apt-get install libnotify-bin
CentOS/RHEL 用戶使用下面的yum 命令[3]:
sudo yum install libnotify
Fedora Linux 用戶使用下面的 dnf 命令:
`$ sudo dnf install libnotify` In this example, send simple desktop notification from the command line, enter: ### 發(fā)送一些通知 ### notify-send "rsnapshot done :)"
示例輸出:
vcWxvsikzra1xLmkvt+8uLj21Pa80yBsaW51eCBzaGVsbCC9xbG+yKTOtrXEuaS+3w==” class=”has” src=”http://www.2cto.com/uploadfile/Collfiles/20180912/20180912093220399.png” />
notify-send: Shell Script Get Or Send Desktop Notifications
下面是另一個附加選項的代碼:
... alert=18000 live=$(lynx --dump http://money.rediff.com/ | grep 'BSE LIVE' | awk '{ print $5}' | sed 's/,//g;s/.[0-9]*//g') [ $notify_counter -eq 0 ] && [ $live -ge $alert ] && { notify-send -t 5000 -u low -i "BSE Sensex touched 18k"; notify_counter=1; } ...
示例輸出:
Linux / UNIX: Display Notifications From Your Shell Scripts With notify-send
這里:
-t 5000:指定超時時間(毫秒) (5000 毫秒 = 5 秒) -u low: 設(shè)置緊急等級 (如:低、普通、緊急) -i gtk-dialog-info: 設(shè)置要顯示的圖標(biāo)名稱或者指定的圖標(biāo)(你可以設(shè)置路徑為:-i /path/to/your-icon.png)
關(guān)于更多使用notify-send功能的信息,請參考 man 手冊。在命令行下輸入man notify-send即可看見:
man notify-send
2、tput 命令
tput命令用于設(shè)置終端特性。通過tput你可以設(shè)置:
在屏幕上移動光標(biāo)。 獲取終端信息。 設(shè)置顏色(背景和前景)。 設(shè)置加粗模式。 設(shè)置反轉(zhuǎn)模式等等。
下面有一段示例代碼:
#!/bin/bash # clear the screen tput clear # Move cursor to screen location X,Y (top left is 0,0) tput cup 3 15 # Set a foreground colour using ANSI escape tput setaf 3 echo "XYX Corp LTD." tput sgr0 tput cup 5 17 # Set reverse video mode tput rev echo "M A I N - M E N U" tput sgr0 tput cup 7 15 echo "1. User Management" tput cup 8 15 echo "2. Service Management" tput cup 9 15 echo "3. Process Management" tput cup 10 15 echo "4. Backup" # Set bold mode tput bold tput cup 12 15 read -p "Enter your choice [1-4] " choice tput clear tput sgr0 tput rc
示例輸出:
Linux / UNIX Script Colours and Cursor Movement With tput
關(guān)于tput命令的詳細信息,參見手冊:
man 5 terminfo man tput
3、setleds 命令
setleds命令允許你設(shè)置鍵盤燈。下面是打開數(shù)字鍵燈的示例:
setleds -D +num
關(guān)閉數(shù)字鍵燈,輸入:
setleds -D -num
-caps:關(guān)閉大小寫鎖定燈 +caps:打開大小寫鎖定燈 -scroll:關(guān)閉滾動鎖定燈 +scroll:打開滾動鎖定燈
查看setleds手冊可看見更多信息和選項man setleds。
4、zenity 命令
zenity 命令顯示 GTK+ 對話框[4],并且返回用戶輸入。它允許你使用各種 Shell 腳本向用戶展示或請求信息。下面是一個whois指定域名目錄服務(wù)的 GUI 客戶端示例。
#!/bin/bash # Get domain name _zenity="/usr/bin/zenity" _out="/tmp/whois.output.$$" domain=$(${_zenity} --title "Enter domain" --entry --text "Enter the domain you would like to see whois info" ) if [ $ -eq 0 ] then # Display a progress dialog while searching whois database whois $domain | tee >(${_zenity} --width=200 --height=100 --title="whois" --progress --pulsate --text="Searching domain info..." --auto-kill --auto-close --percentage=10) >${_out} # Display back output ${_zenity} --width=800 --height=600 --title "Whois info for $domain" --text-info --filename="${_out}" else ${_zenity} --error --text="No input provided" fi
示例輸出:
zenity: Linux / UNIX display Dialogs Boxes From The Shell Scripts
參見手冊獲取更多zenity信息以及其他支持 GTK+ 的組件:
zenity --help man zenity
5、kdialog 命令
kdialog命令與zenity類似,但它是為 KDE 桌面和 QT 應(yīng)用設(shè)計。你可以使用kdialog展示對話框。下面示例將在屏幕上顯示信息:
kdialog --dontagain myscript:nofilemsg --msgbox "File: '~/.backup/config' not found."
示例輸出:
Kdialog: Suppressing the display of a dialog
參見 《KDE 對話框 Shell 腳本編程[5]》 教程獲取更多信息。
6、Dialog
Dialog 是一個使用 Shell 腳本的應(yīng)用[6],顯示用戶界面組件的文本。它使用 curses 或者 ncurses 庫。下面是一個示例代碼:
#!/bin/bash dialog --title "Delete file" --backtitle "Linux Shell Script Tutorial Example" --yesno "Are you sure you want to permanently delete "/tmp/foo.txt"" 7 60 # Get exit status # 0 means user hit [yes] button. # 1 means user hit [no] button. # 255 means user hit [Esc] key. response=$ case $response in 0) echo "File deleted.";; 1) echo "File not deleted.";; 255) echo "[ESC] key pressed.";; esac
參見dialog手冊獲取詳細信息:man dialog。
關(guān)于其他用戶界面工具的注意事項
UNIX、Linux 提供了大量其他工具來顯示和控制命令行中的應(yīng)用程序,shell 腳本可以使用一些 KDE、Gnome、X 組件集:
gmessage- 基于 GTK xmessage 的克隆 xmessage- 在窗口中顯示或詢問消息(基于 X 的 /bin/echo) whiptail- 顯示來自 shell 腳本的對話框 python-dialog- 用于制作簡單文本或控制臺模式用戶界面的 Python 模塊
7、logger 命令
logger命令將信息寫到系統(tǒng)日志文件,如:/var/log/messages。它為系統(tǒng)日志模塊 syslog 提供了一個 shell 命令行接口:
logger "MySQL database backup failed." tail -f /var/log/messages logger -t mysqld -p daemon.error "Database Server failed" tail -f /var/log/syslog
示例輸出:
Apr 20 00:11:45 vivek-desktop kernel: [38600.515354] CPU0: Temperature/speed normal Apr 20 00:12:20 vivek-desktop mysqld: Database Server failed
參見 《如何寫消息到 syslog 或 日志文件[7]》 獲得更多信息。此外,你也可以查看 logger 手冊獲取詳細信息:man logger
8、setterm 命令
setterm命令可設(shè)置不同的終端屬性。下面的示例代碼會強制屏幕在 15 分鐘后變黑,監(jiān)視器則 60 分鐘后待機。
setterm -blank 15 -powersave powerdown -powerdown 60
下面的例子將 xterm 窗口中的文本以下劃線展示:
setterm -underline on; echo "Add Your Important Message Here" setterm -underline off
另一個有用的選項是打開或關(guān)閉光標(biāo)顯示:
setterm -cursor off
打開光標(biāo):
setterm -cursor on
參見 setterm 命令手冊獲取詳細信息:man setterm
9、smbclient:給 MS-Windows 工作站發(fā)送消息
smbclient命令可以與 SMB/CIFS 服務(wù)器通訊。它可以向 MS-Windows 系統(tǒng)上選定或全部用戶發(fā)送消息。
smbclient -M WinXPPro <或
echo "${Message}" | smbclient -M salesguy2參見smbclient手冊或者閱讀我們之前發(fā)布的文章:《給 Windows 工作站發(fā)送消息[8]》:man smbclient
10、Bash 套接字編程
在 bash 下,你可以打開一個套接字并通過它發(fā)送數(shù)據(jù)。你不必使用curl或者lynx命令抓取遠程服務(wù)器的數(shù)據(jù)。bash 和兩個特殊的設(shè)備文件可用于打開網(wǎng)絡(luò)套接字。以下選自 bash 手冊:
/dev/tcp/host/port- 如果host是一個有效的主機名或者網(wǎng)絡(luò)地址,而且端口是一個整數(shù)或者服務(wù)名,bash 會嘗試打開一個相應(yīng)的 TCP 連接套接字。 /dev/udp/host/port- 如果host是一個有效的主機名或者網(wǎng)絡(luò)地址,而且端口是一個整數(shù)或者服務(wù)名,bash 會嘗試打開一個相應(yīng)的 UDP 連接套接字。
你可以使用這項技術(shù)來確定本地或遠程服務(wù)器端口是打開或者關(guān)閉狀態(tài),而無需使用nmap或者其它的端口掃描器。
# find out if TCP port 25 open or not (echo >/dev/tcp/localhost/25) &>/dev/null && echo "TCP port 25 open" || echo "TCP port 25 close"下面的代碼片段,你可以利用bash 循環(huán)找出已打開的端口[9]:
echo "Scanning TCP ports..." for p in {1..1023} do (echo >/dev/tcp/localhost/$p) >/dev/null 2>&1 && echo "$p open" done示例輸出:
Scanning TCP ports... 22 open 53 open 80 open 139 open 445 open 631 open下面的示例中,你的 bash 腳本將像 HTTP 客戶端一樣工作:
#!/bin/bash exec 3<> /dev/tcp/${1:-www.cyberciti.biz}/80 printf "GET / HTTP/1.0rn" >&3 printf "Accept: text/html, text/plainrn" >&3 printf "Accept-Language: enrn" >&3 printf "User-Agent: nixCraft_BashScript v.%srn" "${BASH_VERSION}" >&3 printf "rn" >&3 while read LINE <&3 do # do something on $LINE # or send $LINE to grep or awk for grabbing data # or simply display back data with echo command echo $LINE done參見 bash 手冊獲取更多信息:man bash
關(guān)于 GUI 工具和 cron 任務(wù)的注意事項
如果你使用 crontab[10]來啟動你的腳本,你需要使用export DISPLAY=[用戶機器]:0命令請求本地顯示或輸出服務(wù)。舉個例子,使用zenity工具調(diào)用/home/vivek/scripts/monitor.stock.sh:
@hourly DISPLAY=:0.0 /home/vivek/scripts/monitor.stock.sh你有喜歡的可以增加 shell 腳本趣味的 UNIX 工具么?請在下面的評論區(qū)分享它吧。
關(guān)于作者
本文作者是 nixCraft 創(chuàng)始人、一個老練的系統(tǒng)管理員、Linux 操作系統(tǒng)和 UNIX shell 編程培訓(xùn)師。他服務(wù)來自全球的客戶和不同的行業(yè),包括 IT 、教育、防務(wù)和空間探索、還有非營利組織。你可以在Twitter[11],F(xiàn)acebook[12],Google+[13]上面關(guān)注他。