pyutilscripts 0.1.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ """
2
+ PyUtilScripts 是一个基于 Python 的通用小工具集合,目标是提供编写通用任务的辅助工具。
3
+ """
4
+
5
+ __version__ = "0.1.0"
6
+ __status__ = "beta1"
7
+ __author__ = "zero <zero.kwok@foxmail.com>"
8
+
9
+ projectName = 'PyUtilScripts'
10
+ projectHome = 'https://github.com/ZeroKwok/pyutilscripts.git'
11
+ projectVersion = f'{__version__} {__status__}'.strip()
12
+ projectAuthor = __author__
pyutilscripts/fcopy.py ADDED
@@ -0,0 +1,116 @@
1
+ #! python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # This file is part of the PyUtilScripts project.
5
+ # Copyright (c) 2020-2025 zero <zero.kwok@foxmail.com>
6
+ #
7
+ # For the full copyright and license information, please view the LICENSE
8
+ # file that was distributed with this source code.
9
+ #
10
+ # ###
11
+ #
12
+ # 1. 以tree -aif命令输出的内容作为文件清单(如下).
13
+ # 2. 通过脚本将(directory)原目录下的匹配文件, 拷贝到(output)目标目录.
14
+ #
15
+ # 语法如下
16
+ # fcopy.py [-l,--list FILE] [-d,--directory DIRECTORY] <-o,--output DIRECTORY>
17
+ #
18
+ # CMD
19
+ # python fcopy.py -l ../fcopy.list -d . -o "\\192.168.1.230\2024-01-26 1625"
20
+
21
+ import os
22
+ import shlex
23
+ import sys
24
+ import stat
25
+ import shutil
26
+ import filecmp
27
+ import argparse
28
+ import traceback
29
+ from termcolor import cprint
30
+
31
+ def copy_files(source_directory, target_directory, manifest, report:dict):
32
+ for file in manifest:
33
+ source = os.path.normpath(os.path.join(source_directory, file))
34
+ target = os.path.normpath(os.path.join(target_directory, file))
35
+
36
+ try:
37
+ fs = os.stat(source)
38
+ if fs.st_mode & stat.S_IFDIR:
39
+ continue
40
+ except FileNotFoundError:
41
+ cprint(f'Failed: SourceFileNotFound -> {source}', 'red', file=sys.stderr)
42
+ report[0].setdefault('SourceFileNotFound', []).append(source)
43
+ continue
44
+
45
+ if os.path.exists(target):
46
+ if filecmp.cmp(source, target):
47
+ print(f'Skip: SameFile -> {source} -> {target}')
48
+ report[1].setdefault('SkipSameFile', []).append(source)
49
+ continue
50
+ else:
51
+ print(f'Update: {source} -> {target}')
52
+ report[1].setdefault('Update', []).append(source)
53
+ else:
54
+ print(f'Copy: {source} -> {target}')
55
+ report[1].setdefault('Copy', []).append(source)
56
+ os.makedirs(os.path.dirname(target), exist_ok=True)
57
+ shutil.copy2(source, target)
58
+
59
+ def read_file_list(file_path):
60
+ with open(file_path, 'r') as file:
61
+ return [line.strip() for line in file.readlines() if not line[0].isdigit()]
62
+
63
+ def main(sequence = None):
64
+ try:
65
+ parser = argparse.ArgumentParser(description='Copy files from source directory to target directory.')
66
+ parser.add_argument('-l', '--list', default='fcopy.list', help='File containing the list of files to copy.')
67
+ parser.add_argument('-d', '--directory', default='.', help='Source directory where the files are located.')
68
+ parser.add_argument('-o', '--output', required=True, help='Target directory where the files will be copied.')
69
+ parser.add_argument('-v', '--verbose', action='store_true', default=False)
70
+
71
+ while True:
72
+ try:
73
+ args = parser.parse_args(shlex.split(sequence, posix=False) if sequence else None)
74
+ break
75
+ except SystemExit:
76
+ sequence = input('$ Please enter parameters:\n')
77
+ continue
78
+
79
+ for key in args.__dict__:
80
+ if type(args.__dict__[key]) == str:
81
+ args.__dict__[key] = args.__dict__[key].strip(' \'"')
82
+
83
+ if not args.list or not args.directory or not args.output:
84
+ print("Error: Please provide the required arguments.")
85
+ parser.print_help()
86
+ return
87
+
88
+ report = { 0 : {}, 1 : {} }
89
+ manifest = read_file_list(args.list)
90
+ copy_files(args.directory, args.output, manifest, report)
91
+
92
+ failed = {}
93
+ success = {}
94
+ for key in report[0]:
95
+ failed[key] = failed.setdefault(key, 0) + len(report[0][key])
96
+ for key in report[1]:
97
+ success[key] = success.setdefault(key, 0) + len(report[1][key])
98
+ failed = [f'{i}: {failed[i]}' for i in failed]
99
+ success = [f'{i}: {success[i]}' for i in success]
100
+
101
+ print()
102
+ if args.verbose:
103
+ print()
104
+ for key in report[0]:
105
+ for f in report[0][key]:
106
+ cprint(f'{key}: {f}', 'red')
107
+ if 'Update' in report[1]:
108
+ for f in report[1]['Update']:
109
+ cprint(f'{key}: {f}', 'green')
110
+ cprint(f'{", ".join(success)} {", ".join(failed)}', 'yellow' if failed else 'green')
111
+ except:
112
+ traceback.print_exc()
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
@@ -0,0 +1,91 @@
1
+ #! python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # This file is part of the PyUtilScripts project.
5
+ # Copyright (c) 2020-2025 zero <zero.kwok@foxmail.com>
6
+ #
7
+ # For the full copyright and license information, please view the LICENSE
8
+ # file that was distributed with this source code.
9
+
10
+ import sys
11
+ import time
12
+ import socket
13
+ import argparse
14
+ import threading
15
+
16
+ listen_host = "0.0.0.0"
17
+ listen_port = 8081
18
+
19
+ target_host = "127.0.0.1"
20
+ target_port = 1081
21
+
22
+ verbose = False
23
+
24
+ def log(message):
25
+ """Log messages if verbose mode is enabled."""
26
+ if verbose:
27
+ print(message)
28
+
29
+ def run():
30
+ threading.Thread(target=server, daemon=True).start()
31
+ try:
32
+ print(f"Press [Ctrl + C] to exit ...")
33
+ while True:
34
+ time.sleep(1)
35
+ except KeyboardInterrupt:
36
+ print(f"KeyboardInterrupt: Aborting ...")
37
+
38
+ def server(*settings):
39
+ try:
40
+ dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
41
+ dock_socket.bind((listen_host, listen_port)) # listen
42
+ dock_socket.listen(5)
43
+ log("*** listening on %s:%i" % ( listen_host, listen_port ))
44
+ while True:
45
+ client_socket, client_address = dock_socket.accept()
46
+
47
+ log("*** from %s:%i to %s:%i" % ( client_address, listen_port, target_host, target_port ))
48
+ server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
49
+ server_socket.connect((target_host, target_port))
50
+ threading.Thread(target=forward, args=(client_socket, server_socket, f"client -> server, {client_address}" ), daemon=True).start()
51
+ threading.Thread(target=forward, args=(server_socket, client_socket, f"server -> client, {client_address}" ), daemon=True).start()
52
+ finally:
53
+ dock_socket.close()
54
+ time.sleep(1)
55
+ threading.Thread(target=server, daemon=True).start()
56
+
57
+ def forward(source, destination, description):
58
+ data = ' '
59
+ try:
60
+ while data:
61
+ data = source.recv(4096)
62
+ log(f"*** {description}, data length: {len(data)}")
63
+ if data:
64
+ destination.sendall(data)
65
+ else:
66
+ source.shutdown(socket.SHUT_RD)
67
+ destination.shutdown(socket.SHUT_WR)
68
+ except socket.error as e:
69
+ print(f"*** {description} {e.strerror}")
70
+ source.shutdown(socket.SHUT_RD)
71
+ destination.shutdown(socket.SHUT_WR)
72
+
73
+ def main():
74
+ parser = argparse.ArgumentParser(description='Forward TCP traffic from source to destination')
75
+ parser.add_argument('--src', '-s', required=True, type=str, help='The source IP address and port to listen on (e.g. 0.0.0.0:8081)')
76
+ parser.add_argument('--dst', '-d', required=True, type=str, help='The destination IP address and port to forward traffic to (e.g. 127.0.0.1:1081)')
77
+ parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output')
78
+
79
+ args = parser.parse_args()
80
+
81
+ # 解析后的参数
82
+ listen_host = args.src.split(':')[0]
83
+ listen_port = int(args.src.split(':')[1])
84
+ target_host = args.dst.split(':')[0]
85
+ target_port = int(args.dst.split(':')[1])
86
+ verbose = args.verbose
87
+
88
+ run()
89
+
90
+ if __name__ == '__main__':
91
+ main()
@@ -0,0 +1,55 @@
1
+ #! python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # This file is part of the PyUtilScripts project.
5
+ # Copyright (c) 2020-2025 zero <zero.kwok@foxmail.com>
6
+ #
7
+ # For the full copyright and license information, please view the LICENSE
8
+ # file that was distributed with this source code.
9
+
10
+ # 删除空目录
11
+ # 注意: -rl递归列出要删除的空目录时, 结果可能比实际的少
12
+ # 因为可能出现子文件夹是空目录, 删除后父目录也可以删除的情况.
13
+
14
+ import os
15
+ import sys
16
+ import argparse
17
+
18
+ def DoRemoveEmpty(directory:str, args):
19
+ for f in os.listdir(directory):
20
+ t = os.path.join(directory, f)
21
+ if not os.path.isdir(t):
22
+ continue
23
+
24
+ # 若是目录则先递归一次
25
+ if args.recursion:
26
+ DoRemoveEmpty(t, args)
27
+
28
+ # 再看是否为空目录
29
+ if len(os.listdir(t)) == 0:
30
+ if args.list:
31
+ print(f'To be removed: {t}')
32
+ else:
33
+ print(f'Removed: {t}')
34
+ os.rmdir(t)
35
+ args.count = args.count + 1
36
+ continue
37
+
38
+ def main():
39
+ parser = argparse.ArgumentParser()
40
+ parser.add_argument('-l', '--list', action='store_true', help='it is listed but not deleted')
41
+ parser.add_argument('-d', '--directory', type=str, default=os.getcwd(), help='specifies the directory on which to perform this operation')
42
+ parser.add_argument('-r', '--recursion', action='store_true', help='recursive file directory')
43
+ args = parser.parse_args()
44
+
45
+ if not args.list:
46
+ opt = input('Do you want to remove an empty directory (Yes/No)?')
47
+ if opt.lower() != 'yes':
48
+ exit(0)
49
+
50
+ args.count = 0
51
+ DoRemoveEmpty(args.directory, args)
52
+ print(f'Total: {args.count}')
53
+
54
+ if __name__ == "__main__":
55
+ main()
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyutilscripts
3
+ Version: 0.1.0b1
4
+ Summary: PyUtilScripts 是一个基于 Python 的通用小工具集合,目标是提供编写通用任务的辅助工具。
5
+ Author-email: Zero Kwok <zero.kwok@foxmail.com>
6
+ License: MIT License
7
+ Project-URL: Homepage, https://github.com/ZeroKwok/pyutilscripts
8
+ Project-URL: Issues, https://github.com/ZeroKwok/pyutilscripts/issues
9
+ Keywords: tools
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Topic :: Software Development :: Build Tools
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.7
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Requires-Python: >=3.7
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: termcolor
24
+ Dynamic: license-file
25
+
26
+ # **PyUtilScripts**
27
+
28
+ `PyUtilScripts` 是一个基于 Python 的通用小工具集合,目标是提供编写通用任务的辅助工具。
29
+
30
+ ## **📜 脚本列表**
31
+
32
+ | 脚本名称 | 功能描述 | 示例用法 |
33
+ |----------|---------|---------|
34
+ | [`fcopy.py`](fcopy.py) | 基于清单文件的复制工具 | `fcopy -l list.txt -s src_dir -d dest_dir` |
35
+ | [`forward-tcp.py`](forward-tcp.py) | TCP 端口转发工具 | `forward-tcp -s 0.0.0.0:8081 -d 127.0.0.1:1081` |
36
+ | [`prunedirs.py`](prunedirs.py) | 递归删除空目录 | `prunedirs /path/to/dir` |
37
+
38
+ ---
39
+
40
+ ## **⚙️ 安装与使用**
41
+
42
+ ### **1. 克隆仓库**
43
+
44
+ ```bash
45
+ git clone https://github.com/ZeroKwok/PyUtilScripts.git
46
+ cd PyUtilScripts
47
+ ```
48
+
49
+ ### **2. 直接运行(无需安装)**
50
+
51
+ 所有脚本均可直接执行:
52
+
53
+ ```bash
54
+ python3 script_name.py [args]
55
+ ```
@@ -0,0 +1,10 @@
1
+ pyutilscripts/__init__.py,sha256=inZvg58mvLd_5b4udszD3CEwCq3IOC6-MHDIIFsC7a0,406
2
+ pyutilscripts/fcopy.py,sha256=mbzBZKoFdAoQ6jpmmcctjMfO1atzYaGA-y6MZBp2vFs,4433
3
+ pyutilscripts/forward_tcp.py,sha256=ZI05AQ_hFFzuI8OigUD8MFBmdHgXPO63Qvtz36jr9KI,3263
4
+ pyutilscripts/prunedirs.py,sha256=Wza7MfH6mqbC-VHHo_j7D1Svfpr7tx-QTTFluiob1wU,1830
5
+ pyutilscripts-0.1.0b1.dist-info/licenses/LICENSE,sha256=qocFQjIOOjK3GfixkWhfONEEq5327ac3rYPx8FLebPE,1111
6
+ pyutilscripts-0.1.0b1.dist-info/METADATA,sha256=8jEKh0TKGf2dqRSrEQiq5QNGEzucVNbOezDSYSflDxg,1928
7
+ pyutilscripts-0.1.0b1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
+ pyutilscripts-0.1.0b1.dist-info/entry_points.txt,sha256=dHqHBHWojx-bkLpecsxkUZxh8pfAVvKVYIO2Xwh83Ao,137
9
+ pyutilscripts-0.1.0b1.dist-info/top_level.txt,sha256=q1zRSvdJafzyewHd1b57EhgwB4_EzoMtMyOEMZzOKKs,14
10
+ pyutilscripts-0.1.0b1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ fcopy = pyutilscripts.fcopy:main
3
+ forward.tcp = pyutilscripts.forward_tcp:main
4
+ prunedirs = pyutilscripts.prunedirs:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2025 Zero <zero.kwok@foxmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pyutilscripts