Compare commits

...

83 Commits

Author SHA1 Message Date
987ac44575 add company 2FA in utool.py and remove old rokae files 2024-08-16 10:11:24 +08:00
e8159fc8cb [modify] change scripts path with mid-fix "/git/", and do a exclude for syncthing due to too big tar ball 2024-06-02 08:01:54 +08:00
cc1463b166 [modify] textbox color, nagative value 2024-05-31 18:33:36 +08:00
14c72fe080 [modify] change vers location again 2024-05-31 08:52:18 +08:00
2922806e9c [modify] change domain to intranet addr in vers check 2024-05-30 20:25:32 +08:00
06e5111309 5. 重新在write2textbox中添加exitcode参数,并补齐相关逻辑和修改brake中的调用方式
6. 修复参数检查无效的情况
7. 屏蔽电流相关的功能
2024-05-30 17:12:43 +08:00
b04b9e9205 v0.1.1(2024/05/30)
1. 增加版本检测功能
2. 修改了无效数据下的动作
3. textbox只在开始和结束时改变状态,而不是每次写入都更改
4. 调整了brake的结构
2024-05-30 16:24:54 +08:00
cad7792fa1 [modify] skip when data is invalid 2024-05-30 15:08:42 +08:00
fd553b3442 [modify] minor modification 2024-05-30 14:37:39 +08:00
9b849897e2 [modify] minor modification, change write2textbox and using shorter func name 2024-05-30 08:28:59 +08:00
05f461f8c1 v0.1.0(2024/05/29)
1. 修改为customtkinter图形化界面
2. 支持工业机器人制动数据处理(理论上支持,测试数据有问题,待验证)
3. 删除configs.xlsx配置表格,直接在界面配置,新增layout.xlsx文件,存储customtkinter布局
4. 电流尚未支持
2024-05-29 19:15:44 +08:00
1cee89cd0a v0.0.7(2024/05/27)
1. 该版本制动数据处理变动较大,重写了find_row_start & copy_data_to_result,删除了delete_excel_files
2. 主要是修改了数据处理的方式,直接使用pandas进行数据处理,跳过了openpyxl来回变换,节省了大量的IO以及时间
2024-05-27 19:15:29 +08:00
203138947b [modify] AXIS is int, and add wb_data param in find_row_start() and modify accordingly; also the info of damage of result files 2024-05-23 20:52:06 +08:00
3d2e0e33af [modify] change icon.ico to true ico, and modify time format 2024-05-23 20:12:07 +08:00
e11dc60438 [modify]
v0.0.6(2024/05/23)
1. 为了调整多功能框架,aio.py文件将会作为入口程序存在,不实现具体功能,功能的实现将由具体的功能脚本实现,aio.py只负责条件调用
2. 新增了自动化处理电流数据(电机/过载)的功能
2024-05-23 17:35:34 +08:00
7123fa1147 [modify] rename workdir 2024-05-23 17:33:26 +08:00
f1fd1aaff5 [modify] add attention sheet 2024-05-23 16:19:17 +08:00
2dec392e50 [modify] minor modifications, see readme.txt in v0.0.5 the later half part 2024-05-23 16:12:35 +08:00
6cb768a05e [modify] change var place in initialization func 2024-05-23 15:11:22 +08:00
a0f8f49b27 [modify] delete some comments 2024-05-23 14:11:53 +08:00
09d63b6630 [add] icon.ico and readme.txt 2024-05-23 14:00:32 +08:00
44ef429d5a [modify]
v0.0.5(2024/05/23)
1. 完善了函数注释
2. 调整了阈值和步长
3. 删除了just_open函数,以及对应的win32com库(Thank GOD!终于可以不用这个库了)
4. 重写了获取开始点位的代码,直接使用speed来判断,而不用角度,所以find_row_start_dp以及copy_data_to_excel_file函数也被一并删除
2024-05-23 13:59:06 +08:00
de6d1d47c8 [midify]
v0.0.4(2024/05/22)
1. 重新标定了get_threshold_step函数,让处理更加准确
2. 新定义了now_doing_msg函数,实时输出处理信息
3. 修改了find_row_start和find_row_start_dp函数,增加的部分相同,处理数据的时候,先判断是否是空值,或者是0,此时可以加快步进
4. 修改了just_open函数,不在做重试
2024-05-23 11:25:45 +08:00
b335f61c72 [modify] v0.0.3(2024/05/21)
1. just_open函数打开失败的信息中,添加文件名
2. 删除global变量,函数全部通过传参实现
3. configuration.xlsx配置文件增加AXIS常量,表示那个轴,取值为 j1/j2/j3/j4/j5/j6/j7
4. [bugfix] 增加get_threshold_step函数,用来获取在计算row_start时合适的阈值和步长,主要是解决了二轴最差工况下,最大速度是个尖端的问题:
    a. load100_speed100_reachxxx 二轴 threshold = 50 step = 20
    b. 其他 threshold = 50 step = 100
    如上是一个比较保守的设定,因为设定的step比较小,找到点之后要往后延200最好
5. 在find_row_start_dp函数中新增一个参数data_file,方便后续调试
2024-05-23 11:23:32 +08:00
c61686065e [modify] v0.0.2(2024/05/20)
1. 功能模块化,为后面其他功能奠定一个基本的框架
2. 使用了多线程提高效率
3. 优化了准备工作中的细节
4. 运行初始化时自动删除 raw_data_dir 中的 .xlsx 文件
5. 优化了输出格式
6. 使用 pyinstaller 库进行代码冻结并调试成功
2024-05-23 11:07:35 +08:00
9a001021b1 [init] v0.0.1 drafts 2024-05-23 11:03:12 +08:00
6080fe48c1 [modify] 1. systemd-networkd service 2. add a mod blacklist 3. bluetooth 4. remove unused files when do a backup 2024-05-19 11:33:36 +08:00
36a18e870f [modify] make a exception for v2raya 2024-05-19 11:31:23 +08:00
40e14b5cc7 [add] create rokae scripts dir, and add script for processing brake data 2024-05-19 11:30:57 +08:00
a96f533f8f [modify] make ifconfig output to /opt/wd/99-Temp/ifconfig.txt on the start of the system 2024-05-19 11:28:01 +08:00
b36c0b6939 [modify] delete sysctl related parts and add conf backup for netdata 2024-04-27 21:46:49 +08:00
7e68bbb891 [modify] delete jekyll related parts 2024-04-27 21:45:42 +08:00
21f481076c [modify] exclude grep/ps/utool process when filtering 2024-01-14 11:10:05 +08:00
fc60587252 [modify] add cert sync for windows nginx 2024-01-14 11:08:53 +08:00
d1afa8e0ad [add] qiyeweixin bot for suqian 2024-01-14 11:08:24 +08:00
09f73bb770 [modify] add new functions of find docker pid and print top 20 info of mem & cpu 2023-11-30 08:32:14 +08:00
ed631e97c2 [modify] change restart mem limit from 1000 to 500 2023-11-30 08:30:48 +08:00
f5c9f65fe7 [modify] test 2023-11-27 14:48:15 +08:00
999b8d977d [modify] rewrite via parseargs module 2023-11-26 11:16:48 +08:00
c6cb2cf281 [add] check frp service, restart it or push an alert to iphone 2023-11-26 11:16:06 +08:00
d6784fa70c [modify] change syncthing location, also the nginx of windows client 2023-11-18 11:10:47 +08:00
52dccb1787 [remove] todo app not used anymore 2023-11-17 20:18:14 +08:00
dbc0c638fd [modify] complete rewrite of utool 2023-11-12 22:15:31 +08:00
1931445c13 [add] rewrite utool with enclosure function 2023-11-09 19:44:45 +08:00
816b07306f [modify] move utool.py to old/ 2023-11-09 19:43:47 +08:00
88a5898f8c [modify] remove restore.sh script 2023-11-01 20:02:49 +08:00
6523b0eac0 [modify] change multi-thread compression algo from pixz to pigz, and add a comment of how to uncompress 2023-11-01 16:33:50 +08:00
cf91fbd224 [modify] rsync will sync everything to backup dir, but tar will exlude some big folder instead, and fix wrong scp 2023-11-01 11:01:24 +08:00
c8be4e5d2c [modify] change the device key and domain 2023-10-27 21:27:58 +08:00
578e1ba496 [modify] remove rand logo for dashboard, change homepage hourly rand logo generation, and add rustle.cc cert sync to windows monthly 2023-10-27 21:26:14 +08:00
2a78030816 [modify] remove restore.sh, and add tailscale sysctl file 2023-10-27 20:54:57 +08:00
459e3bc59b [modify] remove rand logo script, not using 2023-10-27 20:54:29 +08:00
7b07df0ec0 [modify] add nextcloud sync on 01:00 everyday 2023-10-19 20:39:40 +08:00
d4f132eebd [modify] renew frpc-visitor origin path, and move cert sync to first day of month 2023-10-19 20:38:59 +08:00
b5d13cdf5b [modify] remove rsync of syncthing and add frpc-visitor backup 2023-10-19 20:17:41 +08:00
9d07b32e46 [modify] remove initialization of openwrt 2023-10-19 20:16:55 +08:00
d2fd9a6a25 [remove] old scripts, not using anymore 2023-10-19 20:14:39 +08:00
5e821cf08c [modify] add backup for windows frpc xtcp 2023-10-16 01:54:10 +08:00
5eff1f0ac7 remove test 2023-10-16 01:49:11 +08:00
37e4634213 test 2023-10-15 12:58:29 +08:00
af558f33f9 [modify] not sync music dir of koel, and fix name error of syncthing 2023-10-14 13:55:41 +08:00
d7fccd74b9 [modify] remove old navigation related 2023-10-04 21:28:28 +08:00
773e2552ac [modify] add a copy of interfaces 2023-09-15 20:00:52 +08:00
59cb3622f4 [add] rsync syncthing files to nextcloud 2023-09-08 16:52:33 +08:00
90aea333fd [modify] add reboot function and initialization on startup 2023-09-08 16:52:07 +08:00
20813a992f [modify] remove calibre & jekyll things to old/, and change the name and content of shutdown.sh 2023-09-08 16:50:12 +08:00
9b97d42f31 [modify] fix logo number error 2023-09-01 17:20:23 +08:00
42ec2ca2b7 [modify] use dos2unix tool to change the file 2023-09-01 16:16:09 +08:00
1168fa1d36 [modify] add comments of usage 2023-09-01 16:15:39 +08:00
62a7fa644a [modify] change gitignore content to make it effect 2023-09-01 16:15:17 +08:00
4958bed672 [delete] remove alert/bark/option.json file 2023-09-01 16:14:07 +08:00
22da887f77 [add] create gitignore file 2023-09-01 16:12:28 +08:00
4c15418d6f [modify] add to pic space reduction software 2023-08-31 22:31:45 +08:00
9e7424efe2 [modify] make inotify to blog work on background 2023-08-31 22:30:55 +08:00
eca21bb3d0 [modify] change passwd of xgdfmf on the third party client 2023-08-31 22:29:38 +08:00
ddbb77c59e [add] bark server file, notification on iPhone 2023-08-31 22:28:53 +08:00
19f72612cd [modify] make mavvlan take effect by putting this action 20s after NIC setting 2023-08-28 11:42:13 +08:00
ce95c20bc4 [add/modify] add macvlan.sh for create a macvlan network, and add this action to init.sh 2023-08-28 10:11:37 +08:00
ac2ee2f48c [modify] add a condition to determine if the file is empty 2023-08-25 22:04:40 +08:00
e0cdc133a2 [modify] add scp certs action to arm1/arm2/amd 2023-08-25 21:51:15 +08:00
8d11aa9ec8 [modify] change alert method to mail 2023-08-25 21:50:46 +08:00
5efa59be75 [add] send mail via python, using as an alert method 2023-08-25 21:46:07 +08:00
b32ea0978d [modify] move useless scripts to old dir 2023-08-25 21:45:25 +08:00
37 changed files with 742 additions and 206 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
alert/bark/option.json

28
alert/bark/ciphertxt.sh Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Documentation: https://bark.day.app/#/encryption
set -e
# bark key
deviceKey='R5BU8VnMn3ufSFjMnwSmd6'
# push payload
# json='{"body": "test", "sound": "birdsong"}'
json=`cat /opt/scripts/alert/bark/option.json`
# 必须32位
key='sqCT9wE25eS2kMYu6BCGN4f9ymx2Fsmj'
# IV可以是随机生成的但如果是随机的就需要放在 iv 参数里传递。
iv='QA475QXtg4YaGQzc'
# OpenSSL 要求输入的 Key 和 IV 需使用十六进制编码。
key=$(printf $key | xxd -ps -c 200)
iv=$(printf $iv | xxd -ps -c 200)
ciphertext=$(echo -n $json | openssl enc -aes-256-cbc -K $key -iv $iv | base64)
# 删除密文中的空格
ciphertext=`echo $ciphertext | tr -d ' '`
# 密文可能有特殊字符,所以记得 URL 编码一下。
curl --data-urlencode "ciphertext=$ciphertext" --data-urlencode "iv=QA475QXtg4YaGQzc" https://bark.rustle.cc/$deviceKey

70
alert/bark/msgsend.py Normal file
View File

@ -0,0 +1,70 @@
#!/usr/bin/python3
import sys
import json
import os
import argparse
def usage():
pformat = "%-7s%-7s%-10s%-10s%-10s%-10s%-10s"
sformat = "%-23s%-18s%-16s%-14s%-14s%-12s%-12s"
print(pformat % ('must', 'must', 'optional', 'optional', 'optional', 'optional', 'optional'))
print(pformat % ('title', 'body', 'sound', 'icon', 'group', 'badge', 'isArchive'))
print(pformat % ('-', '-', '2.0-alarm', '-', 'default', '-', '1'))
print(pformat % ('-', '-', '1.4-bell', '-', 'docker', '-', '1'))
print(pformat % ('-', '-', '1.6-bloom', '-', 'frp', '-', '1'))
print("\nThe 'sound' parameter also accepts the following as its value:")
print(sformat % ("1.8-healthnotification", "2.6-typewriters", "2.9-newsflash", "1.5-mailsent", "1.5-tiptoes", "4.5-update", "2.9-spell"))
print(sformat % ("2.2-multiwayinvitation", "4.5-anticipate", "1.2-telegraph", "0.9-calypso", "1.5-newmail", "1.7-glass", "2.2-choo"))
print(sformat % ("1.4-paymentsuccess", "1.5-electronic", "0.7-birdsong", "1.9-descent", "1.3-ladder", "4.5-chime", "1.5-horn"))
print(sformat % ("4.7-sherwoodforest", "3.0-gotosleep", "4.2-suspense", "1.5-fanfare", "7.0-minuet", "0.6-shake", "1.9-noir"))
print()
def getParams(
title='test',
body='hello...',
sound='',
icon='',
group='default',
badge='1',
isarchive=1,
):
params_dict = {'title': title, 'body': body, 'sound': sound, 'icon': icon, 'group': group, 'badge': '1', 'isarchive': '1'}
params_json = json.dumps(params_dict)
with open('/opt/scripts/alert/bark/option.json', 'w') as obj_option:
obj_option.write(params_json)
os.system('/usr/bin/bash /opt/scripts/alert/bark/ciphertxt.sh')
def main():
if len(sys.argv) < 5:
usage()
parser = argparse.ArgumentParser(description='Prepare arguements for bark')
parser.add_argument('--title', help='标题,必要参数', required=True)
parser.add_argument('--body', help='主题内容,必要参数', required=True)
parser.add_argument('--sound', help='提示音,非必要参数,有默认值', default='alarm')
parser.add_argument('--icon', help='图标,非必要参数,有默认值', default='0')
parser.add_argument('--group', help='群组,非必要参数,有默认值', default='default')
parser.add_argument('--badge', help='角标,非必要参数,有默认值', default='1')
parser.add_argument('--isarchive', help='是否自动归档,非必要参数,有默认值', default='1')
# if len(sys.argv) == 1:
# print('Need at least 2 parameters, and most can have 7 parameters, exiting...')
# usage()
args = parser.parse_args()
title = args.title
body = args.body
sound = args.sound
icon = 'https://www.rustle.cc/assets/img/logos/' + str(args.icon) + '.jpg'
group = args.group
badge = args.badge
isarchive = args.isarchive
getParams(title, body, sound, icon, group, badge, isarchive)
if __name__ == "__main__":
main()

View File

@ -1,12 +1,17 @@
#!/bin/bash #!/bin/bash
> /tmp/docker_alarm.log
docker ps -a --format "table {{.Names}}\t{{.Status}}" > /opt/logs/docker_status.log docker ps -a --format "table {{.Names}}\t{{.Status}}" > /opt/logs/docker_status.log
while read line; do while read line; do
echo $line | grep -q 'Exited' echo $line | grep -v 'v2raya' | grep -q 'Exited'
if [[ $? -eq 0 ]]; then if [[ $? -eq 0 ]]; then
name=`echo $line | awk '{print $1}'` name=`echo $line | awk '{print $1}'`
alarm="Docker Alarm - $name:\nContainer $name has been off line, please check ASAP." echo "Docker Alarm - $name: Container $name has been off line, please check ASAP." >> /tmp/docker_alarm.log
bash /opt/scripts/alert/sendmsg.sh "$alarm"
fi fi
done < /opt/logs/docker_status.log done < /opt/logs/docker_status.log
if [[ -s /tmp/docker_alarm.log ]]; then
alarm=`cat /tmp/docker_alarm.log`
python3 /opt/git/scripts/alert/sendmail.py "Docker Alarms" "$alarm"
fi

63
alert/sendmail.py Normal file
View File

@ -0,0 +1,63 @@
#!/usr/bin/python3
# 脚本接收两个及以上的参数
# 第一个参数:邮件主题
# 第二个参数:邮件文本内容
# 其他参数:邮件附件
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import smtplib
import sys
# Mail basic information
mail_host = "smtp.163.com"
from_mail = 'xgdfmf@163.com'
from_mail_password = 'PSIKFDYLMGBPSEPJ'
receiver_to = ['mffan0922@163.com']
receiver_cc = []
to_mail = receiver_to + receiver_cc
# MIMEMultipart: mixed/alternative/related
# 1mixed: default option, especially situation with mail attachments must use this one
# 2alternative: with both plain text and hyper text in mail content, using this one
# 3relatedsending content of html format, probably using picture as the background of mail
# content, then html text will be stored in alternative segment, whereas the background picture
# will be stored in multipart/related segment
# Mail content
msg = MIMEMultipart()
msg['From'] = from_mail
msg['To'] = ";".join(to_mail)
msg['Subject'] = sys.argv[1]
txt = sys.argv[2]
body = MIMEText(txt, 'plain', 'utf-8')
msg.attach(body)
# Mail attachment
if len(sys.argv) > 3:
for attachment in sys.argv[3:]:
filename = attachment.split('/')[-1]
attach_file = open(attachment, 'r').read()
attach = MIMEText(str(attach_file), 'base64', 'utf-8')
attach["Content-Type"] = 'application/octet-stream'
attach.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attach)
try:
server = smtplib.SMTP(mail_host)
server.docmd('helo', from_mail)
server.starttls()
server.login(from_mail, from_mail_password)
server.sendmail(from_mail, to_mail, msg.as_string())
server.quit()
print('sendemail successful!')
except Exception as err:
print('Sending email failed, the reason is as below:')
print(err)

View File

@ -4,33 +4,33 @@ import time
import os import os
def send_alert_msg(alert_msg): # def send_alert_msg(alert_msg):
""" # """
send warning messages to phone via Enterprise WeChat Bot API # send warning messages to phone via Enterprise WeChat Bot API
:param alert_msg: messages needed to be sent # :param alert_msg: messages needed to be sent
:return: None # :return: None
""" # """
#
# get the datetime, which is using at a failed situation # # get the datetime, which is using at a failed situation
alert_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # alert_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
# # Enterprise Wechat Bot API and the format of body to send # # # Enterprise Wechat Bot API and the format of body to send
hook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ddea3f5f-fbfc-4c21-994a-71e9fc50e4ef' # hook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ddea3f5f-fbfc-4c21-994a-71e9fc50e4ef'
body = { # body = {
"msgtype": "text", # "msgtype": "text",
"text": { # "text": {
"content": alert_msg # "content": alert_msg
} # }
} # }
#
# get the result of API call # # get the result of API call
res = requests.post(hook_url, data=json.dumps(body, ensure_ascii=False).encode('utf-8')) # res = requests.post(hook_url, data=json.dumps(body, ensure_ascii=False).encode('utf-8'))
#
# when failed, log it in /opt/logs/alert.log file # # when failed, log it in /opt/logs/alert.log file
if res.status_code != 200: # if res.status_code != 200:
with open('/opt/logs/alert.log', 'a', encoding='utf-8') as alert_log: # with open('/opt/logs/alert.log', 'a', encoding='utf-8') as alert_log:
alert_log.write(alert_datetime + ' >>>> ') # alert_log.write(alert_datetime + ' >>>> ')
alert_log.write('Failed sending message: ') # alert_log.write('Failed sending message: ')
alert_log.write(alert_msg + '\n') # alert_log.write(alert_msg + '\n')
def main(): def main():
@ -87,7 +87,13 @@ def main():
alert_msg += '\n' alert_msg += '\n'
alert_msg += 'So, hurry up!! Go get things done!!' alert_msg += 'So, hurry up!! Go get things done!!'
send_alert_msg(alert_msg) os.environ['subject'] = 'TODO TIPS'
os.environ['txt'] = alert_msg
# os.system('/usr/bin/echo subject = $subject')
# os.system('/usr/bin/echo txt = $txt')
# exit(9)
os.system('/usr/bin/python3 /opt/scripts/alert/sendmail.py "$subject" "$txt"')
# send_alert_msg(alert_msg)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
# 设置图片数量和输出文件名 # 设置图片数量和输出文件名
IMAGE_NUM_ALL=`ls /opt/apps/localcr/A_dashboard/local/icons | wc -l` IMAGE_NUM_ALL=`ls /opt/apps/localcr/A_dashboard/local/icons/*.jpg | wc -l`
IMAGE_NUM_NEEDED=`cat /opt/apps/localcr/A_dashboard/local/config/services.yaml | grep -E '[0-9]{1,3}.jpg' | wc -l` IMAGE_NUM_NEEDED=`cat /opt/apps/localcr/A_dashboard/local/config/services.yaml | grep -E '[0-9]{1,3}.jpg' | wc -l`
if [[ $IMAGE_NUM_NEEDED -gt $IMAGE_NUM_ALL ]]; then if [[ $IMAGE_NUM_NEEDED -gt $IMAGE_NUM_ALL ]]; then
alarm='Dashboard:\nThere is NOT enough logos to use, please check ASAP.' alarm='Dashboard:\nThere is NOT enough logos to use, please check ASAP.'

25
old/macvlan.sh Normal file
View File

@ -0,0 +1,25 @@
#!/bin/bash
for i in `seq 3`; do
gateway=`ip route | head -n 1 | grep -Eow '([0-9]{1,3}.){3}[0-9]{1,3}'`
[[ $gateway == '' ]] && { sleep 3; continue; }
done
[[ $gateway == '' ]] && exit 9
num1=`echo $gateway | awk -F '.' '{print $1}'`
num2=`echo $gateway | awk -F '.' '{print $2}'`
num3=`echo $gateway | awk -F '.' '{print $3}'`
for num4 in `seq 200 254`; do
IP=$num1'.'$num2'.'$num3'.'$num4
ping -c 2 $IP
[[ $? -ne 0 ]] && break
done
ip link add main2wrt link enp1s0 type macvlan mode bridge
ip addr add $IP dev main2wrt
ip link set main2wrt up
ip route add 192.168.10.123 dev main2wrt
ip link set main2wrt promisc on

View File

@ -2,6 +2,9 @@
# 设置图片数量和输出文件名 # 设置图片数量和输出文件名
IMAGE_NUM_ALL=`ls /opt/websites/nav/assets/images/logos | wc -l` IMAGE_NUM_ALL=`ls /opt/websites/nav/assets/images/logos | wc -l`
# there are 221 logos in total, and index are from 0, so the max index is 220
# whhereas there has an avatar.jpg file in this dir, so need to subtract one
let IMAGE_NUM_ALL=IMAGE_NUM_ALL-1
IMAGE_NUM_NEEDED=`cat /opt/websites/nav/index.html | grep -E '[0-9]{1,3}.jpg' | wc -l` IMAGE_NUM_NEEDED=`cat /opt/websites/nav/index.html | grep -E '[0-9]{1,3}.jpg' | wc -l`
if [[ $IMAGE_NUM_NEEDED -gt $IMAGE_NUM_ALL ]]; then if [[ $IMAGE_NUM_NEEDED -gt $IMAGE_NUM_ALL ]]; then
alarm='Navigation:\nThere is NOT enough logos to use, please check ASAP.' alarm='Navigation:\nThere is NOT enough logos to use, please check ASAP.'

9
old/nc_rsync.sh Normal file
View File

@ -0,0 +1,9 @@
#!/bin/bash
src_dir='/opt/apps/syncthing/data/common'
dst_dir='/opt/apps/localcr/K_nextcloud/local/nextcloud/data/nextcloud/files/'
rsync --delete-after -avz $src_dir $dst_dir
docker exec -u www-data nextcloud php /var/www/html/occ files:scan --all

View File

@ -136,7 +136,8 @@ apt install lrzsz unzip vim gcc g++ make automake curl wget gnupg2 aria2 jq apt-
python3-pip python3-dev golang net-tools ethtool tcpflow lshw rsync parallel rclone pigz pbzip2 \ python3-pip python3-dev golang net-tools ethtool tcpflow lshw rsync parallel rclone pigz pbzip2 \
pixz neofetch mlocate ncdu dstat fzf tldr nscd inotify-hookable inotify-tools vsftpd mtr bridge-utils \ pixz neofetch mlocate ncdu dstat fzf tldr nscd inotify-hookable inotify-tools vsftpd mtr bridge-utils \
socat dos2unix samba libldap2-dev libsasl2-dev smartmontools parted libpcre3 libpcre3-dev openssl \ socat dos2unix samba libldap2-dev libsasl2-dev smartmontools parted libpcre3 libpcre3-dev openssl \
libssl-dev zlib1g-dev libgeoip-dev libncurses-dev libpython3-dev fwupd virtualenv wpasupplicant -y libssl-dev zlib1g-dev libgeoip-dev libncurses-dev libpython3-dev fwupd virtualenv wpasupplicant \
jpegoptim optipng -y
curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs
# fwupdmgr get-updates && fwupdmgr update # fwupdmgr get-updates && fwupdmgr update

178
old/utool.py Executable file
View File

@ -0,0 +1,178 @@
#!/usr/bin/python3
# coding: utf-8
import os
import sys
import time
c_title = '\033[1;4;31;42m' # title color
c_br = '\033[1;31m' # bold red
c_bg = '\033[1;32m' # bold green
c_by = '\033[1;33m' # bold yellow
c_bb = '\033[1;34m' # bold blue
c_bp = '\033[1;35m' # bold purple
c_bc = '\033[1;36m' # bold cyan
c_bir= '\033[1;3;31m' # * bold italic red
c_bib = '\033[1;3;34m' # * bold italic cyan
c_bic = '\033[1;3;36m' # bold italic cyan
c_e = '\033[0m' # reset
if len(sys.argv) == 2:
opt_1 = sys.argv[1]
opt_rest = None
elif len(sys.argv) > 2:
opt_1 = sys.argv[1]
opt_rest = sys.argv[2:]
else:
opt_1 = None
opt_rest = None
opt_index = ['-do_not_use_this', '-a', '-b', '-c', '-d', '-e', '-f', '-g', '-h', '-i', '-j', '-k', '-l', '-m',
'-n', '-o', '-p', '-q', '-r', '-s', '-t', '-u', '-v', '-w', '-x', '-y', '-z']
if opt_1 not in opt_index:
os.system('/usr/bin/bash /opt/scripts/utool/usage.sh')
exit(100)
if opt_1 == '-a':
if opt_rest != None:
print(f"This option({opt_1}) will print all ports of now using for local, and accept NO parameter.")
exit(opt_index.index(opt_1))
os.system('/usr/bin/bash /opt/scripts/utool/ipports.sh port')
elif opt_1 == '-b':
if opt_rest != None:
print(f"This option({opt_1}) will generate a two-factor auth-key for github login, and accept NO parameter.")
exit(opt_index.index(opt_1))
os.system("/usr/bin/oathtool -b --totp 'G3NHHFO2L2LZ5W2R'")
elif opt_1 == '-c':
if opt_rest != None:
print(f"This option({opt_1}) will print all intranet IP using in docker, and accept NO parameter.")
exit(opt_index.index(opt_1))
os.system('/usr/bin/bash /opt/scripts/utool/ipports.sh ip')
elif opt_1 == '-d':
if opt_rest != None:
print(f"This option({opt_1}) will return the current IP of local machine, and accept NO parameter.")
exit(opt_index.index(opt_1))
os.system("/usr/bin/python3 /opt/scripts/roll_api/get_self_ip.py")
elif opt_1 == '-e':
if opt_rest == None:
print(f"This option({opt_1}) will return the IP info, and accept at least one IP parameter.")
exit(opt_index.index(opt_1))
for opt_2 in opt_rest:
os.environ['opt_2'] = opt_2
os.system('/usr/bin/python3 /opt/scripts/roll_api/get_ip.py $opt_2')
elif opt_1 == '-f':
if len(sys.argv) < 3:
print(f"{c_br}需要至少一个字符串作为输入,退出...{c_e}\n")
exit(opt_index.index(opt_1))
param=''
for item in sys.argv[2:]:
param += item
os.environ['param'] = param
print(f"{c_by}Warning: 输入字符串中间的任何空白符将会被删除,要保留的话,需手动将字符串用单引号括起来{c_e}")
print(f"本次计算MD5值的字符串为 - {param}\n本次计算得到的MD5的值为 - ", end='')
# print(f"本次计算得到的MD5的值为 - ", end='')
os.system('echo -n $param | md5sum | cut -d " " -f 1')
elif opt_1 == '-g':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-h':
os.system('/usr/bin/bash /opt/scripts/utool/usage.sh')
exit(opt_index.index(opt_1))
elif opt_1 == '-i':
if opt_rest == None:
print(f"This option({opt_1}) will return the domain registration info, and accept at least one domain parameter.")
exit(opt_index.index(opt_1))
for opt_2 in opt_rest:
os.environ['opt_2'] = opt_2
os.system('/usr/bin/python3 /opt/scripts/roll_api/domain_reg_check.py $opt_2')
elif opt_1 == '-j':
if len(sys.argv) == 2:
print(f"{c_br}-j选项将十进制或者十六进制数字作为入参转换成标准时间格式只接收第一个参数其他参数将被丢弃有歧义时使用'0x'或者'0X'来区分十进制和十六进制,退出...{c_e}\n")
exit(opt_index.index(opt_1))
os.environ['param'] = sys.argv[2]
os.system('/usr/bin/bash /opt/scripts/utool/number2d.sh $param')
elif opt_1 == '-k':
if len(sys.argv) < 3:
print(f"{c_br}-k选项将输入的时间转换成十进制和十六进制需要一个字符串格式的时间作为输入退出...{c_e}\n")
exit(opt_index.index(opt_1))
param=''
for item in sys.argv[2:]:
param += item + ' '
os.environ['param'] = param
os.system('/usr/bin/bash /opt/scripts/utool/date2n.sh $param')
elif opt_1 == '-l':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-m':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-n':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-o':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-p':
if opt_rest == None:
opt_rest = ['',]
opt_2 = opt_rest[0]
os.environ['opt_2'] = opt_2
os.system('/usr/bin/bash /opt/scripts/utool/genpw.sh $opt_2')
elif opt_1 == '-q':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-r':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-s':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-t':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-u':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-v':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-w':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-x':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-y':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-z':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
else:
print("This line SHOULD NOT be executed, please check carefully.")
exit(255)

View File

@ -8,7 +8,7 @@ cp -rf /var/spool/cron/crontabs/ /opt/configs/
cp -rf /usr/local/nginx/conf/nginx.conf /opt/configs/nginx/nginx.conf cp -rf /usr/local/nginx/conf/nginx.conf /opt/configs/nginx/nginx.conf
cp -rf /usr/local/nginx/conf/domain_confs/ /opt/configs/nginx/ cp -rf /usr/local/nginx/conf/domain_confs/ /opt/configs/nginx/
cp -rf /etc/docker/daemon.json /opt/configs/conf/ cp -rf /etc/docker/daemon.json /opt/configs/conf/
cp -rf /etc/sysctl.conf /opt/configs/conf/ cp -rf /etc/netdata/ /opt/configs/
cp -rf /etc/pip.conf /opt/configs/conf/ cp -rf /etc/pip.conf /opt/configs/conf/
cp -rf /etc/apt/sources.list /opt/configs/conf/ cp -rf /etc/apt/sources.list /opt/configs/conf/
cp -rf /etc/ssh/sshd_config /opt/configs/conf/ cp -rf /etc/ssh/sshd_config /opt/configs/conf/
@ -16,12 +16,17 @@ cp -rf /root/.bashrc /opt/configs/conf/bashrc
cp -rf /root/.vim_runtime/my_configs.vim /opt/configs/conf/ cp -rf /root/.vim_runtime/my_configs.vim /opt/configs/conf/
cp -rf /root/.ssh/config /opt/configs/conf/ cp -rf /root/.ssh/config /opt/configs/conf/
cp -rf /etc/samba/smb.conf /opt/configs/conf/ cp -rf /etc/samba/smb.conf /opt/configs/conf/
cp -rf /etc/network/interfaces /opt/configs/conf/
cp -rf /root/.acme.sh/*ecc /opt/configs/acme/ cp -rf /root/.acme.sh/*ecc /opt/configs/acme/
cp -rf /opt/scripts/update/restore.sh /opt/apps/syncthing/data/common/F-Backup/Linux/ cp -rf /root/.acme.sh/rustle.cc_ecc/rustle.cc.{key,cer} /opt/apps/syncthing/data/common/A_Program/nginx-1.24.0/certs/
cp -rf /opt/apps/syncthing/data/common/A_Program/FRP/* /opt/apps/frp/frpc-xtcp-visitor/
cp -rf /etc/systemd/network /opt/configs/conf/
cp -rf /etc/modprobe.d/pcspkr-blacklist.conf /opt/configs/conf/
cp -rf /lib/firmware/intel/ ibt-0040-1050* /opt/configs/conf/intel/
cd /opt && t=`date +%Y%m%dT%H%M%S` cd /opt && t=`date +%Y%m%dT%H%M%S`
rsync --delete-after -avz apps configs logs scripts websites wd/72-Backups/VPS/ > /opt/logs/rsync/rsync_${t}.log # rsync --delete-after -avz --exclude=apps/localcr/B_koel/local/music apps configs logs scripts websites wd/72-Backups/VPS/ > /opt/logs/rsync/rsync_${t}.log
rsync --delete-after -avz /opt/apps/syncthing/data/* wd/72-Backups/Syncthing/ > /opt/logs/rsync/rsync_${t}.log rsync --delete-after -avz --exclude=apps/syncthing apps configs logs git websites wd/72-Backups/VPS/ > /opt/logs/rsync/rsync_${t}.log
cd /opt/logs/rsync/ cd /opt/logs/rsync/
let count=`ls | wc -l` let count=`ls | wc -l`
if [[ $count -gt 10 ]]; then if [[ $count -gt 10 ]]; then
@ -37,8 +42,18 @@ fi
# on 1st of every month, do a compress # on 1st of every month, do a compress
if [[ `date +%d` == '01' ]]; then if [[ `date +%d` == '01' ]]; then
t=`date +%Y%m%d%H%M%S` t=`date +%Y%m%d%H%M%S` && cd /opt/wd/72-Backups/
tar -I pixz -cf /opt/wd/72-Backups/vps-${t}.tar.gz /opt/wd/72-Backups/VPS > /dev/null 2>&1
tar -I pigz -cf vps-${t}.tar.gz \
--exclude=VPS/apps/localcr/I_cloudreve/local/cloudreve/uploads \
--exclude=VPS/apps/syncthing/data \
VPS/ > /dev/null 2>&1
# tar -I unpigz -xf vps-20231101162641.tar.gz
scp -r /opt/configs/certs/ arm1:/opt/ > /dev/null 2>&1 &
scp -r /opt/configs/certs/ arm2:/opt/ > /dev/null 2>&1 &
scp -r /opt/configs/certs/ amd:/opt/ > /dev/null 2>&1 &
wait
fi fi
set +x set +x
echo End Time: `date` echo End Time: `date`

41
update/chatbot_suqian.sh Normal file
View File

@ -0,0 +1,41 @@
#!/bin/bash
function sendMsg() {
# 个人测试
# curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ddea3f5f-fbfc-4c21-994a-71e9fc50e4ef' \
# -H 'Content-Type: application/json' \
# -d '
# {
# "msgtype": "markdown",
# "markdown": {
# "content": "**'"$alarmTitle"'**\n
# > <font color=\"warning\">'"$alarmInfo"'</font>"
# }
# }' > /dev/null 2>&1
# 群hook
curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=924c62e3-1bb8-4d17-84b1-e543eb27ba1e' \
-H 'Content-Type: application/json' \
-d '
{
"msgtype": "text",
"text": {
"content": "'"$alarmTitle"':\n'"$alarmInfo"'",
"mentioned_list":["@all"]
}
}' > /dev/null 2>&1
}
isFriday=$(date +%A)
time_opt=$1
alarmTitle="每日/周工作记录提醒"
if [[ $isFriday == 'Friday' ]]; then
alarmInfo='周五了[庆祝][庆祝][庆祝],请各位及时填写周报,感谢大家本周的辛苦付出,别忘了还有今日工作内容安排记录,以及问题进展跟新~~~'
else
alarmInfo='大家记得写每日工作内容安排上午10点之前写完工作期间可以补充内容下班前17点左右完善一下争取日事日毕~[拳头][拳头][拳头]\n有事没事找找客户经理发个信息啥的也可~~\n客户走访记录问题解决以及客户经理需求记录也要记得跟进更新闭环~~~'
fi
sendMsg $alarmTitle $alarmInfo

View File

@ -1,15 +1,19 @@
#!/bin/bash #!/bin/bash
#==============================================================================
/usr/bin/qbittorrent-nox --webui-port=10005 -d /usr/bin/qbittorrent-nox --webui-port=10005 -d
/usr/bin/bash /opt/scripts/update/calibre.sh
mv /opt/wd/99-Temp/shutdown /opt/wd/99-Temp/shutdown.old mv /opt/wd/99-Temp/shutdown /opt/wd/99-Temp/shutdown.old
mv /opt/wd/99-Temp/reboot /opt/wd/99-Temp/reboot.old
ip link set enp1s0 promisc on sleep 20
ip link set enp2s0 promisc on ifconfig > /opt/wd/99-Temp/ifconfig.txt
ip link set wlx90de80ca01ec promisc on #==============================================================================
# ip link set enp1s0 promisc on
/usr/bin/bash /opt/scripts/update/jekyll_update.sh # ip link set enp2s0 promisc on
# ip link set wlx90de80ca01ec promisc on
#==============================================================================
# sleep 20
# /usr/bin/bash /opt/git/scripts/update/macvlan.sh
#==============================================================================
# /usr/bin/mount -t ext4 -w UUID="b7c2c4b8-bfde-479b-80bb-655432a433b8" /opt/wd # /usr/bin/mount -t ext4 -w UUID="b7c2c4b8-bfde-479b-80bb-655432a433b8" /opt/wd

View File

@ -1,24 +1,22 @@
#!/bin/bash #!/bin/bash
# get latest hosts for accelerate github visiting # get latest hosts for accelerate github visiting
curl https://raw.hellogithub.com/hosts >> /opt/logs/hosts # curl https://raw.hellogithub.com/hosts >> /opt/logs/hosts
# renew images.json file for background picture of homepage # renew images.json file for background picture of homepage
cd /opt/websites/homepage/ cd /opt/websites/homepage/
node assets/js/bing.js > /dev/null 2>&1 node assets/js/bing.js > /dev/null 2>&1
if [[ `date +%d` == '01' ]]; then if [[ `date +%d` == '01' ]]; then
# random logo for navigation
bash /opt/scripts/update/nav_rand_logo.sh
# random logo for dash # random logo for dash
bash /opt/scripts/update/dash_rand_logo.sh # bash /opt/git/scripts/update/dash_rand_logo.sh
cp /root/.acme/rustle.cc_ecc/fullchain.cer '/opt/apps/syncthing/data/common/A_Program/nginx-1.24.0/certs/'
cp /root/.acme/rustle.cc_ecc/rustle.cc.key '/opt/apps/syncthing/data/common/A_Program/nginx-1.24.0/certs/'
fi fi
# logo renew # logo renew
let numOfAvatar=`ls /opt/websites/nav/assets/images/logos/ | wc -l` let numOfAvatar=`ls /opt/websites/homepage/assets/img/logos | wc -l`
let randNumber=$RANDOM%$numOfAvatar let randNumber=$RANDOM%$numOfAvatar
cp /opt/websites/nav/assets/images/logos/${randNumber}.jpg /opt/websites/nav/assets/images/logos/avatar.jpg cp /opt/websites/homepage/assets/img/logos/${randNumber}.jpg /opt/websites/homepage/assets/img/logo.jpg
cp /opt/websites/nav/assets/images/logos/${randNumber}.jpg /opt/websites/homepage/assets/img/logo.jpg
cp /opt/websites/nav/assets/images/logos/${randNumber}.jpg /opt/apps/blog/img/avatar.jpg
# docker exec -u www-data nextcloud php /var/www/html/occ files:scan --all

16
update/restart_frpc.sh Normal file
View File

@ -0,0 +1,16 @@
#!/bin/bash
rss=$(ps aux | grep frpc.toml | grep -v grep | awk '{print $6}')
if [[ $rss == '' ]]; then
python3 /opt/git/scripts/alert/bark/msgsend.py --title "FRPC Warning" --body "Seems like FRPC Service has been down, need to check ASAP." --group 'frp' --icon 8
exit 9
fi
rss=$((rss/1024))
if [[ $rss -gt 500 ]]; then
systemctl restart frpc.service
fi

16
update/restart_frps.sh Normal file
View File

@ -0,0 +1,16 @@
#!/bin/bash
rss=$(ps aux | grep frps.toml | grep -v grep | awk '{print $6}')
if [[ $rss == '' ]]; then
ssh -o ConnectTimeout=60 beelink 'python3 /opt/scripts/alert/bark/msgsend.py --title "FRPS Warning" --body "Seems like FRPS Service has been down, need to check ASAP." --group "frp" --icon 8'
exit 9
fi
rss=$((rss/1024))
if [[ $rss -gt 500 ]]; then
systemctl restart frps.service
fi

View File

@ -4,6 +4,8 @@
if [[ -f "/opt/wd/99-Temp/shutdown" ]]; then if [[ -f "/opt/wd/99-Temp/shutdown" ]]; then
poweroff poweroff
elif [[ -f "/opt/wd/99-Temp/reboot" ]]; then
reboot
fi fi

View File

@ -25,6 +25,7 @@ elif [[ $number =~ ^[0-9a-fA-F]{1,9}$ ]]; then
hex=`printf "%d" '0x'$number` hex=`printf "%d" '0x'$number`
date -d@$hex +'%Y-%m-%d %H:%M:%S' date -d@$hex +'%Y-%m-%d %H:%M:%S'
else else
echo -e "${c_bb}-j选项将十进制或者十六进制数字作为入参转换成标准时间格式只接收第一个参数其他参数将被丢弃有歧义时使用'0x'或者'0X'来区分十进制和十六进制,退出...${c_e}\n"
echo -e "${c_br}请输入正确的十进制--11位以内或者十六进制数字--9位以内${c_e}" echo -e "${c_br}请输入正确的十进制--11位以内或者十六进制数字--9位以内${c_e}"
echo -e " 十进制的时间戳 - 1678523385" echo -e " 十进制的时间戳 - 1678523385"
echo -e " 十六进制时间戳 - 0x640c3bf9/0X640C3BF9/0x640C3bf9/640c3bf9" echo -e " 十六进制时间戳 - 0x640c3bf9/0X640C3BF9/0x640C3bf9/640c3bf9"

18
utool/pid_in_docker.sh Normal file
View File

@ -0,0 +1,18 @@
#!/bin/bash
psid=$1
ids=$(docker inspect -f "{{.Id}}" $(docker ps -q))
for did in $ids; do
docker top $did | awk '{print $2, $3}' | grep -wq $psid
if [[ $? -eq 0 ]]; then
echo "Docker ID : $did"
name=$(docker inspect -f '{{.Name}}' $did | tr -d "/")
echo "Docker Name: $name"
exit 0
fi
done
echo "Not a docker (sub)process..."

17
utool/ps_top_20.sh Normal file
View File

@ -0,0 +1,17 @@
#!/bin/bash
# ps -ely | sort -nrk 8 | head -n 20 | awk 'BEGIN{print "UID", "PID", "PPID", "RSS", "CMD"} {print $2, $3, $4, $8/1024"M", $NF}' | column -t
fmt="%-9s%-9s%-6s%-6s\033[1;32m%-8s\033[0m%-10s\n"
awk -v fmt=$fmt 'BEGIN{printf fmt, "PID","PPID","%CPU","%MEM","RSS","COMM"}' > /tmp/mem.top
ps -eo pid,ppid,pcpu,pmem,rss,comm | grep -Ev "grep|ps" | sort -nrk 5 | head -n 20 | awk -v fmt=$fmt '{printf fmt, $1,$2,$3,$4,int($5/1024)"M",$6}' >> /tmp/mem.top
> /tmp/deli.top
for i in `seq 21`; do
echo '|' >> /tmp/deli.top
done
fmt="%-9s%-9s\033[1;34m%-6s\033[0m%-6s%-8s%-10s\n"
awk -v fmt=$fmt 'BEGIN{printf fmt, "PID","PPID","%CPU","%MEM","RSS","COMM"}' > /tmp/cpu.top
ps -eo pid,ppid,pcpu,pmem,rss,comm | sort -nrk 3 | grep -Ev "grep|ps|utool" | head -n 20 | awk -v fmt=$fmt '{printf fmt, $1,$2,$3,$4,int($5/1024)"M",$6}' >> /tmp/cpu.top
paste /tmp/mem.top /tmp/deli.top /tmp/cpu.top | column -t
rm -rf /tmp/{mem.top,cpu.top,deli.top}

View File

@ -4,76 +4,56 @@ import os
import sys import sys
import time import time
c_title = '\033[1;4;31;42m' # title color def utool(option):
c_br = '\033[1;31m' # bold red
c_bg = '\033[1;32m' # bold green
c_by = '\033[1;33m' # bold yellow
c_bb = '\033[1;34m' # bold blue
c_bp = '\033[1;35m' # bold purple
c_bc = '\033[1;36m' # bold cyan
c_bir= '\033[1;3;31m' # * bold italic red
c_bib = '\033[1;3;34m' # * bold italic cyan
c_bic = '\033[1;3;36m' # bold italic cyan
c_e = '\033[0m' # reset
if len(sys.argv) == 2: def print_usage():
opt_1 = sys.argv[1] intro = """utool -- A self-defined command line interface, which is used to facilitate operating the system, supports the following options. In the description part, where there is a leading asterisk signifies that this option must take an argument, and for more information of this situation, simply run `utool -h` for details."""
opt_rest = None print(f"{c_intro}{intro}{c_e}")
elif len(sys.argv) > 2: print("_" * 121)
opt_1 = sys.argv[1] print(f"{c_title}|Option| Description{' ' * 40}|Option| Description{' ' * 40}|{c_e}")
opt_rest = sys.argv[2:] count = 0
else: for opt, desc in dict_func.items():
opt_1 = None description = "" if desc[0] == "Reserved" else desc[0]
opt_rest = None if count % 2 == 0:
print(f"{c_text}|{opt:^6}|{description:<52}{c_e}", end="")
opt_index = ['-do_not_use_this', '-a', '-b', '-c', '-d', '-e', '-f', '-g', '-h', '-i', '-j', '-k', '-l', '-m', else:
'-n', '-o', '-p', '-q', '-r', '-s', '-t', '-u', '-v', '-w', '-x', '-y', '-z'] print(f"{c_text}|{opt:^6}|{description:<52}|{c_e}")
count += 1
if opt_1 not in opt_index:
os.system('/usr/bin/bash /opt/scripts/utool/usage.sh')
exit(100) exit(100)
if opt_1 == '-a': # -a
if opt_rest != None: def list_local_using_port():
print(f"This option({opt_1}) will print all ports of now using for local, and accept NO parameter.") exit_on_wrong_number()
exit(opt_index.index(opt_1)) os.system('/usr/bin/bash /opt/git/scripts/utool/ipports.sh port')
os.system('/usr/bin/bash /opt/scripts/utool/ipports.sh port')
elif opt_1 == '-b':
if opt_rest != None:
print(f"This option({opt_1}) will generate a two-factor auth-key for github login, and accept NO parameter.")
exit(opt_index.index(opt_1))
# -b
def github_two_factor():
exit_on_wrong_number()
os.system("/usr/bin/oathtool -b --totp 'G3NHHFO2L2LZ5W2R'") os.system("/usr/bin/oathtool -b --totp 'G3NHHFO2L2LZ5W2R'")
elif opt_1 == '-c': # -c
if opt_rest != None: def get_external_ip():
print(f"This option({opt_1}) will print all intranet IP using in docker, and accept NO parameter.") exit_on_wrong_number()
exit(opt_index.index(opt_1)) os.system("/usr/bin/python3 /opt/git/scripts/roll_api/get_self_ip.py")
os.system('/usr/bin/bash /opt/scripts/utool/ipports.sh ip') # -d
def get_ip_location():
exit_on_wrong_number(2)
import re
checked_ip = sys.argv[2]
ipv4 = re.match(r"^((([01]?\d\d?)|(2[0-4]\d)|(25[0-5]))\.){3}(([01]?\d\d?)|(2[0-4]\d)|(25[0-5]))$", checked_ip)
if ipv4:
os.environ['checked_ip'] = checked_ip
os.system('/usr/bin/python3 /opt/git/scripts/roll_api/get_ip.py $checked_ip')
else:
print(f"{c_br}Plz enter correct IP...{c_e}")
exit(ord(option.strip('-')))
elif opt_1 == '-d': # -e
if opt_rest != None: def gen_md5():
print(f"This option({opt_1}) will return the current IP of local machine, and accept NO parameter.")
exit(opt_index.index(opt_1))
os.system("/usr/bin/python3 /opt/scripts/roll_api/get_self_ip.py")
elif opt_1 == '-e':
if opt_rest == None:
print(f"This option({opt_1}) will return the IP info, and accept at least one IP parameter.")
exit(opt_index.index(opt_1))
for opt_2 in opt_rest:
os.environ['opt_2'] = opt_2
os.system('/usr/bin/python3 /opt/scripts/roll_api/get_ip.py $opt_2')
elif opt_1 == '-f':
if len(sys.argv) < 3: if len(sys.argv) < 3:
print(f"{c_br}需要至少一个字符串作为输入,退出...{c_e}\n") print(f"{c_br}需要至少一个字符串作为输入,退出...{c_e}\n")
exit(opt_index.index(opt_1)) exit(ord(option.strip('-')))
param='' param=''
for item in sys.argv[2:]: for item in sys.argv[2:]:
@ -85,94 +65,133 @@ elif opt_1 == '-f':
# print(f"本次计算得到的MD5的值为 - ", end='') # print(f"本次计算得到的MD5的值为 - ", end='')
os.system('echo -n $param | md5sum | cut -d " " -f 1') os.system('echo -n $param | md5sum | cut -d " " -f 1')
elif opt_1 == '-g': # -f
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") def number2date():
exit(opt_index.index(opt_1)) exit_on_wrong_number(2)
elif opt_1 == '-h':
os.system('/usr/bin/bash /opt/scripts/utool/usage.sh')
exit(opt_index.index(opt_1))
elif opt_1 == '-i':
if opt_rest == None:
print(f"This option({opt_1}) will return the domain registration info, and accept at least one domain parameter.")
exit(opt_index.index(opt_1))
for opt_2 in opt_rest:
os.environ['opt_2'] = opt_2
os.system('/usr/bin/python3 /opt/scripts/roll_api/domain_reg_check.py $opt_2')
elif opt_1 == '-j':
if len(sys.argv) == 2:
print(f"{c_br}-j选项将十进制或者十六进制数字作为入参转换成标准时间格式只接收第一个参数其他参数将被丢弃有歧义时使用'0x'或者'0X'来区分十进制和十六进制,退出...{c_e}\n")
exit(opt_index.index(opt_1))
os.environ['param'] = sys.argv[2] os.environ['param'] = sys.argv[2]
os.system('/usr/bin/bash /opt/scripts/utool/number2d.sh $param') os.system('/usr/bin/bash /opt/git/scripts/utool/number2d.sh $param')
elif opt_1 == '-k': # -g
def date2number():
if len(sys.argv) < 3: if len(sys.argv) < 3:
print(f"{c_br}-k选项:将输入的时间转换成十进制和十六进制,需要一个字符串格式的时间作为输入,退出...{c_e}\n") print(f"{c_br}-g选项:将输入的时间转换成十进制和十六进制,需要一个字符串格式的时间作为输入,退出...{c_e}\n")
exit(opt_index.index(opt_1)) exit(ord(option.strip('-')))
param='' param=''
for item in sys.argv[2:]: for item in sys.argv[2:]:
param += item + ' ' param += item + ' '
os.environ['param'] = param os.environ['param'] = param
os.system('/usr/bin/bash /opt/scripts/utool/date2n.sh $param') os.system('/usr/bin/bash /opt/git/scripts/utool/date2n.sh $param')
elif opt_1 == '-l': # -h
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") def usage():
exit(opt_index.index(opt_1)) exit_on_wrong_number()
elif opt_1 == '-m': print_usage()
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-n':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-o':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.")
exit(opt_index.index(opt_1))
elif opt_1 == '-p':
if opt_rest == None:
opt_rest = ['',]
opt_2 = opt_rest[0] # -i
os.environ['opt_2'] = opt_2 def ps_top_20():
os.system('/usr/bin/bash /opt/scripts/utool/genpw.sh $opt_2') exit_on_wrong_number()
os.system("/usr/bin/bash /opt/git/scripts/utool/ps_top_20.sh")
elif opt_1 == '-q': # -j
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") def docker_pid():
exit(opt_index.index(opt_1)) exit_on_wrong_number(2)
elif opt_1 == '-r': os.environ['param'] = sys.argv[2]
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") os.system('/usr/bin/bash /opt/git/scripts/utool/pid_in_docker.sh $param')
exit(opt_index.index(opt_1))
elif opt_1 == '-s': # -k
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") def company_two_factor():
exit(opt_index.index(opt_1)) exit_on_wrong_number()
elif opt_1 == '-t': # method 1
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") # os.system("/usr/bin/echo -n 'ujjpsx7q'")
exit(opt_index.index(opt_1)) # os.system("/usr/bin/oathtool -b --totp '22IH2VYKEQYOWVFCCHY5KTU4CYTJ7Z3O'")
elif opt_1 == '-u': # method 2
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") pin = 'ujjpsx7q'
exit(opt_index.index(opt_1)) totp = os.popen("/usr/bin/oathtool -b --totp '22IH2VYKEQYOWVFCCHY5KTU4CYTJ7Z3O'").read()
elif opt_1 == '-v': res = pin + totp
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") print(res, end='')
exit(opt_index.index(opt_1)) return res
elif opt_1 == '-w':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") # -p
exit(opt_index.index(opt_1)) def gen_passwd():
elif opt_1 == '-x': exit_on_wrong_number(2)
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") os.environ['length'] = sys.argv[2]
exit(opt_index.index(opt_1)) os.system('/usr/bin/bash /opt/git/scripts/utool/genpw.sh length')
elif opt_1 == '-y':
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") def exit_on_wrong_number(number=1):
exit(opt_index.index(opt_1)) if len(sys.argv) != (number+1):
elif opt_1 == '-z': print(f"{c_br}{sys.argv[1:]}: Wrong arguments!")
print(f"This option({opt_1}) is reserved now, nothing is bound on it.") print(f"Option `{option}' will {dict_func[option][0].strip()}")
exit(opt_index.index(opt_1)) print(f"NEED: {number}\tGIVE: {len(sys.argv)-1}\n{c_e}")
else: exit(ord(option.strip('-')))
print("This line SHOULD NOT be executed, please check carefully.")
exit(255) dict_func = {
'-a': [' print all local ports of using for now', list_local_using_port],
'-n': ['Reserved', None],
'-b': [' generate two-factor key of GITHUB', github_two_factor],
'-o': ['Reserved', None],
'-c': [' show external IP of this machine', get_external_ip],
'-p': ['*generate password of length 1~79', gen_passwd],
'-d': ['*show the location of ip(only v4 for now)', get_ip_location],
'-q': ['Reserved', None],
'-e': ['*generate md5 value of the input string', gen_md5],
'-r': ['Reserved', None],
'-f': ['*convert a (hexa)decimal to specific time format', number2date],
'-s': ['Reserved', None],
'-g': ['*convert multi-formats time to a decimal', date2number],
'-t': ['Reserved', None],
'-h': [' show this help information and exit', print_usage],
'-u': ['Reserved', None],
'-i': [' print top 20 mem and cpu process', ps_top_20],
'-v': ['Reserved', None],
'-j': ['*find a docker subprocess, if true then print info', docker_pid],
'-w': ['Reserved', None],
'-k': [' generate two-factor key of GITHUB', company_two_factor],
'-x': ['Reserved', None],
'-l': ['Reserved', None],
'-y': ['Reserved', None],
'-m': ['Reserved', None],
'-z': ['Reserved', None],
}
return dict_func[option][1]
def main():
global option
options = [ '-' + chr(x) for x in range(ord('a'), ord('z')+1)]
print_usage = utool('-h')
if len(sys.argv) > 1:
option = sys.argv[1]
if option in options:
func = utool(option)
if func == None:
print(f"{c_bg}Option `{option}' is reserved for now...{c_e}\n")
else:
func()
else:
print_usage()
else:
print_usage()
# global area below ↓
c_title = '\033[1;4;37;40m' # title color
c_text = '\033[37;40m' # text color
c_intro = '\033[3;32m' # text color
c_br = '\033[1;31m' # bold red
c_bg = '\033[1;32m' # bold green
c_by = '\033[1;33m' # bold yellow
c_bb = '\033[1;34m' # bold blue
c_bp = '\033[1;35m' # bold purple
c_bc = '\033[1;36m' # bold cyan
c_bir= '\033[1;3;31m' # * bold italic red
c_bib = '\033[1;3;34m' # * bold italic cyan
c_bic = '\033[1;3;36m' # bold italic cyan
c_e = '\033[0m' # reset
if __name__ == '__main__':
main()