Contents
  1. 1. 基础语法
    1. 1.1. 读取文件为参数
    2. 1.2. if-else
    3. 1.3. for 循环
    4. 1.4. 变量与日期
    5. 1.5. Bash 路径通配符
    6. 1.6. Bash 快捷键
    7. 1.7. vi 快捷键
    8. 1.8. 遍历目录下的文件
  2. 2. 文件处理
    1. 2.1. tar
    2. 2.2. 文件切割
    3. 2.3. 编码转换
    4. 2.4. find 查找早于某日期的目录
    5. 2.5. 定位行号修改
    6. 2.6. 同步文件(rsync)
    7. 2.7. 修复 /bin/bash^M: bad interpreter
  3. 3. 网络与文件传输
    1. 3.1. expect + sftp 下载
    2. 3.2. expect + sftp 上传
    3. 3.3. sftp 管理脚本(加密存储连接信息)
    4. 3.4. 脚本加密(shc)
    5. 3.5. lsof
    6. 3.6. 端口使用分析(netstat)
    7. 3.7. iftop / iptraf
    8. 3.8. telnet 批量连通性测试
    9. 3.9. nc 批量连通性测试
  4. 4. 系统与进程
    1. 4.1. 运行超过一天的进程
    2. 4.2. crontab 监控重启
    3. 4.3. screen
    4. 4.4. 异常处理
      1. 4.4.1. jps – process information unavailable
      2. 4.4.2. fork: retry: Resource temporarily unavailable
  5. 5. HDFS 与大数据
    1. 5.1. 清理非月末分区
    2. 5.2. 配置化清理 HDFS 脚本
      1. 5.2.1. TP 版
      2. 5.2.2. YMD 版
    3. 5.3. HDFS 目录检查
    4. 5.4. HDFS 下载 txt 表文件到本地(getmerge)
    5. 5.5. awk 生成 hdfs 命令
  6. 6. zsh
    1. 6.1. 安装
    2. 6.2. 插件
    3. 6.3. 主题 powerlevel10k

基础语法

读取文件为参数

1
2
ans_lines=`sed -n 1p ${verf_file}`
ans_md5=`sed -n 2p ${verf_file}`

if-else

1
2
3
4
5
6
7
8
9
10
11
12
13
# 数值比较
if [ ${ans_lines} -eq ${lines} ]
then
echo "lines is ok"
else
echo "lines is not ok"
fi

# 判断目录是否存在(HDFS)
hdfs dfs -test -d ${HDFS_path}/wap
if [ $? == 0 ]; then
hdfs dfs -rmr ${HDFS_path}/wap
fi

for 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for i in {1..10}; do echo $i; done

# 边界为变量时用 seq
END=10
for i in $(seq 1 $END); do echo $i; done

# 带步长
INTERVAL=2
for i in $(seq 1 $INTERVAL $END); do echo $i; done

for i in {2..5}; do
tablesuffix=$i
echo $tablesuffix
sleep 1
done

变量与日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 从 8 位日期字符串截取年月日
daytime=20220315
year=${daytime:0:4}
month=${daytime:4:2}
day=${daytime:6:2}

# 本月第一天、上月第一天、上月最后一天
nowdate=`date +%Y%m01` # 本月第一天
startdate=`date -d"$nowdate last month" +%Y%m%d` # 上个月第一天
enddate=`date -d"$nowdate last day" +%Y%m%d` # 上个月最后一天

# 本月最后一天
nowdate=${year}${month}01
nextmonth=`date -d"$nowdate +1 month" +%Y%m%d`
enddate=`date -d"$nextmonth last day" +%Y%m%d`

Bash 路径通配符

  • ?:匹配任意单个字符
  • *:匹配任意个任意字符
  • []:中括号通配
    • [abc]:匹配 a 或 b 或 c
    • [^abc] / [!abc]:匹配非 a/b/c 的任意单个字符
    • [a-z]:匹配 a..z,但和 Locale 排序规则有关。Locale C 环境下 [a-d] 表示 abcd;字典排序规则下 [a-d] 表示 aBbCcDd
    • 字符类:[:alpha:]、[:alnum:]、[:ascii:]、[:blank:]、[:cntrl:]、[:digit:]、[:graph:]、[:lower:]、[:print:]、[:punct:]、[:space:]、[:upper:]、[:word:]、[:xdigit:]
  • {abc,def}:枚举,支持连续字符、支持嵌套
1
2
3
4
5
6
7
8
echo {j{p,pe}g,png}
echo {0{2..9},{1..2}{0..9},3{0..1}}

# 组合示例:每月6日至次月5日
statis_date=2024{06{0[^1-5],1*,2*,3*},070[1-5]}
tp=2024{06{0[^1-5],1*,2*,3*},070[1-5]}

hdfs dfs -rm -r /hive/warehouse/ods.db/ndmc_t_ai_task/tp=2024{01..12}{02..31}

Bash 快捷键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
CTRL+A              # 移动到行首,同 <Home>
CTRL+E # 移动到行末,同 <End>
CTRL+B # 向后移动,同 <Left>
CTRL+F # 向前移动,同 <Right>

CTRL+D # 删除光标前的字符,同 <Delete>,或者没有内容时,退出会话
CTRL+G # 退出当前编辑(比如正在 CTRL+R 搜索历史时)
CTRL+H # 删除光标左边的字符,同 <Backspace>
CTRL+K # 删除光标位置到行末的内容
CTRL+L # 清屏并重新显示
CTRL+N # 移动到命令历史的下一行,同 <Down>
CTRL+O # 类似回车,但是会显示下一行历史
CTRL+P # 移动到命令历史的上一行,同 <Up>
CTRL+R # 历史命令反向搜索,使用 CTRL+G 退出搜索
CTRL+S # 历史命令正向搜索,使用 CTRL+G 退出搜索
CTRL+T # 交换前后两个字符
CTRL+U # 删除字符到行首
CTRL+V # 输入字符字面量,先按 CTRL+V 再按任意键
CTRL+W # 删除光标左边的一个单词
CTRL+X # 列出可能的补全
CTRL+Y # 粘贴前面 CTRL+u/k/w 删除过的内容
CTRL+Z # 暂停前台进程返回 bash,需要时可用 fg 将其切换回前台
CTRL+_ # 撤销(undo),有的终端将 CTRL+_ 映射为 CTRL+/ 或 CTRL+7

ALT+b # 向后(左边)移动一个单词
ALT+f # 向前(右边)移动一个单词

ALT+d # 删除光标后(右边)一个单词
ALT+t # 交换字符
ALT+BACKSPACE # 删除光标前面一个单词,类似 CTRL+W,但不影响剪贴板

CTRL+X CTRL+X # 连续按两次 CTRL+X,光标在当前位置和行首来回跳转
CTRL+X CTRL+E # 用你指定的编辑器,编辑当前命令

vi 快捷键

跳转 备注
b 上一单词 w 下一单词 e 词尾
B 上一单词 W 下一单词 小写的可以标点、空格分隔,大写的必须空格分隔
( 上一句首 ) 下一句首 句号后面的第一个字符为句首
0 或 | 行首 $ 行末 ^ 行首非零字符
- 上一行首 + 下一行首
{ 段首 } 段末 o的操作算段
H 屏幕顶行 L 屏幕底行
? 向前搜索 / 向后搜索
N 查找上一处 n 查找下一处
编辑
~ 大小写转换
o 分段(后) O 分段(前)
p 粘贴(后) P 粘贴(前)
i 插入模式 I 插入到行首
d 删除 D 删除到行末 dd 删除行
x 删除 X 删除前面字符,退格
s 删除并插入 S 删除行并插入
c C 修改至行末 cc 删除行并编辑
r 替换 R 替换模式
< 反缩进 > 缩进 <<, >>
y 复制 Y 复制行
u 撤销
J 与下一行合并
1
2
ZZ 保存退出
ZQ 不保存退出

遍历目录下的文件

1
2
3
4
5
6
fileList=`ls *$DT_time*.zip`
fileArr=($fileList)
for fileName in ${fileArr[@]}
do
unzip $unzip_name
done

文件处理

tar

打包、排除指定文件、删除源文件:

1
tar -zcf wap.tar.gz wap --exclude *.zip --remove-files

文件切割

100w 每个文件,3 位数字序号,前缀 cloudid_part:

1
split -l 1000000 -d -a 3 cloudid533379830 cloudid_part

编码转换

1
2
iconv -f 'gbk' -t 'utf-8' 199801.txt > 199801_utf8.txt
iconv -f 'utf-8' -t 'gbk' 199801.txt > 199801_gbk.txt

find 查找早于某日期的目录

1
2
3
4
5
6
# + 表示将所有匹配的路径作为参数传递给一次命令调用,而不是每次调用一次命令
# 修改时间参数为 newermt

find . -maxdepth 1 -type d ! -newerct "2025-01-01" | head
find . -maxdepth 1 -type d ! -newerct "2025-01-01" -exec ls -ld {} +
find . -maxdepth 1 -type d ! -newerct "2025-01-01" -exec rm -r {} +

定位行号修改

1
2
3
grep -n 60000 conf/interpreter.json
# 返回行号818
sed -i '818s/60000/"60000"/' conf/interpreter.json

同步文件(rsync)

集群服务器增减同步,注意目的地址写父目录:

1
rsync -av --delete /data/soft/spark/jars LGJF-ZYC6-SJZT-SVR04:/data/soft/spark/

修复 /bin/bash^M: bad interpreter

Windows 换行符问题,批量去掉 \r:

1
find . -type f -name "*.sh" -exec sed -i 's/\r$//' {} \;

网络与文件传输

expect + sftp 下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
sftp_get_wap()
{
if [ -d ${sftpLocal_wap} ]; then
rm -rf ${sftpLocal_wap}
fi
mkdir -p ${sftpLocal_wap}
expect <<- EOF
set timeout 120
spawn sftp $sftp_user@$sftp_IP
expect {
"(yes/no)?" {send "yes\r"; exp_continue}
"*assword:" {send "$sftp_password\n"; exp_continue}
"*Permission*" {exit -1}
"sftp>" {send "pwd\n"}
}
expect "sftp>"
send "cd $sftpRemote_wap\n"
expect "sftp>"
send "lcd $sftpLocal_wap\n"
expect "sftp>"
set timeout -1
send "mget *$DT_time*log\n"
expect "sftp>"
set timeout -1
send "mget *$DT_time*verf.txt\n"
expect "sftp>"
send "bye\n"
EOF
}

expect + sftp 上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
sftp_IP=10.xx
port=3030
sftp_user=biuser
sftp_password=xx
sftpRemote=/hcycdnsrc/biapp/
sftpLocal=/data/tmp
putfiles=ndmc_ispace_disk_attr_brwspace.csv

expect <<- EOF
set timeout 5
spawn sftp -P $port $sftp_user@$sftp_IP
expect {
"(yes/no*" {send "yes\r"; exp_continue}
"*assword:" {send "$sftp_password\n"}
}
expect "sftp>"
send "cd $sftpRemote\n"
expect "sftp>"
send "lcd $sftpLocal\n"
expect "sftp>"
set timeout -1
send "mput $putfiles\n"
expect "sftp>"
send "ls -l \n"
expect "sftp>"
send "bye\n"
EOF

sftp 管理脚本(加密存储连接信息)

免主机确认:echo "StrictHostKeyChecking no" > ~/.ssh/config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/bin/bash
# transfer.sh

encrypt() {
local str=$1
# Use PBKDF2 with 10000 iterations for better security
echo "$str" | openssl enc -aes-256-cbc -a -pbkdf2 -iter 100 \
-S "1234567890ABCDEF" \
-iv "0123456789ABCDEF0123456789ABCDEF" \
-pass pass:"${ENCRYPTION_KEY:-default_key}"
}

decrypt() {
local str=$1
# Use PBKDF2 with 10000 iterations for better security
echo "$str" | openssl enc -aes-256-cbc -a -d -pbkdf2 -iter 100 \
-S "1234567890ABCDEF" \
-iv "0123456789ABCDEF0123456789ABCDEF" \
-pass pass:"${ENCRYPTION_KEY:-default_key}"
}

CONFIG_FILE="config.dat"
ENCRYPTION_KEY="your_encryption_key_here" # Change this to your secure key
SEPARATOR="|" # Separator for config file entries

# Function to parse user@host format
parse_user_host() {
local input=$1
local username=$(echo "$input" | cut -d'@' -f1)
local hostname=$(echo "$input" | cut -d'@' -f2)
echo "$username|$hostname"
}

# Function to add new SFTP configuration
add_config() {
echo "Enter connection string (format: user@host):"
read -r connection_string

if [[ ! "$connection_string" =~ ^[^@]+@[^@]+$ ]]; then
echo "Invalid format. Please use user@host format"
exit 1
fi

# Parse username and hostname
parsed=$(parse_user_host "$connection_string")
username=$(echo "$parsed" | cut -d'|' -f1)
host=$(echo "$parsed" | cut -d'|' -f2)

# Set default nickname as username if not provided
echo "Enter nickname (press Enter to use '$username' as default):"
read -r nickname
nickname=${nickname:-$username}

# Set default port as 22 if not provided
echo "Enter port (press Enter to use default port 22):"
read -r port
port=${port:-22}

echo "Enter password:"
read -rs password
echo

# Encrypt sensitive data
encrypted_user=$(encrypt "$username")
encrypted_pass=$(encrypt "$password")
# Add to config file (format: nickname|host|port|encrypted_user|encrypted_pass)
echo "$nickname$SEPARATOR$host$SEPARATOR$port$SEPARATOR$encrypted_user$SEPARATOR$encrypted_pass" >> "$CONFIG_FILE"
echo "Configuration added successfully!"
}

# Alternative add_config function that accepts direct parameters
add_config_direct() {
if [ "$#" -ne 4 ]; then
echo "Usage: $0 add-direct <port> <host> <user> <password>"
exit 1
fi
local port=$1
local host=$2
local username=$3
local password=$4
local nickname=${username}
# If nickname already exists, append a random number
if [ -f "$CONFIG_FILE" ]; then
if grep -q "^$nickname$SEPARATOR" "$CONFIG_FILE"; then
nickname="${nickname}_$(date +%s)"
echo "Nickname already exists. Using '$nickname' as nickname."
fi
fi
# Encrypt sensitive data
encrypted_user=$(encrypt "$username")
encrypted_pass=$(encrypt "$password")
# Add to config file
echo "$nickname$SEPARATOR$host$SEPARATOR$port$SEPARATOR$encrypted_user$SEPARATOR$encrypted_pass" >> "$CONFIG_FILE"
echo "Configuration added successfully!"
}

# Function to get configuration by nickname
get_config() {
local nickname=$1
if [ ! -f "$CONFIG_FILE" ]; then
echo "Config file not found!"
exit 1
fi
# Get the line for this nickname
local config_line=$(grep "^$nickname$SEPARATOR" "$CONFIG_FILE")
if [ -z "$config_line" ]; then
echo "Nickname not found!"
exit 1
fi
# Parse the line using separator
host=$(echo "$config_line" | cut -d"$SEPARATOR" -f2)
port=$(echo "$config_line" | cut -d"$SEPARATOR" -f3)
encrypted_user=$(echo "$config_line" | cut -d"$SEPARATOR" -f4)
encrypted_pass=$(echo "$config_line" | cut -d"$SEPARATOR" -f5)
# Decrypt sensitive data
user=$(decrypt "$encrypted_user")
password=$(decrypt "$encrypted_pass")
}

# Function to list all configured nicknames
list_configs() {
if [ ! -f "$CONFIG_FILE" ]; then
echo "No configurations found."
return
fi
echo "Available SFTP configurations:"
while IFS="$SEPARATOR" read -r nickname host port encrypted_user _; do
if [ ! -z "$nickname" ]; then
user=$(decrypt "$encrypted_user")
echo " $nickname -> $user@$host:$port"
fi
done < "$CONFIG_FILE"
}

# Function to list remote directory
sftp_ls() {
local nickname=$1
local remote_path=${2:-.}
get_config "$nickname"
sshpass -p "$password" sftp -P "$port" "$user@$host" << EOL
cd "$remote_path"
ls
bye
EOL
}

# Function to download files/directories
sftp_get() {
local nickname=$1
local remote_path=$2
local local_path=${3:-.}
get_config "$nickname"
if [[ "$remote_path" == */ ]]; then
# It's a directory
sshpass -p "$password" sftp -P "$port" "$user@$host" << EOL
get -r "$remote_path" "$local_path"
bye
EOL
else
# It's a file
sshpass -p "$password" sftp -P "$port" "$user@$host" << EOL
get "$remote_path" "$local_path"
bye
EOL
fi
}

# Function to upload files/directories
sftp_put() {
local nickname=$1
local local_path=$2
local remote_path=${3:-.}
get_config "$nickname"
if [ -d "$local_path" ]; then
# It's a directory
sshpass -p "$password" sftp -P "$port" "$user@$host" << EOL
put -r "$local_path" "$remote_path"
bye
EOL
else
# It's a file
sshpass -p "$password" sftp -P "$port" "$user@$host" << EOL
put "$local_path" "$remote_path"
bye
EOL
fi
}

# Main menu
case "$1" in
"add")
add_config
;;
"add-direct")
shift # Remove first argument
add_config_direct "$@"
;;
"list")
list_configs
;;
"ls")
if [ -z "$2" ]; then
echo "Usage: $0 ls <nickname> [remote_path]"
exit 1
fi
sftp_ls "$2" "$3"
;;
"get")
if [ -z "$3" ]; then
echo "Usage: $0 get <nickname> <remote_path> [local_path]"
exit 1
fi
sftp_get "$2" "$3" "$4"
;;
"put")
if [ -z "$3" ]; then
echo "Usage: $0 put <nickname> <local_path> [remote_path]"
exit 1
fi
sftp_put "$2" "$3" "$4"
;;
*)
echo "Usage: $0 {add|list|ls|get|put} [arguments]"
echo "Commands:"
echo " add Add new SFTP configuration"
echo " add-direct Add with direct parameters <port> <host> <user> <password>"
echo " list List all configured SFTP connections"
echo " ls <nickname> [path] List remote directory contents"
echo " get <nickname> <remote_path> [local_path] Download file/directory"
echo " put <nickname> <local_path> [remote_path] Upload file/directory"
exit 1
;;
esac

# ./sftp_tool.sh add-direct '22' '192.168.x' 'xx' 'xx!xx'

脚本加密(shc)

1
2
3
4
5
6
7
8
apt-get install -y shc
shc -v -f sftp_tool.sh
# 输出C语言源代码和可执行文件

# 自行编译方式:
cc test.sh.x.c -o test.sh.x
strip sftp_tool.sh.x
chmod +x test.sh.x

lsof

端口查进程:

1
lsof -i:<port>

进程查端口:

1
lsof -P -p 123674 | grep IPv | grep LISTEN

进程的线程信息:

1
ps -mp 11139 -o THREAD

本机所有进程监听端口:

1
lsof -nP -iTCP -sTCP:LISTEN

端口使用分析(netstat)

1
2
3
netstat -an        # 查看所有
netstat -plntu # 查询当前处于监听状态的端口
netstat -plnt -4 # 查询当前处于监听状态的 tcp4 端口

python 脚本整理监听端口与连接信息(python2,commands 模块):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 这个方法得不到shell命令的输出
import commands,os
# os.system('netstat -ntlp -4')
retCode,output = commands.getstatusoutput('netstat -ntlp')

tmp = set()
lines = output.split('\n')
for line in lines:
if str(line).startswith('tcp'):
items = str(line).split()
if not items[3].startswith('127.0.0.1') :
if items[3].startswith('0.0.0.0') or items[3].startswith(':::') or items[3].split(':')[0] != items[4].split(':')[0]:
print('%s\t\t%s\t\t%s' %(items[3], items[4], items[6]))
tmp.add(int(items[3].split(':')[-1]))

listeningPort=list(tmp)
listeningPort.sort()

for p in listeningPort:
print(p)

#########
inUsePortInfo = {}
retCode,output = commands.getstatusoutput('netstat -ntp -4 |grep ESTABLISHED')
lines = output.split('\n')
for line in lines:
if str(line).startswith('tcp'):
items = str(line).split()
if items[3].split(':')[0] != items[4].split(':')[0]:
port = items[3].split(':')[1] + ' ' + items[6]
tmp = inUsePortInfo.get(port, list())
tmp.append(items[4])
tmp.sort()
inUsePortInfo[port] = tmp

for i in sorted(inUsePortInfo):
print('%s \t %s' %(i, inUsePortInfo[i]))

说明:

  • 期望输出:port + foreign address list
  • 过滤条件:本机 127.0.0.1、local 和 remote 都为本机的连接

iftop / iptraf

1
2
3
4
5
nohup sudo iftop -n -N -t -s 10 -L 1000 -o destination > /data/tmp/iftop20231211 &
nohup sudo iftop -n -N -t -s 86400 -L 5000 -o destination > /data/tmp/iftop20231211 &
cat /data/tmp/iftop20231211 | grep '<=' | awk '{print $1}' | grep -v :

sudo iptraf -i eth0 -L /var/log/traffic_log -B

telnet 批量连通性测试

1
for i in {14..23}; do  a=`(sleep 1;echo 'quit') |telnet 10.27.48.${i} 22 |grep OpenS |wc -l`; if [ ${a} == 0 ]; then     echo "10.27.48.${i} failed"; else     echo "10.27.48.${i} ok"; fi; done

多行版:

1
2
3
4
5
6
7
8
for i in {14..23};
do
a=`(sleep 1;echo 'quit') |telnet 10.xx.xx.${i} 22 |grep OpenS |wc -l`;
if [ ${a} == 0 ];
then echo "10.xx.xx.${i} failed";
else echo "10.xx.xx.${i} ok";
fi;
done

telnet 方式批量检测(数组版):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/bash

# Define IP addresses array
ip_list=(
"192.168.1.10"
"10.0.0.15"
"172.16.0.20"
)

# Port to check
PORT=1019

# Function to check port connectivity
check_port() {
local ip=$1
result=$(timeout 3 telnet "$ip" $PORT 2>&1)
if echo "$result" | grep -q "Connected to"; then
return 0
else
return 1
fi
}

echo "Checking port $PORT connectivity..."
echo "Unreachable IPs:"

# Check each IP
for ip in "${ip_list[@]}"; do
if ! check_port "$ip"; then
echo "$ip"
fi
done

nc 批量连通性测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/bash
# chmod +x check_ports.sh
# yum install nc

declare -a targets # 存储所有输入的 IP:PORT
success_count=0
fail_count=0
declare -a fail_list

# 提示用户输入多行信息
echo "请输入 IP 地址和端口,每行一个,格式为 IP:PORT。"
echo "输入完成后,按 Ctrl+D 结束输入。"

while IFS= read -r line; do
# 检查输入格式是否正确
if [[ "$line" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+$ ]]; then
targets+=("$line")
else
echo "无效的输入格式,跳过:$line"
fi
done

# 检测到 EOF 后的提示
echo "输入结束,正在处理数据..."
for target in "${targets[@]}"; do
IP=$(echo "$target" | cut -d: -f1)
PORT=$(echo "$target" | cut -d: -f2)
# 打印一个点号,不换行
echo -n "."
# 使用 nc 检测连通性
if nc -z -w 5 "$IP" "$PORT"; then
((success_count++))
else
((fail_count++))
fail_list+=("$target")
fi
done

echo "====汇总结果===="
echo "成功连接的总数: $success_count"
echo "失败连接的总数: $fail_count"

# 输出失败清单
if [ ${#fail_list[@]} -gt 0 ]; then
echo "失败的清单:"
for fail in "${fail_list[@]}"; do
echo "$fail"
done
else
echo "没有失败的连接。"
fi

系统与进程

运行超过一天的进程

1
ps -eo user,pid,ppid,etime,cmd | grep -E ' [0-9]+-[0-9]+:.*' | grep -E 'SparkSubmit|miniconda' | tee /dev/tty | awk '{print $2}'

crontab 监控重启

写脚本时注意环境变量问题,建议程序使用全路径执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/bin/bash

# */5 * * * * /bin/sh /data/dolphinscheduler-1.3.6/ds-watcher.sh

restart_worker()
{
#pid=`pgrep -f org.apache.dolphinscheduler.server.worker.WorkerServer`
/usr/bin/pkill -f org.apache.dolphinscheduler.server.worker.WorkerServer
rm -f /data/dolphinscheduler-1.3.6/pid/dolphinscheduler-worker-server.pid
sleep 3s
su dolphinscheduler -c "sh /data/dolphinscheduler-1.3.6/bin/dolphinscheduler-daemon.sh start worker-server"
}

# worker
ret=`/data/java/bin/java -cp /data/dolphinscheduler-1.3.6/ds-watcher.jar ds.ZkCheckNode master:2181,slave1:2181,slave2:2181 /dolphinscheduler/nodes/worker/default/`

if [ $ret = 'false' ] ;then
restart_worker
fi

screen

1
2
3
4
5
6
7
8
9
10
11
12
13
14
screen            创建会话
screen -ls
screen -S xxx 指定名称创建会话
screen -r xxx 指定名称恢复会话
screen -R xxx 指定名称恢复或创建会话

Ctrl+a 再按:
- d:保存会话,后台运行该虚拟终端
- k:关闭对话,等同输入:exit
- c:新建一个虚拟终端
- ?:显示所有绑定键盘

exit 虚拟终端内退出
screen -R [pid/Name] -X quit 主终端内结束虚拟终端

异常处理

jps – process information unavailable

问题:无法显示进程名称。

解决:删除 perfdata 临时目录。

1
rm -rf /tmp/hsperfdata_*

fork: retry: Resource temporarily unavailable

修改 /etc/security/limits.d/90-nproc.conf(修改后重启进程生效):

1
2
3
*          soft    nproc    65535
hadoop soft nproc 257529
root soft nproc unlimited

在控制台执行(修改这个不需要重启):

1
2
3
4
ulimit -u 655350

# 检查是否生效:在控制台切到该用户下
ulimit -u

其他信息查看命令:

1
2
3
ps h -Led -o user | sort | uniq -c | sort -n
ps -o nlwp,pid,lwp,args -u hadoop | sort -n
# 第一列 NLWP 为线程数

HDFS 与大数据

清理非月末分区

1
2
3
4
5
6
7
8
9
10
11
keepDay=7
tbl="ods.t_used_space_df"

part=`date -d "${date} -${keepDay} day" +%Y%m%d`
echo "${part}"
if [[ "$(date -d "${part} +1 day" +%d)" = "01" ]]; then
echo "日期是月末,跳过清理"
else
echo "日期不是月末,清理"
spark-sql --master local[1] -e "ALTER TABLE ${tbl} DROP IF EXISTS PARTITION (tp=${part});"
fi

YMD 分区版:

1
2
3
4
5
6
7
8
9
10
11
12
keepDay=15
tbl="ods.ablum_saas_pro_photo_file_label"

date="${year}${month}${day}"
part=`date -d "${date} -${keepDay} day" +%Y%m%d`
echo "${part}"
if [[ "$(date -d "${part} +1 day" +%d)" = "01" ]]; then
echo "日期是月末,跳过清理"
else
echo "日期不是月末,清理"
spark-sql --master local[1] -e "ALTER TABLE ${tbl} DROP IF EXISTS PARTITION (year='${part:0:4}',month='${part:4:2}',day='${part:6:2}');"
fi

配置化清理 HDFS 脚本

YEAR_AGO 保留年底,MONTHS_AGO 保留月底,MONTHS_AGO 以内每天保留。

TP 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/bin/bash

BASE_PATH="/hive/warehouse/dw.db/dws_pds_total_asset_df"
TODAY=$(date +%Y%m%d)

YEAR_AGO=$(date -d "2 year ago" +%Y%m%d)
MONTHS_AGO=$(date -d "1 months ago" +%Y%m%d)

TODAY_TS=$(date -d "$TODAY" +%s)
YEAR_AGO_TS=$(date -d "$YEAR_AGO" +%s)
MONTHS_AGO_TS=$(date -d "$MONTHS_AGO" +%s)

echo "今日日期: $TODAY"
echo "n年前日期: $YEAR_AGO"
echo "n个月前日期: $MONTHS_AGO"
echo "------------------------------------------------"

# 获取所有tp=开头的目录
DIRECTORIES=$(hdfs dfs -ls "$BASE_PATH" | grep -E "tp=[0-9]{8}$" | awk '{print $8}')

if [ -z "$DIRECTORIES" ]; then
echo "没有找到需要清理的目录"
exit 0
fi

# 收集待删除目录,统一批量删除
DELETE_PATHS=""

for DIR in $DIRECTORIES; do
# 提取目录名中的日期部分
DIR_NAME=$(basename "$DIR")
DIR_DATE=${DIR_NAME#tp=}

# 将目录日期转换为时间戳
DIR_DATE_TS=$(date -d "$DIR_DATE" +%s)

echo "处理目录: $DIR_NAME"

# 判断是否在最近n个月内
if [ $DIR_DATE_TS -ge $MONTHS_AGO_TS ]; then
continue
fi

# 判断是否在3个月到n年之间
if [ $DIR_DATE_TS -ge $YEAR_AGO_TS ]; then
# 检查是否为月末
YEAR=${DIR_DATE:0:4}
MONTH=${DIR_DATE:4:2}
LAST_DAY=$(date -d "$YEAR-$MONTH-01 +1 month -1 day" +%d)

if [ "${DIR_DATE:6:2}" = "$LAST_DAY" ]; then
echo " -> 保留: 月末目录 ($DIR_DATE 是 ${YEAR}-${MONTH}的最后一天)"
else
echo " -> 删除: 非月末目录 ($DIR_DATE 不是月末)"
DELETE_PATHS="$DELETE_PATHS $DIR"
fi
continue
fi

# n年以上的目录
YEAR=${DIR_DATE:0:4}

# 检查是否为年末(12月31日)
if [ "${DIR_DATE:4:4}" = "1231" ]; then
echo " -> 保留: 年末目录 ($DIR_DATE 是 ${YEAR}年12月31日)"
else
echo " -> 删除: 非年末目录 ($DIR_DATE 不是年末)"
DELETE_PATHS="$DELETE_PATHS $DIR"
fi
done

# 一次性批量删除
if [ -n "$DELETE_PATHS" ]; then
echo ""
echo "开始批量删除..."
hdfs dfs -rm -r $DELETE_PATHS
else
echo "没有需要删除的目录"
fi

echo "------------------------------------------------"
echo "清理完成!"

YMD 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/bash

BASE_PATH="/hive/warehouse/ods.db/dws_pds_total_asset_df"
TODAY=$(date +%Y%m%d)

YEAR_AGO=$(date -d "2 year ago" +%Y%m%d)
MONTHS_AGO=$(date -d "1 months ago" +%Y%m%d)

TODAY_TS=$(date -d "$TODAY" +%s)
YEAR_AGO_TS=$(date -d "$YEAR_AGO" +%s)
MONTHS_AGO_TS=$(date -d "$MONTHS_AGO" +%s)

echo "今日日期: $TODAY"
echo "2年前日期: $YEAR_AGO"
echo "1个月前日期: $MONTHS_AGO"
echo "------------------------------------------------"

DELETE_PATHS=""

# 获取所有年份目录
YEAR_DIRS=$(hdfs dfs -ls "$BASE_PATH" | grep -E "year=[0-9]{4}$" | awk '{print $8}')

if [ -z "$YEAR_DIRS" ]; then
echo "没有找到 year= 开头的分区目录"
exit 0
fi

for YEAR_DIR in $YEAR_DIRS; do
YEAR_VALUE=${YEAR_DIR##*=}

# 获取该年份下的月份目录
MONTH_DIRS=$(hdfs dfs -ls "$YEAR_DIR" | grep -E "month=[0-9]{2}$" | awk '{print $8}')
[ -z "$MONTH_DIRS" ] && continue

for MONTH_DIR in $MONTH_DIRS; do
MONTH_VALUE=${MONTH_DIR##*=}

# 获取该月份下的天目录
DAY_DIRS=$(hdfs dfs -ls "$MONTH_DIR" | grep -E "day=[0-9]{2}$" | awk '{print $8}')
[ -z "$DAY_DIRS" ] && continue

for DAY_DIR in $DAY_DIRS; do
DAY_VALUE=${DAY_DIR##*=}
DIR_DATE="${YEAR_VALUE}${MONTH_VALUE}${DAY_VALUE}"
DIR_DATE_TS=$(date -d "$DIR_DATE" +%s)

echo "处理目录: year=$YEAR_VALUE/month=$MONTH_VALUE/day=$DAY_VALUE"

# 最近n个月内 → 保留
if [ $DIR_DATE_TS -ge $MONTHS_AGO_TS ]; then
continue
fi

# 3个月到2年之间 → 只保留月末
if [ $DIR_DATE_TS -ge $YEAR_AGO_TS ]; then
LAST_DAY=$(date -d "$YEAR_VALUE-$MONTH_VALUE-01 +1 month -1 day" +%d)

if [ "$DAY_VALUE" = "$LAST_DAY" ]; then
echo " -> 保留: 月末目录 ($DIR_DATE 是 ${YEAR_VALUE}-${MONTH_VALUE}的最后一天)"
else
echo " -> 删除: 非月末目录 ($DIR_DATE 不是月末)"
DELETE_PATHS="$DELETE_PATHS $DAY_DIR"
fi
continue
fi

# 2年以上 → 只保留年末(12月31日)
if [ "${MONTH_VALUE}${DAY_VALUE}" = "1231" ]; then
echo " -> 保留: 年末目录 ($DIR_DATE 是 ${YEAR_VALUE}年12月31日)"
else
echo " -> 删除: 非年末目录 ($DIR_DATE 不是年末)"
DELETE_PATHS="$DELETE_PATHS $DAY_DIR"
fi
done
done
done

echo ""
echo "================================================"
if [ -n "$DELETE_PATHS" ]; then
COUNT=$(echo $DELETE_PATHS | wc -w)
echo "开始批量删除 $COUNT 个目录..."
hdfs dfs -rm -r $DELETE_PATHS
else
echo "没有需要删除的目录"
fi

echo "------------------------------------------------"
echo "清理完成!"

HDFS 目录检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/bin/bash

HDFS_PATH=/hive/warehouse/bdoc.db/lg_dim_db01_dim_public_section_no_df/dtime=20250121
MIN_FILE_COUNT=0

if ! hdfs dfs -test -d "$HDFS_PATH"; then
echo "Error: Path does not exist: $HDFS_PATH"
exit 1
fi

if hdfs dfs -ls "$HDFS_PATH" | grep -q ".hive-staging_"; then
echo "Error: Found .hive-staging_ files/directories in path"
exit 1
fi

FILE_COUNT=$(hdfs dfs -ls "$HDFS_PATH" | grep -v Found | grep -v "^d" | grep -v "/\." | wc -l)

if [ "$FILE_COUNT" -le "$MIN_FILE_COUNT" ]; then
echo "Error: File count ($FILE_COUNT) is not greater than minimum required ($MIN_FILE_COUNT)"
exit 1
fi

echo "Success: All conditions met!"
echo "- Path exists: $HDFS_PATH"
echo "- No .hive-staging_ files found"
echo "- File count: $FILE_COUNT (minimum required: $MIN_FILE_COUNT)"
exit 0

HDFS 下载 txt 表文件到本地(getmerge)

自动清理一天前文件和空文件夹:

1
2
0 1 * * * find /data/ts/ -type f -mtime +1 -delete
5 1 * * * find /data/ts/ -type d -empty -delete

脚本名 getmerge:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/bin/sh
while true; do
echo -n "请输入需要操作的库名.表名(如 tmp.test_table): "
read input
db_name=$(echo $input | awk -F. '{print $1}')
table_name=$(echo $input | awk -F. '{print $2}')
if [ -z "$db_name" ] || [ -z "$table_name" ]; then
echo "输入格式不对,请重新输入"
else
break
fi
done

if [ "$db_name" != "tmp" ]; then
echo -n "库名不是tmp,是否继续?(y/n): "
read confirm_db
if [ "$confirm_db" != "y" ] && [ "$confirm_db" != "Y" ]; then
echo "操作取消"
exit 1
fi
fi

hdfs_dir="/hive/warehouse/${db_name}.db/${table_name}"
echo "空间使用情况:"
hdfs dfs -dus -h "$hdfs_dir"
echo "文件示例:"
file_example=$(hdfs dfs -ls "$hdfs_dir" | head)
echo "$file_example"

if echo "$file_example" | grep -Ei 'orc|snappy|parquet' > /dev/null; then
echo ">>>检测到可能非文本格式<<<"
fi

date_str=$(date +%Y%m%d%H%M%S)
default_output="/data/ts/${db_name}_${table_name}_${date_str}"
echo -n "是否将所有文件合并导出为 ${default_output}?(y/n自定义输出文件名): "
read do_merge

if [ "$do_merge" = "y" ] || [ "$do_merge" = "Y" ]; then
output_name="$default_output"
else
while true; do
echo -n "请输入自定义输出文件名(输入 q 退出): "
read custom_output
if [ "$custom_output" = "q" ] || [ "$custom_output" = "Q" ]; then
echo "操作已取消。"
exit 0
fi
echo -n "你确认输出文件名为 $custom_output 吗?(y/n): "
read confirm_output
if [ "$confirm_output" = "y" ] || [ "$confirm_output" = "Y" ]; then
output_name="$custom_output"
break
else
echo "请重新输入输出文件名"
fi
done
fi

hdfs dfs -getmerge "$hdfs_dir" "$output_name"
if [ $? -eq 0 ]; then
echo "$(date +%Y%m%d%H%M%S) $db_name.$table_name $output_name" >> "/data/getmerge_his"
head -3 $output_name
echo "操作完成"
else
echo "getmerge 操作失败"
fi

awk 生成 hdfs 命令

1
2
3
4
5
6
7
8
9
10
11
12
13
# case 1
cat mblock | grep '/hive/warehouse/dw.db/dwm_huadan_user_act_summary_d/year=2025/month=01/' | awk '{print "/Current20250214" $2, $2}' | xargs -P 5 -n 2 -I {} echo "hdfs dfs -mv {}" |bash

# case 2
snapshot_prefix="/hive/warehouse/.snapshot/hive_warehouse_20250213"
target_prefix="/hive/warehouse"

cat mblock | grep 'dwd_huadan_share_person_d' |grep 'year=2025' |awk -v snapshot="$snapshot_prefix" -v target="$target_prefix" '{
file_path = $2
source_path = snapshot substr(file_path, length(target) + 1)
target_path = file_path
print "hdfs dfs -cp " source_path " " target_path
}'

zsh

安装

1
2
3
4
5
6
7
8
9
10
# 安装zsh
apt install zsh

# 安装ohmyzsh
sh -c "$(curl -fsSL https://install.ohmyz.sh)"

# 修改默认shell
echo $SHELL
chsh -s /bin/zsh
chsh -s /bin/bash

插件

  1. 把插件下载到本地的 ~/.oh-my-zsh/custom/plugins 目录:
1
2
3
4
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:-${ZSH:-~/.oh-my-zsh}/custom}/plugins/zsh-completions
git clone https://github.com/zsh-users/zsh-history-substring-search ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-history-substring-search
  1. 在 .zshrc 中,把插件加入插件列表:
1
2
3
4
5
6
7
8
plugins=(
# other plugins...
git
zsh-autosuggestions # 插件之间使用空格隔开
zsh-syntax-highlighting
zsh-completions
zsh-history-substring-search
)
  1. 开启新的 Shell 或执行 source ~/.zshrc,就可以开始体验插件。

更多插件:Plugins Overview · ohmyzsh/ohmyzsh Wiki

主题 powerlevel10k

1
2
3
git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git "${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k"

# Open ~/.zshrc, find the line that sets ZSH_THEME, and change its value to "powerlevel10k/powerlevel10k"