10個(gè)增加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)壯的、可交互的、對(duì)用戶友好的 UNIX/Linux bash 腳本。
制作 GUI 應(yīng)用不是一項(xiàng)困難的任務(wù),但需要時(shí)間和耐心。幸運(yùn)的是,UNIX 和 Linux 都帶有大量編寫漂亮 GUI 腳本的工具。以下工具是基于 FreeBSD 和 Linux 操作系統(tǒng)做的測(cè)試,而且也適用于其他類 UNIX 操作系統(tǒng)。
1、notify-send 命令
notify-send
命令允許你借助通知守護(hù)進(jìn)程發(fā)送桌面通知給用戶。這種避免打擾用戶的方式,對(duì)于通知桌面用戶一個(gè)事件或顯示一些信息是有用的。在 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
下面是另一個(gè)附加選項(xiàng)的代碼:
...
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
:指定超時(shí)時(shí)間(毫秒) (5000 毫秒 = 5 秒)-u low
: 設(shè)置緊急等級(jí) (如:低、普通、緊急)-i gtk-dialog-info
: 設(shè)置要顯示的圖標(biāo)名稱或者指定的圖標(biāo)(你可以設(shè)置路徑為:-i /path/to/your-icon.png
)
關(guān)于更多使用 notify-send
功能的信息,請(qǐng)參考 man 手冊(cè)。在命令行下輸入 man notify-send
即可看見:
man notify-send
2、tput 命令
tput
命令用于設(shè)置終端特性。通過 tput
你可以設(shè)置:
- 在屏幕上移動(dòng)光標(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
命令的詳細(xì)信息,參見手冊(cè):
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)閉滾動(dòng)鎖定燈+scroll
:打開滾動(dòng)鎖定燈
查看 setleds
手冊(cè)可看見更多信息和選項(xiàng) man setleds
。
4、zenity 命令
zenity 命令顯示 GTK+ 對(duì)話框,并且返回用戶輸入。它允許你使用各種 Shell 腳本向用戶展示或請(qǐng)求信息。下面是一個(gè) 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
參見手冊(cè)獲取更多 zenity
信息以及其他支持 GTK+ 的組件:
zenity --help
man zenity
5、kdialog 命令
kdialog
命令與 zenity
類似,但它是為 KDE 桌面和 QT 應(yīng)用設(shè)計(jì)。你可以使用 kdialog
展示對(duì)話框。下面示例將在屏幕上顯示信息:
kdialog --dontagain myscript:nofilemsg --msgbox "File: '~/.backup/config' not found."
示例輸出:
Kdialog: Suppressing the display of a dialog
參見 《KDE 對(duì)話框 Shell 腳本編程》 教程獲取更多信息。
6、Dialog
Dialog 是一個(gè)使用 Shell 腳本的應(yīng)用,顯示用戶界面組件的文本。它使用 curses 或者 ncurses 庫。下面是一個(gè)示例代碼:
#!/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
手冊(cè)獲取詳細(xì)信息:man dialog
。
關(guān)于其他用戶界面工具的注意事項(xiàng)
UNIX、Linux 提供了大量其他工具來顯示和控制命令行中的應(yīng)用程序,shell 腳本可以使用一些 KDE、Gnome、X 組件集:
gmessage
- 基于 GTK xmessage 的克隆xmessage
- 在窗口中顯示或詢問消息(基于 X 的 /bin/echo)whiptail
- 顯示來自 shell 腳本的對(duì)話框python-dialog
- 用于制作簡(jiǎn)單文本或控制臺(tái)模式用戶界面的 Python 模塊
7、logger 命令
logger
命令將信息寫到系統(tǒng)日志文件,如:/var/log/messages
。它為系統(tǒng)日志模塊 syslog 提供了一個(gè) 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 或 日志文件》 獲得更多信息。此外,你也可以查看 logger 手冊(cè)獲取詳細(xì)信息:man logger
8、setterm 命令
setterm
命令可設(shè)置不同的終端屬性。下面的示例代碼會(huì)強(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
另一個(gè)有用的選項(xiàng)是打開或關(guān)閉光標(biāo)顯示:
setterm -cursor off
打開光標(biāo):
setterm -cursor on
參見 setterm 命令手冊(cè)獲取詳細(xì)信息:man setterm
9、smbclient:給 MS-Windows 工作站發(fā)送消息
smbclient
命令可以與 SMB/CIFS 服務(wù)器通訊。它可以向 MS-Windows 系統(tǒng)上選定或全部用戶發(fā)送消息。
smbclient -M WinXPPro <<eof
Message 1
Message 2
...
..
EOF
或
echo "${Message}" | smbclient -M salesguy2
參見 smbclient
手冊(cè)或者閱讀我們之前發(fā)布的文章:《給 Windows 工作站發(fā)送消息》:man smbclient
10、Bash 套接字編程
在 bash 下,你可以打開一個(gè)套接字并通過它發(fā)送數(shù)據(jù)。你不必使用 curl
或者 lynx
命令抓取遠(yuǎn)程服務(wù)器的數(shù)據(jù)。bash 和兩個(gè)特殊的設(shè)備文件可用于打開網(wǎng)絡(luò)套接字。以下選自 bash 手冊(cè):
/dev/tcp/host/port
- 如果host
是一個(gè)有效的主機(jī)名或者網(wǎng)絡(luò)地址,而且端口是一個(gè)整數(shù)或者服務(wù)名,bash 會(huì)嘗試打開一個(gè)相應(yīng)的 TCP 連接套接字。/dev/udp/host/port
- 如果host
是一個(gè)有效的主機(jī)名或者網(wǎng)絡(luò)地址,而且端口是一個(gè)整數(shù)或者服務(wù)名,bash 會(huì)嘗試打開一個(gè)相應(yīng)的 UDP 連接套接字。
你可以使用這項(xiàng)技術(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 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.0\r\n" >&3
printf "Accept: text/html, text/plain\r\n" >&3
printf "Accept-Language: en\r\n" >&3
printf "User-Agent: nixCraft_BashScript v.%s\r\n" "${BASH_VERSION}" >&3
printf "\r\n" >&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 手冊(cè)獲取更多信息:man bash
關(guān)于 GUI 工具和 cron 任務(wù)的注意事項(xiàng)
如果你 使用 crontab 來啟動(dòng)你的腳本,你需要使用 export DISPLAY=[用戶機(jī)器]:0
命令請(qǐng)求本地顯示或輸出服務(wù)。舉個(gè)例子,使用 zenity
工具調(diào)用 /home/vivek/scripts/monitor.stock.sh
:
@hourly DISPLAY=:0.0 /home/vivek/scripts/monitor.stock.sh






