一些Cygwin/WSL,BASH脚本hook函数,nc、ping、mysql、wmysql等;


ping

使ping命令参数支持网址形式,直接在命令行ping一个网址,显示其服务器信息(当然了,也有可能是CDN节点),同时在ping域名的同时,检查改域名是否在hosts文件中进行了重定向,如果域名被hosts文件制定了解析给出提示...

ping() {
	if [ $# -eq 1 ] && [[ "$1" =~ "/" ]];then
	#if [ $# -eq 1 ] && [[ "$1" =~ ^http ]];then
		host=$(/usr/bin/env python3 /v/bin/python-parseurl.py "$1")
		[ ! -z "$host" ] && _ping $host
	else
		_ping $@
	fi
}

附:依赖的python-parseurl.py源码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#解析一个URL,仅输出host部分
import sys
from urllib.parse import urlparse

if len(sys.argv)==2:
        url=str(sys.argv[1]).strip()
else:
        url=""

if not (url.startswith("http") or url.startswith("ftp://")):
        url="{}{}".format("http://",url)

parsed = urlparse(url)
print(parsed.netloc)


_ping

ping域名之前检查域名是否被hosts文件重定向,如果有,则进行提示;
注:即便hosts文件中有此域名,但用#注释掉的解析行会被忽略(因为没有被重定向),不进行提示;


_ping(){
	# 检查域名是否被hosts文件劫持
	local winHosts="$SYSTEMROOT\\System32\\drivers\\etc\\hosts"
	local target="${@:$#}"
	if [[ ! "$target" =~ ^\- ]];
	then
		#grep -vE '^\s*\t*#' $winHosts|awk '{print $NF}'|grep -i $target >/dev/null 2>&1
		awk '!/^\s*\t*#|^$/{gsub("\r","");print $NF}' $winHosts|grep -ix "$target" >/dev/null 2>&1
		if [ $? -eq 0 ];
		then
			print_color 41 "Notice:$target 被hosts文件重定向...!"
		fi	
	fi
	/usr/bin/ping $@
}

nc

默认nc命令的使用格式为nc -v www.baidu.com 443,此函数使nc命令支持地址和端口连在一起的情况,比如nc -v www.baidu.com:443;

##覆盖默认nc命令,使之可以直接使用ip和端口粘在一起的参数形式:eg:nc -v 127.0.0.1:80
nc() {
	if [[ "${@:$#}" =~ ^.+:[0-9]{1,5}$ ]];then
		echo "参数粘连,分开解析地址和端口..."
		local addr=$(echo "${@:$#}"|cut -d ':' -f 1)
		local port=$(echo "${@:$#}"|cut -d ':' -f 2)
		declare -a options
		while [ $# -gt 1 ]; #最后一个参数不使用,去除之,并保留前面的所有参数
		do
			options=(${options[@]} $1)
			shift
		done
		/usr/bin/nc ${options[@]} $addr $port
	else
		/usr/bin/nc $@
	fi
}


MySQL

mysql不带命令行参数时,直接使用默认用户名和密码root登录MySQL命令行终端;方便快捷地进行本地开发;

mysql() {
	#hookmysql命令,使用默认用户名和密码连接本地MySQL主机
	if [ $# -eq 0 ];then
		/usr/bin/mysql -h127.0.0.1 -uroot -proot
	else
		/usr/bin/mysql $@
	fi
}

wmysql

作用:方便在Cygwin,WSL终端窗口中直接使用Windows版的mysql命令,(因Windows版的MySQL和Posix规范的MySQL命令存在操作效果上的差异);
一些差异列举:
比如:
1、Windows版的MYSQL无法Ctrl+L清屏,Ctrl+D退出会话等其他快捷键,Posix版的MySQL命令完美响应Bash下各种快捷键;
2、Windows版的MYSQL在命令行中输入中文汉字正常,Posix版的MYSQL无法直接输入中文,必须从外部文件导入;
etc...

wmysql() {
	#在mintty中使用Windows版MySQL的命令行链接Windows MySQL主机
	#需要此函数原因是使用Cygwin版本的mysql连接到Windows mysqld后无法输入和粘贴中文;
	local apppath="D:\UPUPW_ANK_W64\Modules\MySQL\bin\mysql.exe"
	if [ -e "${apppath}" ];then
		#`cygpath -au "$apppath"` $@
		`cygpath -au "$apppath"` --default-character-set=utf8mb4 $@	
	else
		local MySQLDBIN=$(wmicps mysqld.exe 2>/dev/null|dos2unix -q|iconv -f GBK -t utf-8|awk -F '=' '/ExecutablePath=/{sub($1"=","");print $0;exit;}')
		if [ -e "$MySQLDBIN" ];then
			`cygpath -au "${MySQLDBIN/mysqld.exe/mysql.exe}"` $@
			return
		fi
		echo -e "program not found!\npath:${apppath//\\/\\\\} "
	fi
}
alias wmysql2='wmysql -h127.0.0.1 -uroot -proot'
alias wmysqluser='wmysql2'