10个增加UNIX/Linux Shell脚本趣味的工具

系统 Linux
有些误解认为 shell 脚本仅用于CLI环境。实际上在 KDE 或 Gnome 桌面下,你可以有效的使用各种工具编写 GUI 或者网络脚本。shell 脚本可以使用一些GUI 件,你可以控制终端输出、光标位置以及各种输出效果等等。利用下面的工具,你可以构建强壮的、可交互的、对用户友好的 UNIX/Linux bash 脚本。

[[224865]]

有些误解认为 shell 脚本仅用于 CLI 环境。实际上在 KDE 或 Gnome 桌面下,你可以有效的使用各种工具编写 GUI 或者网络(socket)脚本。shell 脚本可以使用一些 GUI 组件(菜单、警告框、进度条等),你可以控制终端输出、光标位置以及各种输出效果等等。利用下面的工具,你可以构建强壮的、可交互的、对用户友好的 UNIX/Linux bash 脚本。

制作 GUI 应用不是一项困难的任务,但需要时间和耐心。幸运的是,UNIX 和 Linux 都带有大量编写漂亮 GUI 脚本的工具。以下工具是基于 FreeBSD 和 Linux 操作系统做的测试,而且也适用于其他类 UNIX 操作系统。 

1、notify-send 命令

notify-send 命令允许你借助通知守护进程发送桌面通知给用户。这种避免打扰用户的方式,对于通知桌面用户一个事件或显示一些信息是有用的。在 Debian 或 Ubuntu 上,你需要使用 apt 命令apt-get 命令 安装的包:

  1. sudo apt-get install libnotify-bin

CentOS/RHEL 用户使用下面的 yum 命令

  1. sudo yum install libnotify

Fedora Linux 用户使用下面的 dnf 命令:

  1. `$ sudo dnf install libnotify`
  2. In this example, send simple desktop notification from the command line, enter:
  3. ### 发送一些通知 ###
  4. notify-send "rsnapshot done :)"

示例输出:

Fig:01: notify-send in action

notify-send: Shell Script Get Or Send Desktop Notifications

下面是另一个附加选项的代码:

  1. ...
  2. alert=18000
  3. live=$(lynx --dump http://money.rediff.com/ | grep 'BSE LIVE' | awk '{ print $5}' | sed 's/,//g;s/\.[0-9]*//g')
  4. [ $notify_counter -eq 0 ] && [ $live -ge $alert ] && { notify-send -t 5000 -u low -i "BSE Sensex touched 18k"; notify_counter=1; }
  5. ...

示例输出:

Fig.02: notify-send with timeouts and other options

Linux / UNIX: Display Notifications From Your Shell Scripts With notify-send

这里:

  • -t 5000:指定超时时间(毫秒) (5000 毫秒 = 5 秒)
  • -u low: 设置紧急等级 (如:低、普通、紧急)
  • -i gtk-dialog-info: 设置要显示的图标名称或者指定的图标(你可以设置路径为:-i /path/to/your-icon.png

关于更多使用 notify-send 功能的信息,请参考 man 手册。在命令行下输入 man notify-send 即可看见:

  1. man notify-send 

2、tput 命令

tput 命令用于设置终端特性。通过 tput 你可以设置:

  • 在屏幕上移动光标。
  • 获取终端信息。
  • 设置颜色(背景和前景)。
  • 设置加粗模式。
  • 设置反转模式等等。

下面有一段示例代码:

  1. #!/bin/bash
  2.  
  3. # clear the screen
  4. tput clear
  5.  
  6. # Move cursor to screen location X,Y (top left is 0,0)
  7. tput cup 3 15
  8.  
  9. # Set a foreground colour using ANSI escape
  10. tput setaf 3
  11. echo "XYX Corp LTD."
  12. tput sgr0
  13.  
  14. tput cup 5 17
  15. # Set reverse video mode
  16. tput rev
  17. echo "M A I N - M E N U"
  18. tput sgr0
  19.  
  20. tput cup 7 15
  21. echo "1. User Management"
  22.  
  23. tput cup 8 15
  24. echo "2. Service Management"
  25.  
  26. tput cup 9 15
  27. echo "3. Process Management"
  28.  
  29. tput cup 10 15
  30. echo "4. Backup"
  31.  
  32. # Set bold mode
  33. tput bold
  34. tput cup 12 15
  35. read -p "Enter your choice [1-4] " choice
  36.  
  37. tput clear
  38. tput sgr0
  39. tput rc

示例输出:

Fig.03: tput in action

Linux / UNIX Script Colours and Cursor Movement With tput

关于 tput 命令的详细信息,参见手册:

  1. man 5 terminfo
  2. man tput 

3、setleds 命令

setleds 命令允许你设置键盘灯。下面是打开数字键灯的示例:

  1. setleds -D +num

关闭数字键灯,输入:

  1. setleds -D -num
  • -caps:关闭大小写锁定灯
  • +caps:打开大小写锁定灯
  • -scroll:关闭滚动锁定灯
  • +scroll:打开滚动锁定灯

查看 setleds 手册可看见更多信息和选项 man setleds。 

4、zenity 命令

zenity 命令显示 GTK+ 对话框,并且返回用户输入。它允许你使用各种 Shell 脚本向用户展示或请求信息。下面是一个 whois 指定域名目录服务的 GUI 客户端示例。

  1. #!/bin/bash
  2. # Get domain name
  3. _zenity="/usr/bin/zenity"
  4. _out="/tmp/whois.output.$$"
  5. domain=$(${_zenity} --title "Enter domain" \
  6. --entry --text "Enter the domain you would like to see whois info" )
  7.  
  8. if [ $? -eq 0 ]
  9. then
  10. # Display a progress dialog while searching whois database
  11. whois $domain | tee >(${_zenity} --width=200 --height=100 \
  12. --title="whois" --progress \
  13. --pulsate --text="Searching domain info..." \
  14. --auto-kill --auto-close \
  15. --percentage=10) >${_out}
  16.  
  17. # Display back output
  18. ${_zenity} --width=800 --height=600 \
  19. --title "Whois info for $domain" \
  20. --text-info --filename="${_out}"
  21. else
  22. ${_zenity} --error \
  23. --text="No input provided"
  24. fi

示例输出:

Fig.04: zenity in Action

zenity: Linux / UNIX display Dialogs Boxes From The Shell Scripts

参见手册获取更多 zenity 信息以及其他支持 GTK+ 的组件:

  1. zenity --help
  2. man zenity 

5、kdialog 命令

kdialog 命令与 zenity 类似,但它是为 KDE 桌面和 QT 应用设计。你可以使用 kdialog 展示对话框。下面示例将在屏幕上显示信息:

  1. kdialog --dontagain myscript:nofilemsg --msgbox "File: '~/.backup/config' not found."

示例输出:

Fig.05: Suppressing the display of a dialog

Kdialog: Suppressing the display of a dialog

参见 《KDE 对话框 Shell 脚本编程》 教程获取更多信息。 

6、Dialog

Dialog 是一个使用 Shell 脚本的应用,显示用户界面组件的文本。它使用 curses 或者 ncurses 库。下面是一个示例代码:

  1. #!/bin/bash
  2. dialog --title "Delete file" \
  3. --backtitle "Linux Shell Script Tutorial Example" \
  4. --yesno "Are you sure you want to permanently delete \"/tmp/foo.txt\"?" 7 60
  5.  
  6. # Get exit status
  7. # 0 means user hit [yes] button.
  8. # 1 means user hit [no] button.
  9. # 255 means user hit [Esc] key.
  10. response=$?
  11. case $response in
  12. 0) echo "File deleted.";;
  13. 1) echo "File not deleted.";;
  14. 255) echo "[ESC] key pressed.";;
  15. esac

参见 dialog 手册获取详细信息:man dialog。 

关于其他用户界面工具的注意事项

UNIX、Linux 提供了大量其他工具来显示和控制命令行中的应用程序,shell 脚本可以使用一些 KDE、Gnome、X 组件集:

  • gmessage - 基于 GTK xmessage 的克隆
  • xmessage - 在窗口中显示或询问消息(基于 X 的 /bin/echo)
  • whiptail - 显示来自 shell 脚本的对话框
  • python-dialog - 用于制作简单文本或控制台模式用户界面的 Python 模块 

7、logger 命令

logger 命令将信息写到系统日志文件,如:/var/log/messages。它为系统日志模块 syslog 提供了一个 shell 命令行接口:

  1. logger "MySQL database backup failed."
  2. tail -f /var/log/messages
  3. logger -t mysqld -p daemon.error "Database Server failed"
  4. tail -f /var/log/syslog

示例输出:

  1. Apr 20 00:11:45 vivek-desktop kernel: [38600.515354] CPU0: Temperature/speed normal
  2. Apr 20 00:12:20 vivek-desktop mysqld: Database Server failed

参见 《如何写消息到 syslog 或 日志文件》 获得更多信息。此外,你也可以查看 logger 手册获取详细信息:man logger 

8、setterm 命令

setterm 命令可设置不同的终端属性。下面的示例代码会强制屏幕在 15 分钟后变黑,监视器则 60 分钟后待机。

  1. setterm -blank 15 -powersave powerdown -powerdown 60

下面的例子将 xterm 窗口中的文本以下划线展示:

  1. setterm -underline on;
  2. echo "Add Your Important Message Here"
  3. setterm -underline off

另一个有用的选项是打开或关闭光标显示:

  1. setterm -cursor off

打开光标:

  1. setterm -cursor on

参见 setterm 命令手册获取详细信息:man setterm 

9、smbclient:给 MS-Windows 工作站发送消息

smbclient 命令可以与 SMB/CIFS 服务器通讯。它可以向 MS-Windows 系统上选定或全部用户发送消息。

  1. smbclient -M WinXPPro <<eof
  2. Message 1
  3. Message 2
  4. ...
  5. ..
  6. EOF

  1. echo "${Message}" | smbclient -M salesguy2

参见 smbclient 手册或者阅读我们之前发布的文章:《给 Windows 工作站发送消息》:man smbclient 

10、Bash 套接字编程

在 bash 下,你可以打开一个套接字并通过它发送数据。你不必使用 curl 或者 lynx 命令抓取远程服务器的数据。bash 和两个特殊的设备文件可用于打开网络套接字。以下选自 bash 手册:

  1. /dev/tcp/host/port - 如果 host 是一个有效的主机名或者网络地址,而且端口是一个整数或者服务名,bash 会尝试打开一个相应的 TCP 连接套接字。
  2. /dev/udp/host/port - 如果 host 是一个有效的主机名或者网络地址,而且端口是一个整数或者服务名,bash 会尝试打开一个相应的 UDP 连接套接字。

你可以使用这项技术来确定本地或远程服务器端口是打开或者关闭状态,而无需使用 nmap 或者其它的端口扫描器。

  1. # find out if TCP port 25 open or not
  2. (echo >/dev/tcp/localhost/25) &>/dev/null && echo "TCP port 25 open" || echo "TCP port 25 close"

下面的代码片段,你可以利用 bash 循环找出已打开的端口

  1. echo "Scanning TCP ports..."
  2. for p in {1..1023}
  3. do
  4. (echo >/dev/tcp/localhost/$p) >/dev/null 2>&1 && echo "$p open"
  5. done

示例输出:

  1. Scanning TCP ports...
  2. 22 open
  3. 53 open
  4. 80 open
  5. 139 open
  6. 445 open
  7. 631 open

下面的示例中,你的 bash 脚本将像 HTTP 客户端一样工作:

  1. #!/bin/bash
  2. exec 3<> /dev/tcp/${1:-www.cyberciti.biz}/80
  3.  
  4. printf "GET / HTTP/1.0\r\n" >&3
  5. printf "Accept: text/html, text/plain\r\n" >&3
  6. printf "Accept-Language: en\r\n" >&3
  7. printf "User-Agent: nixCraft_BashScript v.%s\r\n" "${BASH_VERSION}" >&3
  8. printf "\r\n" >&3
  9.  
  10. while read LINE <&3
  11. do
  12. # do something on $LINE
  13. # or send $LINE to grep or awk for grabbing data
  14. # or simply display back data with echo command
  15. echo $LINE
  16. done

参见 bash 手册获取更多信息:man bash 

关于 GUI 工具和 cron 任务的注意事项

如果你 使用 crontab 来启动你的脚本,你需要使用 export DISPLAY=[用户机器]:0 命令请求本地显示或输出服务。举个例子,使用 zenity 工具调用 /home/vivek/scripts/monitor.stock.sh

  1. @hourly DISPLAY=:0.0 /home/vivek/scripts/monitor.stock.sh
责任编辑:庞桂玉 来源: Linux中国
相关推荐

2014-03-13 16:34:04

LinuxBashKSH shel

2010-03-23 16:35:31

shell 脚本编程

2022-08-30 08:52:04

shell脚本Linux

2020-06-16 09:02:36

Linux Shell脚本

2014-05-28 09:26:57

Linux Shellshell脚本

2014-07-25 17:21:43

Linux Shell面试

2018-02-01 17:32:30

LinuxUNIXBash Shell

2009-09-29 10:45:17

UnixLinuxshell

2010-04-16 14:46:22

2009-10-23 13:44:03

linux Shell

2011-05-11 09:29:43

LinuxUnix

2010-06-23 15:55:36

Linux Bash

2021-05-12 10:17:15

Shell工具Linux

2016-10-31 08:35:20

LinuxUnix

2019-08-09 13:50:08

shellLinux

2013-06-13 11:07:52

2017-08-11 17:20:07

LinuxShell

2018-08-28 16:02:59

LinuxShellBash

2017-06-19 15:46:08

LinuxBash脚本技巧

2019-12-12 10:23:34

Linux 代码 开发
点赞
收藏

51CTO技术栈公众号