10個增加UNIX/Linux Shell腳本趣味的工具
有些誤解認(rèn)為 shell 腳本僅用于 CLI 環(huán)境。實(shí)際上在 KDE 或 Gnome 桌面下,你可以有效的使用各種工具編寫 GUI 或者網(wǎng)絡(luò)(socket)腳本。shell 腳本可以使用一些 GUI 組件(菜單、警告框、進(jìn)度條等),你可以控制終端輸出、光標(biāo)位置以及各種輸出效果等等。利用下面的工具,你可以構(gòu)建強(qiáng)壯的、可交互的、對用戶友好的 UNIX/Linux bash 腳本。
制作 GUI 應(yīng)用不是一項困難的任務(wù),但需要時間和耐心。幸運(yùn)的是,UNIX 和 Linux 都帶有大量編寫漂亮 GUI 腳本的工具。以下工具是基于 FreeBSD 和 Linux 操作系統(tǒng)做的測試,而且也適用于其他類 UNIX 操作系統(tǒng)。
1、notify-send 命令
notify-send 命令允許你借助通知守護(hù)進(jìn)程發(fā)送桌面通知給用戶。這種避免打擾用戶的方式,對于通知桌面用戶一個事件或顯示一些信息是有用的。在 Debian 或 Ubuntu 上,你需要使用 apt 命令 或 apt-get 命令 安裝的包:
sudo apt-get install libnotify-bin
CentOS/RHEL 用戶使用下面的 yum 命令:
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 :)"
示例輸出:

notify-send: Shell Script Get Or Send Desktop Notifications
下面是另一個附加選項的代碼:
...alert=18000live=$(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 screentput clear# Move cursor to screen location X,Y (top left is 0,0)tput cup 3 15# Set a foreground colour using ANSI escapetput setaf 3echo "XYX Corp LTD."tput sgr0tput cup 5 17# Set reverse video modetput revecho "M A I N - M E N U"tput sgr0tput cup 7 15echo "1. User Management"tput cup 8 15echo "2. Service Management"tput cup 9 15echo "3. Process Management"tput cup 10 15echo "4. Backup"# Set bold modetput boldtput cup 12 15read -p "Enter your choice [1-4] " choicetput cleartput sgr0tput rc
示例輸出:

Linux / UNIX Script Colours and Cursor Movement With tput
關(guān)于 tput 命令的詳細(xì)信息,參見手冊:
man 5 terminfoman 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+ 對話框,并且返回用戶輸入。它允許你使用各種 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 databasewhois $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 --helpman 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 腳本編程》 教程獲取更多信息。
6、Dialog
Dialog 是一個使用 Shell 腳本的應(yīng)用,顯示用戶界面組件的文本。它使用 curses 或者 ncurses 庫。下面是一個示例代碼:
#!/bin/bashdialog --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 in0) echo "File deleted.";;1) echo "File not deleted.";;255) echo "[ESC] key pressed.";;esac
參見 dialog 手冊獲取詳細(xì)信息: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/messageslogger -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 normalApr 20 00:12:20 vivek-desktop mysqld: Database Server failed
參見 《如何寫消息到 syslog 或 日志文件》 獲得更多信息。此外,你也可以查看 logger 手冊獲取詳細(xì)信息:man logger 
8、setterm 命令
setterm 命令可設(shè)置不同的終端屬性。下面的示例代碼會強(qiáng)制屏幕在 15 分鐘后變黑,監(jiān)視器則 60 分鐘后待機(jī)。
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 命令手冊獲取詳細(xì)信息:man setterm 
9、smbclient:給 MS-Windows 工作站發(fā)送消息
smbclient 命令可以與 SMB/CIFS 服務(wù)器通訊。它可以向 MS-Windows 系統(tǒng)上選定或全部用戶發(fā)送消息。
smbclient -M WinXPPro <<eofMessage 1Message 2.....EOF
或
echo "${Message}" | smbclient -M salesguy2
參見 smbclient 手冊或者閱讀我們之前發(fā)布的文章:《給 Windows 工作站發(fā)送消息》:man smbclient 
10、Bash 套接字編程
在 bash 下,你可以打開一個套接字并通過它發(fā)送數(shù)據(jù)。你不必使用 curl 或者 lynx 命令抓取遠(yuǎn)程服務(wù)器的數(shù)據(jù)。bash 和兩個特殊的設(shè)備文件可用于打開網(wǎng)絡(luò)套接字。以下選自 bash 手冊:
/dev/tcp/host/port- 如果host是一個有效的主機(jī)名或者網(wǎng)絡(luò)地址,而且端口是一個整數(shù)或者服務(wù)名,bash 會嘗試打開一個相應(yīng)的 TCP 連接套接字。/dev/udp/host/port- 如果host是一個有效的主機(jī)名或者網(wǎng)絡(luò)地址,而且端口是一個整數(shù)或者服務(wù)名,bash 會嘗試打開一個相應(yīng)的 UDP 連接套接字。
你可以使用這項技術(shù)來確定本地或遠(yuǎn)程服務(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)找出已打開的端口:
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 open53 open80 open139 open445 open631 open
下面的示例中,你的 bash 腳本將像 HTTP 客戶端一樣工作:
#!/bin/bashexec 3<> /dev/tcp/${1:-www.cyberciti.biz}/80printf "GET / HTTP/1.0\r\n" >&3printf "Accept: text/html, text/plain\r\n" >&3printf "Accept-Language: en\r\n" >&3printf "User-Agent: nixCraft_BashScript v.%s\r\n" "${BASH_VERSION}" >&3printf "\r\n" >&3while read LINE <&3do# do something on $LINE# or send $LINE to grep or awk for grabbing data# or simply display back data with echo commandecho $LINEdone
參見 bash 手冊獲取更多信息:man bash 
關(guān)于 GUI 工具和 cron 任務(wù)的注意事項
如果你 使用 crontab 來啟動你的腳本,你需要使用 export DISPLAY=[用戶機(jī)器]:0 命令請求本地顯示或輸出服務(wù)。舉個例子,使用 zenity 工具調(diào)用 /home/vivek/scripts/monitor.stock.sh:
@hourly DISPLAY=:0.0 /home/vivek/scripts/monitor.stock.sh
 
 
 
 














 
 









 