From 962b00ac013ea4fa7b5cbf5317fdcfaff4f0681e Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Mon, 31 Jul 2023 22:24:01 +0800 Subject: [PATCH 01/33] Build a simple anonymous rsync server --- rsync/rsync.sh | 81 +++++++++++++++++++++++++++++++++ rsync/rsync_file_from_server.sh | 21 +++++++++ rsync/rsync_file_to_server.sh | 21 +++++++++ 3 files changed, 123 insertions(+) create mode 100644 rsync/rsync.sh create mode 100644 rsync/rsync_file_from_server.sh create mode 100644 rsync/rsync_file_to_server.sh diff --git a/rsync/rsync.sh b/rsync/rsync.sh new file mode 100644 index 0000000..d95539b --- /dev/null +++ b/rsync/rsync.sh @@ -0,0 +1,81 @@ +#!/bin/bash +#this script for start|stop rsync daemon service + +# 指定rsyncd.conf文件的路径 +RSYNC_CONF="/etc/rsyncd.conf" +RSYNC_PID_FILE="/var/run/rsyncd.pid" # rsync服务器进程ID文件路径 + +check_status() { + STATUS=$(ps -ef | egrep -q "rsync --daemon.*rsyncd.conf" | grep -v 'grep') +} +start() { + if [ "${STATUS}X" == "X" ]; then + rm -f $RSYNC_PID_FILE + # 启动rsync服务器 + rsync --daemon --config=$RSYNC_CONF + check_status + if [ "${STATUS}X" != "X" ]; then + echo "rsync service start.......OK" + fi + else + echo "rsync service is running !" + fi + +} + +stop() { + # 停止rsync服务器 + if [ "${STATUS}X" != "X" ]; then + kill -9 "$(cat $RSYNC_PID_FILE)" #读取并结束 进程 pid号 + check_status + if [ "${STATUS}X" == "X" ]; then + echo "rsync service stop.......OK" + fi + else + echo "rsync service is not running !" + fi +} + +restart() { + # 重启rsync服务器 + stop + start +} + +status() { + # 检查rsync服务器的状态 + if [ "${STATUS}X" != "X" ]; then + echo "rsync service is running !" + else + echo "rsync service is not running !" + fi +} + +main() { + + if ! grep "rsync --daemon" /etc/rc.local; then + echo "rsync --daemon --config=$RSYNC_CONF" >>/etc/rc.local #加入开机自启动 + fi + check_status + case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + status + ;; + *) + echo "使用方法: $0 {start|stop|restart|status}" + exit 1 + ;; + esac + +} + +main "$@" diff --git a/rsync/rsync_file_from_server.sh b/rsync/rsync_file_from_server.sh new file mode 100644 index 0000000..4a9893a --- /dev/null +++ b/rsync/rsync_file_from_server.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# 定义rsync服务器的IP地址和源文件夹 +RSYNC_SERVER="rsync://192.168.98.129" +SOURCE_FOLDER="/mirrors/" + +# 定义要同步的目标文件夹 +DEST_FOLDER="/opt/mirrors/" + +# 定义日志文件的路径 +LOG_FILE="/tmp/logfile.log" + +# 同步操作 +rsync -avzp --delete "$RSYNC_SERVER:$DEST_FOLDER" "$SOURCE_FOLDER">> $LOG_FILE + +# 检查rsync命令的返回状态 +if [ $? -eq 0 ]; then + echo "同步成功!" +else + echo "同步失败,请检查日志文件 $LOG_FILE 以获取更多详细信息。" +fi diff --git a/rsync/rsync_file_to_server.sh b/rsync/rsync_file_to_server.sh new file mode 100644 index 0000000..00f51c0 --- /dev/null +++ b/rsync/rsync_file_to_server.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# 定义rsync服务器的IP地址和目标文件夹 +RSYNC_SERVER="rsync://192.168.98.129" +DEST_FOLDER="/mirrors/" + +# 定义要同步的源文件夹 +SOURCE_FOLDER="/opt/mirrors/" + +# 定义日志文件的路径 +LOG_FILE="/tmp/logfile.log" + +# 同步操作 +rsync -avzp --delete "$SOURCE_FOLDER" "$RSYNC_SERVER:$DEST_FOLDER" >> $LOG_FILE + +# 检查rsync命令的返回状态 +if [ $? -eq 0 ]; then + echo "同步成功!" +else + echo "同步失败,请检查日志文件 $LOG_FILE 以获取更多详细信息。" +fi From a6ba4c929f33d46e59106c1c1636111cfa76b47e Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Mon, 31 Jul 2023 22:24:26 +0800 Subject: [PATCH 02/33] Build a simple anonymous rsync server --- rsync/rsyncd.conf | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 rsync/rsyncd.conf diff --git a/rsync/rsyncd.conf b/rsync/rsyncd.conf new file mode 100644 index 0000000..5ab6702 --- /dev/null +++ b/rsync/rsyncd.conf @@ -0,0 +1,19 @@ +uid = root +gid = root +use chroot = yes +log file = /var/log/rsyncd.log +pid file = /var/run/rsyncd.pid +lock file = /var/run/rsync.lock +port = 873 +# 模块定义 +[mirrors] +comment = "backup" +path = /opt/mirrors #模块对应的位置(路径) +ignore errors #忽略错误程序 +read only = false #是否只读(这里是假,表示能写入) +list = false #是否可以列表* +# hosts allow = 172.16.2.0/24 #准许访问rsync服务器客户范围(白名单) +#hosts deny = 0.0.0.0/32 #禁止访问rsync服务器客户范围(黑名单) +#auth users = rsync_backup #不存在的用户,只用于认证 +#设置进行连接认证的密钥文件: +#secrets file = /etc/rsync.password #认证时密钥文件 From 0bff58b5502059d7c9db83200cc69367a31a3ec6 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 3 Aug 2023 00:38:42 +0800 Subject: [PATCH 03/33] modify rsync shell --- rsync/rsync.sh | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/rsync/rsync.sh b/rsync/rsync.sh index d95539b..0bbd80d 100644 --- a/rsync/rsync.sh +++ b/rsync/rsync.sh @@ -1,20 +1,21 @@ #!/bin/bash #this script for start|stop rsync daemon service +# status1=$(ps -ef | egrep "rsync --daemon.*rsyncd.conf" | grep -v 'grep') # 指定rsyncd.conf文件的路径 RSYNC_CONF="/etc/rsyncd.conf" RSYNC_PID_FILE="/var/run/rsyncd.pid" # rsync服务器进程ID文件路径 +START_RSYNC="rsync --daemon --config=$RSYNC_CONF" -check_status() { - STATUS=$(ps -ef | egrep -q "rsync --daemon.*rsyncd.conf" | grep -v 'grep') -} start() { - if [ "${STATUS}X" == "X" ]; then + status1=$(ps -ef | grep -E "rsync --daemon.*rsyncd.conf" | grep -v 'grep') + if [ "${status1}X" == "X" ]; then rm -f $RSYNC_PID_FILE # 启动rsync服务器 - rsync --daemon --config=$RSYNC_CONF - check_status - if [ "${STATUS}X" != "X" ]; then + ${START_RSYNC} + # rsync --daemon --config=$RSYNC_CONF + status2=$(ps -ef | grep -E "rsync --daemon.*rsyncd.conf" | grep -v 'grep') + if [ "${status2}X" != "X" ]; then echo "rsync service start.......OK" fi else @@ -25,10 +26,11 @@ start() { stop() { # 停止rsync服务器 - if [ "${STATUS}X" != "X" ]; then + status1=$(ps -ef | grep -E "rsync --daemon.*rsyncd.conf" | grep -v 'grep') + if [ "${status1}X" != "X" ]; then kill -9 "$(cat $RSYNC_PID_FILE)" #读取并结束 进程 pid号 - check_status - if [ "${STATUS}X" == "X" ]; then + status2=$(ps -ef | grep -E "rsync --daemon.*rsyncd.conf" | grep -v 'grep') + if [ "${status2}X" == "X" ]; then echo "rsync service stop.......OK" fi else @@ -44,19 +46,23 @@ restart() { status() { # 检查rsync服务器的状态 - if [ "${STATUS}X" != "X" ]; then + status1=$(ps -ef | grep -E "rsync --daemon.*rsyncd.conf" | grep -v 'grep') + if [ "${status1}X" != "X" ]; then echo "rsync service is running !" else echo "rsync service is not running !" fi } -main() { - - if ! grep "rsync --daemon" /etc/rc.local; then +add_boot_up() { + # 加入开机自启动 + if ! grep -E "rsync --daemon" /etc/rc.local >/dev/null; then echo "rsync --daemon --config=$RSYNC_CONF" >>/etc/rc.local #加入开机自启动 fi - check_status +} + +main() { + add_boot_up case "$1" in start) start @@ -71,7 +77,7 @@ main() { status ;; *) - echo "使用方法: $0 {start|stop|restart|status}" + echo "Usage: $0 {start|stop|restart|status}" exit 1 ;; esac From 6c8d1f5a7688a4e707cedd9c9a0202e9ea4b9a2f Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Tue, 8 Aug 2023 23:48:17 +0800 Subject: [PATCH 04/33] lottery procedure --- shell/lottery.sh | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 shell/lottery.sh diff --git a/shell/lottery.sh b/shell/lottery.sh new file mode 100644 index 0000000..ab9f9b2 --- /dev/null +++ b/shell/lottery.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +###### +# 需要一个抓阄的程序: + +# 要求: + +# 1、执行脚本后,想去的同学输入英文名字全拼,产生随机数01-99之间的数字,数字越大就去参加项目实践,前面已经抓到的数字,下次不能在出现相同数字。 + +# 2、第一个输入名字后,屏幕输出信息,并将名字和数字记录到文件里,程序不能退出继续等待别的学生输入。 +##### +namelist=/tmp/name.txt +#判断数字是否重复 +judgeNum() { + if grep -w "$1" $namelist; then + a=1 + else + a=0 + fi +} + +while read -rp "please input your name:" name; do + a=1 + while [ $a -eq 1 ]; do #数字不重复就跳出第二个while ,重复就再生成一个 + num=$((RANDOM % 100 + 1)) + judgeNum $num + done + echo "$name:$num" | tee -a $namelist #结果显示到屏幕 并 追加到文件中 +done From 60ae3d77c56d2d5d768472d0c54e220c5e59f8ae Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Wed, 23 Aug 2023 01:08:04 +0800 Subject: [PATCH 05/33] =?UTF-8?q?=E8=A7=A3=E5=AF=86=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shell/decrypt.sh | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 shell/decrypt.sh diff --git a/shell/decrypt.sh b/shell/decrypt.sh new file mode 100644 index 0000000..dac1d1b --- /dev/null +++ b/shell/decrypt.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +array=(21029299 f2b61ccf a3da1677 1f6d12dd 8721469a) +count=0 + +for i in $(seq 0 32767); do + variable=$(echo $i | md5sum | cut -c 1-8) + if [[ ${array[*]} =~ $variable ]]; then + let count++ + echo "$count: $i ==>> $variable" + fi + [ $count -eq 5 ] && exit +done From 191bec85cd7fee5133e9d2df42fea3b644c769f9 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Tue, 29 Aug 2023 21:58:14 +0800 Subject: [PATCH 06/33] check url --- shell/check_url.sh | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 shell/check_url.sh diff --git a/shell/check_url.sh b/shell/check_url.sh new file mode 100644 index 0000000..8c8e350 --- /dev/null +++ b/shell/check_url.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +[ -f /etc/init.d/functions ] && source /etc/init.d/functions + +array=( + http://www.163.com + http://www.taobao.com + http://oldboy.blog.51cto.com + http://10.0.0.7 +) + +wait() { + echo -n "wait" + for ((a = 1; a <= 3; a++)); do + echo -n "." + sleep 1 + done +} + +check_url() { + wget -T 5 -t 2 --spider "$1" &>/dev/null + RETVAL=$? + if [ $RETVAL -eq 0 ]; then + action "check $1" /bin/true + else + action "check $1" /bin/false + fi + return $RETVAL +} + +main() { + for ((i = 0; i < ${#array[*]}; i++)); do + wait + check_url "${array[i]}" + done +} + +main From 33d6abc22d4d80f8a368e9af3044e4593e17a9de Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Fri, 8 Sep 2023 00:15:40 +0800 Subject: [PATCH 07/33] word sort --- shell/word_sort.sh | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 shell/word_sort.sh diff --git a/shell/word_sort.sh b/shell/word_sort.sh new file mode 100644 index 0000000..ccba762 --- /dev/null +++ b/shell/word_sort.sh @@ -0,0 +1,42 @@ +#!/bin/bash +a="the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation" + +word=/tmp/word.txt + +word_sort() { + for i in $a; do + echo "$i" >>$word + done + cat $word | sort | uniq -c | sort -rn +} + +letter_sort() { + echo "$a" | + while read -r line; do + for i in $(seq 1 ${#line}); do + echo "$line" | cut -c "$i" >>$word + done + done + cat $word | sort | uniq -c | sort -rn +} +main() { + + [ -f $word ] && rm -f $word + echo "word sort input 1" + echo "letter sort input 2" + read -r num + + case $num in + "1") + word_sort + ;; + "2") + letter_sort + ;; + *) + echo "please input 1 or 2" + ;; + esac +} + +main From 498f29318119a0e5218da879f2f3dae4ab79e198 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sun, 17 Sep 2023 19:26:07 +0800 Subject: [PATCH 08/33] File change monitoring --- inotify/watchd.py | 97 +++++++++++++++++++++++++++++++++++ inotify/watching.py | 121 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 inotify/watchd.py create mode 100644 inotify/watching.py diff --git a/inotify/watchd.py b/inotify/watchd.py new file mode 100644 index 0000000..1e37f7b --- /dev/null +++ b/inotify/watchd.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +''' +@File : watchd.py +@Time : 2023/09/17 19:16:14 +@Author : jumploop +@Version : 1.0 +@Desc : None +''' + +import datetime +import time + +from watchdog.events import * +from watchdog.observers import Observer + + +class Logger: + """log record""" + + def __init__(self): + self.logger = logging.getLogger('watching') + self.logger.setLevel(logging.INFO) + + def statup(self, path, stream=True): + """statup""" + write_handler = logging.handlers.TimedRotatingFileHandler( + path, + when='midnight', + interval=1, + backupCount=7, + atTime=datetime.time(0, 0, 0, 0), + ) + write_handler.setFormatter( + logging.Formatter( + "%(asctime)s - %(levelname)s - %(module)s[:%(lineno)d] - %(message)s" + ) + ) + + if stream: + stream_handler = logging.StreamHandler() + stream_handler.setFormatter( + logging.Formatter( + "%(asctime)s - %(levelname)s - %(module)s[:%(lineno)d] - %(message)s" + ) + ) + self.logger.addHandler(stream_handler) + self.logger.addHandler(write_handler) + + return self.logger + + +class FileEventHandler(FileSystemEventHandler): + """file event handler""" + + def __init__(self): + FileSystemEventHandler.__init__(self) + + def on_moved(self, event): + if event.is_directory: + logger.info( + "directory moved from %s to %s", event.src_path, event.dest_path + ) + else: + logger.info("file moved from %s to %s", event.src_path, event.dest_path) + + def on_created(self, event): + if event.is_directory: + logger.info("directory created:%s", event.src_path) + else: + logger.info("file created:%s", event.src_path) + + def on_deleted(self, event): + if event.is_directory: + logger.info("directory deleted:%s", event.src_path) + else: + logger.info("file deleted:%s", event.src_path) + + def on_modified(self, event): + if event.is_directory: + logger.info("directory modified:%s", event.src_path) + else: + logger.info("file modified:%s", event.src_path) + + +if __name__ == "__main__": + logger = Logger().statup("test.log", stream=True) + observer = Observer() + event_handler = FileEventHandler() + observer.schedule(event_handler, "/opt", True) + observer.start() + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + observer.stop() + observer.join() diff --git a/inotify/watching.py b/inotify/watching.py new file mode 100644 index 0000000..4c84c36 --- /dev/null +++ b/inotify/watching.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +''' +@File : watching.py +@Time : 2023/09/17 17:34:17 +@Author : jumploop +@Version : 1.0 +@Desc : None +''' + +import os +import shutil +import time +import datetime +import logging +import logging.handlers +from concurrent.futures import ThreadPoolExecutor + +import pyinotify + + +def copy_files(path): + """copy file""" + logger.info('copy file %s starting', path) + shutil.copy(path, "/tmp") + logger.info('copy file %s finished', path) + + +class Logger: + """log record""" + + def __init__(self): + self.logger = logging.getLogger('watching') + self.logger.setLevel(logging.INFO) + + def statup(self, path, stream=True): + """statup""" + write_handler = logging.handlers.TimedRotatingFileHandler( + path, + when='midnight', + interval=1, + backupCount=7, + atTime=datetime.time(0, 0, 0, 0), + ) + write_handler.setFormatter( + logging.Formatter( + "%(asctime)s - %(levelname)s - %(module)s[:%(lineno)d] - %(message)s" + ) + ) + + if stream: + stream_handler = logging.StreamHandler() + stream_handler.setFormatter( + logging.Formatter( + "%(asctime)s - %(levelname)s - %(module)s[:%(lineno)d] - %(message)s" + ) + ) + self.logger.addHandler(stream_handler) + self.logger.addHandler(write_handler) + + return self.logger + + +class MonitorEvent(pyinotify.ProcessEvent): + """monitor event""" + + def __init__(self, func): + super().__init__() + self.func = func + self.flag = time.time() + + def process_IN_CREATE(self, event): + """ + 文件被创建 + """ + if time.time() - self.flag > 0: + file_full_path = os.path.join(event.path, event.name) + logger.info("%s 被创建!", file_full_path) + self.flag = time.time() + # 这里就可以做想做的事情了 + + def process_IN_MODIFY(self, event): + """文件被修改""" + if time.time() - self.flag > 3: + file_full_path = os.path.join(event.path, event.name) + logger.info("%s 被修改!", file_full_path) + self.flag = time.time() + # 这里就可以做想做的事情了 + + def process_IN_DELETE(self, event): + """文件被删除""" + if time.time() - self.flag > 0: + file_full_path = os.path.join(event.path, event.name) + logger.info("%s 被删除!", file_full_path) + self.flag = time.time() + # 这里就可以做想做的事情了 + + def process_IN_CLOSE_WRITE(self, event): + """文件写入完毕""" + if time.time() - self.flag > 0: + file_full_path = os.path.join(event.path, event.name) + logger.info("%s 写入完毕!", file_full_path) + self.flag = time.time() + # 这里就可以做想做的事情了 + with ThreadPoolExecutor(max_workers=10) as executor: + executor.submit(self.func, file_full_path) + + +def main(): + """main function""" + path = '/opt' # 监控目录 + watch_manager = pyinotify.WatchManager() + watch_manager.add_watch(path, pyinotify.ALL_EVENTS, rec=True) + event = MonitorEvent(func=copy_files) + notifier = pyinotify.ThreadedNotifier(watch_manager, event) + notifier.loop() + + +if __name__ == '__main__': + logger = Logger().statup("test.log", stream=True) + main() From c91f6628311a56c18ca8c5114ff5afd69606cec7 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sun, 17 Sep 2023 20:29:01 +0800 Subject: [PATCH 09/33] modify watching --- inotify/watching.py | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/inotify/watching.py b/inotify/watching.py index 4c84c36..6f8027a 100644 --- a/inotify/watching.py +++ b/inotify/watching.py @@ -9,6 +9,7 @@ ''' import os +import pwd import shutil import time import datetime @@ -74,41 +75,51 @@ def process_IN_CREATE(self, event): 文件被创建 """ if time.time() - self.flag > 0: - file_full_path = os.path.join(event.path, event.name) - logger.info("%s 被创建!", file_full_path) + get_file_status(event) + logger.info("%s 被创建!", event.pathname) self.flag = time.time() # 这里就可以做想做的事情了 def process_IN_MODIFY(self, event): """文件被修改""" if time.time() - self.flag > 3: - file_full_path = os.path.join(event.path, event.name) - logger.info("%s 被修改!", file_full_path) + get_file_status(event) + logger.info("%s 被修改!", event.pathname) self.flag = time.time() # 这里就可以做想做的事情了 + with ThreadPoolExecutor(max_workers=10) as executor: + executor.submit(self.func, event.pathname) def process_IN_DELETE(self, event): """文件被删除""" if time.time() - self.flag > 0: - file_full_path = os.path.join(event.path, event.name) - logger.info("%s 被删除!", file_full_path) + logger.info("%s 被删除!", event.pathname) self.flag = time.time() # 这里就可以做想做的事情了 def process_IN_CLOSE_WRITE(self, event): """文件写入完毕""" if time.time() - self.flag > 0: - file_full_path = os.path.join(event.path, event.name) - logger.info("%s 写入完毕!", file_full_path) + get_file_status(event) + logger.info("%s 写入完毕!", event.pathname) self.flag = time.time() # 这里就可以做想做的事情了 - with ThreadPoolExecutor(max_workers=10) as executor: - executor.submit(self.func, file_full_path) + + +def get_file_status(event): + """get file status""" + file_info = os.stat(event.pathname) + modified_time = datetime.datetime.fromtimestamp(file_info.st_mtime) + modified_user = pwd.getpwuid(file_info.st_uid).pw_name + logger.info("文件/目录修改:") + logger.info("路径:%s", event.pathname) + logger.info("修改时间: %s", modified_time) + logger.info("修改用户:%s", modified_user) def main(): """main function""" - path = '/opt' # 监控目录 + path = '/opt' # 监控目录 watch_manager = pyinotify.WatchManager() watch_manager.add_watch(path, pyinotify.ALL_EVENTS, rec=True) event = MonitorEvent(func=copy_files) From 9edd3fe90faeb55c305198bdf1efb7def7d8b547 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sun, 17 Sep 2023 20:31:49 +0800 Subject: [PATCH 10/33] pyinotify simple demo --- inotify/simple.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 inotify/simple.py diff --git a/inotify/simple.py b/inotify/simple.py new file mode 100644 index 0000000..faa72d5 --- /dev/null +++ b/inotify/simple.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +''' +@File : simple.py +@Time : 2023/09/17 20:29:55 +@Author : jumploop +@Version : 1.0 +@Desc : None +''' + +import pyinotify + +wm = pyinotify.WatchManager() + + +class EventHandler(pyinotify.ProcessEvent): + """事件处理""" + + def process_IN_CREATE(self, event): + """处理文件创建""" + print("create:", event.pathname) + + def process_IN_DELETE(self, event): + """处理文件删除""" + print("delete:", event.pathname) + + +handler = EventHandler() +wm.add_watch('/tmp', pyinotify.IN_DELETE | pyinotify.IN_CREATE, rec=True) +notifier = pyinotify.Notifier(wm, handler) +notifier.loop() From 0daeabf0f653dc565d1604d84b7d552d63b7e0aa Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sun, 17 Sep 2023 21:13:40 +0800 Subject: [PATCH 11/33] modify watching.py --- inotify/watching.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/inotify/watching.py b/inotify/watching.py index 6f8027a..fcd25cb 100644 --- a/inotify/watching.py +++ b/inotify/watching.py @@ -75,7 +75,6 @@ def process_IN_CREATE(self, event): 文件被创建 """ if time.time() - self.flag > 0: - get_file_status(event) logger.info("%s 被创建!", event.pathname) self.flag = time.time() # 这里就可以做想做的事情了 @@ -83,8 +82,13 @@ def process_IN_CREATE(self, event): def process_IN_MODIFY(self, event): """文件被修改""" if time.time() - self.flag > 3: - get_file_status(event) - logger.info("%s 被修改!", event.pathname) + file_info = os.stat(event.pathname) + modified_time = datetime.datetime.fromtimestamp(file_info.st_mtime) + modified_user = pwd.getpwuid(file_info.st_uid).pw_name + logger.info("文件/目录修改:") + logger.info("路径:%s", event.pathname) + logger.info("修改时间: %s", modified_time) + logger.info("修改用户:%s", modified_user) self.flag = time.time() # 这里就可以做想做的事情了 with ThreadPoolExecutor(max_workers=10) as executor: @@ -96,27 +100,21 @@ def process_IN_DELETE(self, event): logger.info("%s 被删除!", event.pathname) self.flag = time.time() # 这里就可以做想做的事情了 + deleted_time = datetime.datetime.now() + deleted_user = pwd.getpwuid(os.getuid()).pw_name + logger.info("文件/目录删除:") + logger.info("路径:%s", event.pathname) + logger.info("修改时间: %s", deleted_time) + logger.info("修改用户:%s", deleted_user) def process_IN_CLOSE_WRITE(self, event): """文件写入完毕""" if time.time() - self.flag > 0: - get_file_status(event) logger.info("%s 写入完毕!", event.pathname) self.flag = time.time() # 这里就可以做想做的事情了 -def get_file_status(event): - """get file status""" - file_info = os.stat(event.pathname) - modified_time = datetime.datetime.fromtimestamp(file_info.st_mtime) - modified_user = pwd.getpwuid(file_info.st_uid).pw_name - logger.info("文件/目录修改:") - logger.info("路径:%s", event.pathname) - logger.info("修改时间: %s", modified_time) - logger.info("修改用户:%s", modified_user) - - def main(): """main function""" path = '/opt' # 监控目录 From 08a805521b706512f348dce64942cb27507cbb4c Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sun, 17 Sep 2023 21:33:12 +0800 Subject: [PATCH 12/33] add new file --- inotify/simple2.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 inotify/simple2.py diff --git a/inotify/simple2.py b/inotify/simple2.py new file mode 100644 index 0000000..6f82bd4 --- /dev/null +++ b/inotify/simple2.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import pyinotify +import os +import pwd +import datetime + + +class EventHandler(pyinotify.ProcessEvent): + def process_default(self, event): + if event.mask & pyinotify.IN_CREATE: + file_info = os.stat(event.pathname) + modified_time = datetime.datetime.fromtimestamp(file_info.st_mtime) + modified_user = pwd.getpwuid(file_info.st_uid).pw_name + + with open("log.txt", "a") as log_file: + log_file.write("文件/目录创建:\n") + log_file.write("路径: {0}\n".format(event.pathname)) + log_file.write("创建时间: {0}\n".format(modified_time)) + log_file.write("创建用户: {0}\n\n".format(modified_user)) + if event.mask & pyinotify.IN_MODIFY: + file_info = os.stat(event.pathname) + modified_time = datetime.datetime.fromtimestamp(file_info.st_mtime) + modified_user = pwd.getpwuid(file_info.st_uid).pw_name + + with open("log.txt", "a") as log_file: + log_file.write("文件/目录修改:\n") + log_file.write("路径: {0}\n".format(event.pathname)) + log_file.write("修改时间: {0}\n".format(modified_time)) + log_file.write("修改用户: {0}\n\n".format(modified_user)) + elif event.mask & pyinotify.IN_DELETE: + deleted_time = datetime.datetime.now() + deleted_user = pwd.getpwuid(os.getuid()).pw_name + with open("log.txt", "a") as log_file: + log_file.write("文件/目录删除:\n") + log_file.write("路径: {0}\n".format(event.pathname)) + log_file.write("修改时间: {0}\n".format(deleted_time)) + log_file.write("修改用户: {0}\n\n".format(deleted_user)) + + +def main(): + """Program entrance""" + # 创建监控器实例并关联监控器类和目录 + watch_manager = pyinotify.WatchManager() + event_handler = EventHandler() + + watch_manager.add_watch('/opt/mirrors', pyinotify.ALL_EVENTS, rec=True) + notifier = pyinotify.Notifier(watch_manager, event_handler) + + # 启动监控器并开始监听目录的变化 + notifier.loop() + + +if __name__ == '__main__': + main() From 42fb8e70182b38e43f702ef42a47fbd5a7391b36 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sun, 17 Sep 2023 21:34:26 +0800 Subject: [PATCH 13/33] modify simple.py --- inotify/simple.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/inotify/simple.py b/inotify/simple.py index faa72d5..b3fc17e 100644 --- a/inotify/simple.py +++ b/inotify/simple.py @@ -25,7 +25,13 @@ def process_IN_DELETE(self, event): print("delete:", event.pathname) -handler = EventHandler() -wm.add_watch('/tmp', pyinotify.IN_DELETE | pyinotify.IN_CREATE, rec=True) -notifier = pyinotify.Notifier(wm, handler) -notifier.loop() +def main(): + """Program entrance""" + handler = EventHandler() + wm.add_watch('/tmp', pyinotify.IN_DELETE | pyinotify.IN_CREATE, rec=True) + notifier = pyinotify.Notifier(wm, handler) + notifier.loop() + + +if __name__ == '__main__': + main() From 4041f4077df3ea1a310181f0305d09d57d49aa85 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Mon, 18 Sep 2023 20:17:09 +0800 Subject: [PATCH 14/33] update watching.py --- inotify/watching.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/inotify/watching.py b/inotify/watching.py index fcd25cb..d577d9c 100644 --- a/inotify/watching.py +++ b/inotify/watching.py @@ -85,10 +85,12 @@ def process_IN_MODIFY(self, event): file_info = os.stat(event.pathname) modified_time = datetime.datetime.fromtimestamp(file_info.st_mtime) modified_user = pwd.getpwuid(file_info.st_uid).pw_name - logger.info("文件/目录修改:") - logger.info("路径:%s", event.pathname) - logger.info("修改时间: %s", modified_time) - logger.info("修改用户:%s", modified_user) + logger.info( + "文件/目录修改:\n路径:%s, 修改时间: %s, 修改用户:%s", + event.pathname, + modified_time, + modified_user, + ) self.flag = time.time() # 这里就可以做想做的事情了 with ThreadPoolExecutor(max_workers=10) as executor: @@ -102,10 +104,12 @@ def process_IN_DELETE(self, event): # 这里就可以做想做的事情了 deleted_time = datetime.datetime.now() deleted_user = pwd.getpwuid(os.getuid()).pw_name - logger.info("文件/目录删除:") - logger.info("路径:%s", event.pathname) - logger.info("修改时间: %s", deleted_time) - logger.info("修改用户:%s", deleted_user) + logger.info( + "文件/目录删除:\n路径:%s, 修改时间: %s, 修改用户:%s", + event.pathname, + deleted_time, + deleted_user, + ) def process_IN_CLOSE_WRITE(self, event): """文件写入完毕""" From e9f807048dbde18b67e40b921df6e88a553bf754 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sat, 23 Sep 2023 14:27:53 +0800 Subject: [PATCH 15/33] test execute time --- decorator/timer.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 decorator/timer.py diff --git a/decorator/timer.py b/decorator/timer.py new file mode 100644 index 0000000..54b96a8 --- /dev/null +++ b/decorator/timer.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import time + +def timer(func): + def wrapper(*args, **kwargs): + start_time=time.time() + result=func(*args, **kwargs) + end_time=time.time() + print(f'{func.__name__} took {end_time-start_time:.2f} seconds to execute.') + return result + return wrapper + +@timer +def my_func(): + time.sleep(3) + print('hello world') + return "ok" + + +if __name__ == '__main__': + print(my_func()) From ad7c57df360228c6ee58b671967195e8e4652779 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sat, 23 Sep 2023 14:36:02 +0800 Subject: [PATCH 16/33] Caching results --- decorator/memoize.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 decorator/memoize.py diff --git a/decorator/memoize.py b/decorator/memoize.py new file mode 100644 index 0000000..0baa4ff --- /dev/null +++ b/decorator/memoize.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +def memoize(func): + cache = {} + + def wrapper(*args): + if args in cache: + return cache[args] + result = func(*args) + cache[args] = result + return result + + return wrapper + + +@memoize +def fibonacci(n): + if n <= 1: + return n + return fibonacci(n - 1) + fibonacci(n - 2) + + +if __name__ == "__main__": + print(fibonacci(2)) From c3ef8db3319eda0540269eaa3f150a87afb57e5f Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sun, 24 Sep 2023 22:44:00 +0800 Subject: [PATCH 17/33] valid data --- decorator/validate_input.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 decorator/validate_input.py diff --git a/decorator/validate_input.py b/decorator/validate_input.py new file mode 100644 index 0000000..6bbb934 --- /dev/null +++ b/decorator/validate_input.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +''' +@File : validate_input.py +@Time : 2023/09/23 20:39:11 +@Author : jumploop +@Version : 1.0 +''' + + +def validate_input(func): + def wrapper(*args, **kwargs): + # your data validation logic here + if valid_date: + return func(*args, **kwargs) + else: + raise ValueError('Invalid data. Please check your inputs.') + + return wrapper + + +@validate_input +def my_func(data): + pass From 60a4317cbac65a0eea9c4efe6b0eae067fce0eac Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Mon, 25 Sep 2023 00:56:34 +0800 Subject: [PATCH 18/33] log results --- decorator/log_results.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 decorator/log_results.py diff --git a/decorator/log_results.py b/decorator/log_results.py new file mode 100644 index 0000000..b1355d0 --- /dev/null +++ b/decorator/log_results.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +def log_results(func): + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + with open("results.log", "a") as log_file: + log_file.write(f"{func.__name__} - Result: {result}\n") + return result + + return wrapper + + +@log_results +def calculate_metrics(data): + # Your metric calculation code here + return data + + +if __name__ == "__main__": + calculate_metrics(123) From eecce5ba61e17bb39d019b74db40a81ed3e165d2 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Mon, 25 Sep 2023 01:00:41 +0800 Subject: [PATCH 19/33] suppress errors --- decorator/suppress_errors.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 decorator/suppress_errors.py diff --git a/decorator/suppress_errors.py b/decorator/suppress_errors.py new file mode 100644 index 0000000..ed30329 --- /dev/null +++ b/decorator/suppress_errors.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +def suppress_errors(func): + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except Exception as e: + print(f"Error in {func.__name__}: {e}") + return None + + return wrapper + + +@suppress_errors +def preprocess_data(data): + # Your data preprocessing code here + return data / 0 + + +if __name__ == "__main__": + preprocess_data(123) From 57e885dd079dafc309670b88513b8ba88da5d6ab Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Mon, 25 Sep 2023 01:03:52 +0800 Subject: [PATCH 20/33] validate output --- decorator/validate_output.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 decorator/validate_output.py diff --git a/decorator/validate_output.py b/decorator/validate_output.py new file mode 100644 index 0000000..cc4ba94 --- /dev/null +++ b/decorator/validate_output.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +def valid_output(data): + return isinstance(data, int) + + +def validate_output(func): + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + if valid_output(result): + return result + else: + raise ValueError("Invalid output. Please check your function logic.") + + return wrapper + + +@validate_output +def clean_data(data): + # Your data cleaning code here + return data + + +if __name__ == "__main__": + clean_data("12") From f876da6770a8112fa2578e6592752d0cabe39415 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 28 Sep 2023 21:38:03 +0800 Subject: [PATCH 21/33] Retry execution --- decorator/retry.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 decorator/retry.py diff --git a/decorator/retry.py b/decorator/retry.py new file mode 100644 index 0000000..dac1107 --- /dev/null +++ b/decorator/retry.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import time +import requests + + +def retry(max_attempts, delay): + def decorator(func): + def wrapper(*args, **kwargs): + attempts = 0 + while attempts < max_attempts: + try: + return func(*args, **kwargs) + except Exception as e: + print( + f"Attempt {attempts + 1} failed. Retrying in {delay} seconds." + ) + attempts += 1 + time.sleep(delay) + raise Exception("Max retry attempts exceeded.") + + return wrapper + + return decorator + + +@retry(max_attempts=3, delay=2) +def fetch_data_from_api(api_url): + # Your API data fetching code here + response = requests.get(api_url) + return response.json() + + +if __name__ == "__main__": + print(fetch_data_from_api("https://www.google.com/")) From 2ca65c199c26448ab0f10cbcf1354cb57663a880 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 28 Sep 2023 21:43:38 +0800 Subject: [PATCH 22/33] visualize results --- decorator/visualize_results.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 decorator/visualize_results.py diff --git a/decorator/visualize_results.py b/decorator/visualize_results.py new file mode 100644 index 0000000..7bfe29f --- /dev/null +++ b/decorator/visualize_results.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import matplotlib.pyplot as plt + + +def visualize_results(func): + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + plt.figure() + # Your visualization code here + plt.show() + return result + + return wrapper + + +@visualize_results +def analyze_and_visualize(data): + # Your combined analysis and visualization code here + return data + + +if __name__ == "__main__": + print(analyze_and_visualize("data")) From 5f33e55391021cfc478d66c6d75768af0cc8b741 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 28 Sep 2023 22:13:13 +0800 Subject: [PATCH 23/33] visualize results --- decorator/visualize_results.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/decorator/visualize_results.py b/decorator/visualize_results.py index 7bfe29f..ff36c19 100644 --- a/decorator/visualize_results.py +++ b/decorator/visualize_results.py @@ -1,6 +1,8 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt +import numpy as np +import pandas as pd def visualize_results(func): @@ -8,6 +10,7 @@ def wrapper(*args, **kwargs): result = func(*args, **kwargs) plt.figure() # Your visualization code here + plt.plot(result) plt.show() return result @@ -17,7 +20,10 @@ def wrapper(*args, **kwargs): @visualize_results def analyze_and_visualize(data): # Your combined analysis and visualization code here - return data + data_DataFrame = pd.DataFrame( + {"x1": np.random.rand(10), "x2": np.random.rand(10), "x3": np.random.rand(10)} + ) + return data_DataFrame if __name__ == "__main__": From 279135150988133b536e41a6c27d019fd139c648 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 28 Sep 2023 22:15:22 +0800 Subject: [PATCH 24/33] debug --- decorator/debug.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 decorator/debug.py diff --git a/decorator/debug.py b/decorator/debug.py new file mode 100644 index 0000000..3581b4c --- /dev/null +++ b/decorator/debug.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +def debug(func): + def wrapper(*args, **kwargs): + print(f"Debugging {func.__name__} - args: {args}, kwargs: {kwargs}") + return func(*args, **kwargs) + + return wrapper + + +@debug +def complex_data_processing(data, threshold=0.5): + # Your complex data processing code here + return data + + +if __name__ == "__main__": + print(complex_data_processing(1)) From b929bf7e75d2302b44bba8387fc2e60a1fa3582e Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 28 Sep 2023 22:17:55 +0800 Subject: [PATCH 25/33] deprecated function --- decorator/deprecated.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 decorator/deprecated.py diff --git a/decorator/deprecated.py b/decorator/deprecated.py new file mode 100644 index 0000000..9064d4b --- /dev/null +++ b/decorator/deprecated.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import warnings + + +def deprecated(func): + def wrapper(*args, **kwargs): + warnings.warn( + f"{func.__name__} is deprecated and will be removed in future versions.", + DeprecationWarning, + ) + return func(*args, **kwargs) + + return wrapper + + +@deprecated +def old_data_processing(data): + # Your old data processing code here + return data + + +if __name__ == "__main__": + print(old_data_processing("foo")) From 05a56b672021892aa2fc7cc5cbb7d2810c11c10c Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Sat, 14 Oct 2023 21:53:31 +0800 Subject: [PATCH 26/33] bin to dump --- tools/bin2dump.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 tools/bin2dump.py diff --git a/tools/bin2dump.py b/tools/bin2dump.py new file mode 100644 index 0000000..2781843 --- /dev/null +++ b/tools/bin2dump.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import with_statement, print_function +import sys +import binascii + +READ_BLOCKSIZE = 16 + +is_py3 = sys.version_info[0] == 3 + + +def main(argv): + if len(argv) < 3: + print('Usage: {0} input_file output_file'.format(argv[0])) + sys.exit(1) + with open(argv[1], 'rb') as file_inp, open(argv[2], 'w') as file_out: + while True: + byte_s = file_inp.read(READ_BLOCKSIZE) + if not byte_s: break + hex_char_repr = binascii.hexlify(byte_s) + hex_char_repr = str(hex_char_repr, encoding='utf-8') if is_py3 else hex_char_repr + file_out.write(hex_char_repr) + file_out.write("\n") + + +if __name__ == '__main__': + main(sys.argv) From f6bef99f36bdc73e103a09741e4aea3bf31e2f97 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Tue, 17 Oct 2023 23:41:37 +0800 Subject: [PATCH 27/33] output square --- shell/square.sh | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 shell/square.sh diff --git a/shell/square.sh b/shell/square.sh new file mode 100644 index 0000000..bccd848 --- /dev/null +++ b/shell/square.sh @@ -0,0 +1,7 @@ +#!/bin/bash +echo -n "please input a number:" +read -r a +b=$((a * 2)) +for ((i = 1; i <= "${a}"; i++)); do + printf "%-${b}s\n" "+" | sed 's/ /+/g' +done From e10ad65c157a7b816c03307c15b37dccf1735fe1 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Wed, 18 Oct 2023 00:10:12 +0800 Subject: [PATCH 28/33] output square --- shell/square2.sh | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 shell/square2.sh diff --git a/shell/square2.sh b/shell/square2.sh new file mode 100644 index 0000000..01b1538 --- /dev/null +++ b/shell/square2.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +echo "input a number" +read -r num + +num2=$(( num * 2 )) +for ((a = 1; a <= "$num"; a++)); do + echo -e "\n" + for ((b = 1; b <= "$num2"; b++)); do + echo -n + + done +done From 4480cffeb7392c9baf93c5a66e5fae0edf97bf1b Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Wed, 18 Oct 2023 00:10:37 +0800 Subject: [PATCH 29/33] output trapezoid --- shell/ trapezoid.sh | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 shell/ trapezoid.sh diff --git a/shell/ trapezoid.sh b/shell/ trapezoid.sh new file mode 100644 index 0000000..ac08ab0 --- /dev/null +++ b/shell/ trapezoid.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +echo -n "please input a number:" +read -r a +for ((i = 1; i <= "$a"; i++)); do + printf "%-${i}s\n" "+" | sed 's/ /+/g' +done From 09dcb261f4601265533764aa79e460cad3f877a5 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Wed, 18 Oct 2023 00:17:46 +0800 Subject: [PATCH 30/33] output trapezoid --- shell/ trapezoid2 | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 shell/ trapezoid2 diff --git a/shell/ trapezoid2 b/shell/ trapezoid2 new file mode 100644 index 0000000..cd0203c --- /dev/null +++ b/shell/ trapezoid2 @@ -0,0 +1,12 @@ +#!/bin/bash + +echo "input a number" +read -r num + +#let num2=num*2 +for ((a = 1; a <= "$num"; a++)); do + for ((b = 1; b <= a; b++)); do + echo -n "+" + done + echo -e "\n" +done From f007f3a2b1d328c0c0861e9c4d05495ca2e9731e Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 19 Oct 2023 20:46:41 +0800 Subject: [PATCH 31/33] add .sh suffix --- shell/ trapezoid2 | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 shell/ trapezoid2 diff --git a/shell/ trapezoid2 b/shell/ trapezoid2 deleted file mode 100644 index cd0203c..0000000 --- a/shell/ trapezoid2 +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -echo "input a number" -read -r num - -#let num2=num*2 -for ((a = 1; a <= "$num"; a++)); do - for ((b = 1; b <= a; b++)); do - echo -n "+" - done - echo -e "\n" -done From 60246315f986ee318e8bf0f288da924bdbb055c2 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 19 Oct 2023 20:47:09 +0800 Subject: [PATCH 32/33] add .sh suffix --- shell/trapezoid2.sh | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 shell/trapezoid2.sh diff --git a/shell/trapezoid2.sh b/shell/trapezoid2.sh new file mode 100644 index 0000000..cd0203c --- /dev/null +++ b/shell/trapezoid2.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +echo "input a number" +read -r num + +#let num2=num*2 +for ((a = 1; a <= "$num"; a++)); do + for ((b = 1; b <= a; b++)); do + echo -n "+" + done + echo -e "\n" +done From 516cb27f32df13503e7fa64c4aea794baa7221c9 Mon Sep 17 00:00:00 2001 From: liming <827182486@qq.com> Date: Thu, 19 Oct 2023 21:02:06 +0800 Subject: [PATCH 33/33] Isosceles trapezoid --- shell/Isosceles_trapezoid.sh | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 shell/Isosceles_trapezoid.sh diff --git a/shell/Isosceles_trapezoid.sh b/shell/Isosceles_trapezoid.sh new file mode 100644 index 0000000..4f9f94e --- /dev/null +++ b/shell/Isosceles_trapezoid.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +echo "please a number" +read -r num + +sum=$((num * 2 + 1)) + +for ((a = 1; a <= num; a++)); do + + for ((b = 1; b <= $(((sum - 2 * a - 1) / 2)); b++)); do + echo -n " " + done + + for ((b = 1; b <= $((2 * a - 1)); b++)); do + echo -n "+" + done + + for ((b = 1; b <= $(((sum - 2 * a - 1) / 2)); b++)); do + echo -n " " + done + + echo -e "\n" +done