首先,我们需要下载python和vscode或Trae AI IDE。这里不再演示。我用Trae AI IDE来演示。
打开Trae AI IDE,点击打开文件夹。
然后找一个你心仪的位置,打开文件夹。
然后新建一个文件,叫homemade_cmd.py,再新建一个文件夹,叫bin。
然后再homemade_cmd.py里输入以下代码:
import time
import shutil
import datetime
import subprocess
import ast
import importlib.util
import os
VERSION = '1.1.2'
class SimpleOS:
def __init__(self):
self.current_directory = os.getcwd()
self.command_history = []
self.cmd = None
self.args = None
self.ImportedModuleList = []
def command(self,cmd,args):
if cmd == 'cd' or cmd == 'CD':
self.change_directory(self.args)
elif cmd == 'dir' or cmd == 'DIR':
if args and args[0].lower() == '/s':
self.list_files_recursive(self.current_directory)
else:
self.list_files()
elif cmd == 'color' or cmd == 'COLOR':
self.color_command(args)
elif cmd == 'helpinternet':
if 'Internet' in self.ImportedModuleList:
self.ModuleInternet.show_help()
else:
print("该模块未导入")
elif cmd == 'helpget':
if 'Get' in self.ImportedModuleList:
self.ModuleGet.show_help()
else:
print("该模块未导入")
elif cmd == 'help' or cmd == 'HELP':
self.show_help()
elif cmd == 'history' or cmd == 'HISTORY':
self.show_history()
elif cmd == 'echo' or cmd == 'ECHO':
self.echo_command(args)
elif cmd == 'copy' or cmd == 'COPY':
self.copy_file(args)
elif cmd == 'move' or cmd == 'MOVE':
self.move_file(args)
elif cmd == 'ren' or cmd == 'REN':
self.rename_file(args)
elif cmd == 'del' or cmd == 'DEL':
self.delete_file(args)
elif cmd == 'cls' or cmd == 'CLS' or cmd == 'clear' or cmd == 'CLEAR':
os.system('cls')
elif cmd == 'open' or cmd == 'OPEN':
self.open_command(args)
elif cmd == 'dir/s':
self.list_files_recursive(self.current_directory)
elif cmd == 'ver' or cmd == 'VER':
self.show_ver()
elif cmd == 'tree' or cmd == 'TREE':
self.tree_command(args)
elif cmd == 'more' or cmd == 'MORE':
self.more_command(args)
elif cmd == 'attrib' or cmd == 'ATTRIB':
self.attrib_command(args)
elif cmd == 'calc' or cmd == 'CALC':
self.calc_command(args)
elif cmd == 'mkdir' or cmd == 'MKDIR':
self.mkdir_command(args)
elif cmd == 'mmc' or cmd == 'MMC':
self.mmc_command()
elif cmd == 'timedate.cpl' or cmd == 'TIMEDATE.CPL':
self.timedatecpl_command()
elif cmd == 'title' or cmd == 'TITLE':
self.title_command(args)
elif cmd == 'cmd' or cmd == 'CMD':
self.cmd_command()
elif cmd == 'openbat' or cmd == 'OPENBAT':
self.openbat_command(args)
elif cmd == 'import' or cmd == 'IMPORT':
self.import_command(args)
elif cmd == 'start' or cmd == 'START':
self.start_command(args)
elif cmd == 'print' or cmd == 'PRINT':
self.print_command(args)
elif 'cmd' in self.ImportedModuleList:
self.ModuleInternet.command(cmd, args)
elif 'Get' in self.ImportedModuleList:
self.ModuleGet.command(cmd)
else:
print(f"'{cmd}'不是内部或外部命令,也不是可运行的程序或批处理文件。")
def command_line(self):
"""主命令循环"""
while True:
command = input(f"{self.current_directory}> ").strip()
if not command:
continue
# 添加到历史记录
self.command_history.append(command)
parts = command.split()
self.cmd = parts[0].lower()
self.args = parts[1:]
# 处理命令
if len(self.cmd) < 8191:
if self.cmd == 'exit' or self.cmd == 'EXIT':
break
else:
self.command(self.cmd, self.args)
else:
print("输入行太长")
def print_command(self, args):
if not args:
print("命令语法不正确。")
return
"""打印文本"""
if len(self.cmd) >= 8191:
print("输入行太长")
return
text = args[0]
print(text)
print()
def import_command(self, args):
'''导入外部模块'''
if not args:
print("命令语法不正确。")
return
# 获取bin文件夹下的所有py文件
bin_dir = os.path.join(os.path.dirname(__file__), 'bin')
if not os.path.exists(bin_dir):
"""创建bin文件夹"""
os.makedirs(bin_dir)
return
# 获取bin文件夹下所有py文件的文件名(去掉后缀)
available_modules = [os.path.splitext(f)[0] for f in os.listdir(bin_dir) if f.endswith('.py')]
if args[0] in self.ImportedModuleList:
print("该模块已导入")
return
if args[0] in available_modules:
# 动态导入模块
module_name = args[0]
spec = importlib.util.spec_from_file_location(module_name, os.path.join(bin_dir, module_name + '.py'))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# 将模块添加到已导入模块列表,并设置模块对象
self.ImportedModuleList.append(module_name)
setattr(self, f'Module{module_name}', getattr(module, module_name)())
else:
print("未找到该模块")
def openbat_command(self, args):
if not args:
print("命令语法不正确。")
return
file_extension = os.path.splitext(args[0])[1]
if file_extension == '.bat':
try:
with open(args[0], 'r', encoding='utf-8') as file:
filelines = file.readlines()
for cmd in filelines:
cmd = cmd.strip()
if cmd == '':
continue # 跳过空行
print(f'{os.getcwd()}>{cmd}')
time.sleep(0.1)
parts = cmd.split()
sub_cmd = parts[0].lower()
sub_args = parts[1:]
# 处理命令
if sub_cmd == 'exit':
break
else:
self.command(sub_cmd, sub_args)
time.sleep(0.1) # 每执行完一行命令后等待 0.1 秒
except FileNotFoundError:
print("文件不存在。")
else:
print("文件后缀名一定要是.bat")
print()
def calc_command(self, args):
if not args:
print("命令语法不正确。")
return
"""简单的计算器,支持 +, -, *, /"""
expression = ' '.join(args)
# 只允许数字、基本运算符和括号
allowed_chars = set('0123456789+-*/. ()')
if not all(c in allowed_chars for c in expression):
print("命令语法不正确。")
return
# 使用更安全的literal_eval
result = ast.literal_eval(expression)
print(result)
print()
def mkdir_command(self, args):
if not args:
print("命令语法不正确。")
return
"""创建新的文件夹"""
folder_name = os.path.join(self.current_directory, args[0])
os.makedirs(folder_name, exist_ok=True)
print()
def open_command(self, args):
if not args:
print("命令语法不正确。")
return
"""使用系统默认程序打开文件"""
file_path = os.path.join(self.current_directory, args[0])
os.startfile(file_path) # 自动使用默认程序
print()
def show_history(self):
print("\n命令历史:")
for i, cmd in enumerate(self.command_history[-10:], 1):
print(f"{i}: {cmd}")
print()
def list_files(self):
print(f"\n {self.current_directory} 的目录\n")
self.list_files_recursive(self.current_directory, recursive=False)
print()
def list_files_recursive(self, path, recursive=True):
try:
files = os.listdir(path)
except OSError as e:
print(f"无法访问路径 {path}: {e}")
return
for f in files:
full_path = os.path.join(path, f)
if os.path.isdir(full_path):
if recursive:
print(f"\n {full_path} 的目录\n")
self.list_files_recursive(full_path)
else:
print(f"{os.path.getmtime(full_path):.2f} <DIR> {f}")
else:
try:
size = os.path.getsize(full_path)
mtime = os.path.getmtime(full_path)
mtime_str = time.strftime('%Y/%m/%d %H:%M', time.localtime(mtime))
print(f"{mtime_str} {size:>6} {f}")
except OSError as e:
print(f"无法访问文件 {full_path}: {e}")
print()
def change_directory(self, args):
if not args:
print(f"{self.current_directory}\n")
return
new_path = os.path.abspath(os.path.join(self.current_directory, args[0]))
if os.path.exists(new_path) and os.path.isdir(new_path):
self.current_directory = new_path
print()
def start_command(self, args):
if not args:
print("命令语法不正确。")
return
'''用默认浏览器打开网站'''
url = args[0]
if not url.startswith('http'):
url = 'http://' + url
os.system(f'start {url}')
print()
def copy_file(self, args):
if not args:
print("命令语法不正确。")
return
src = os.path.join(self.current_directory, args[0])
dst = os.path.join(self.current_directory, args[1])
shutil.copy(src, dst)
print()
def move_file(self, args):
if not args:
print("命令语法不正确。")
return
src = os.path.join(self.current_directory, args[0])
dst = os.path.join(self.current_directory, args[1])
shutil.move(src, dst)
print()
def delete_file(self, args):
if not args:
print("命令语法不正确。")
return
path = os.path.join(self.current_directory, args[0])
if os.path.exists(path):
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
print()
def rename_file(self, args):
if not args:
print("命令语法不正确。")
return
src = os.path.join(self.current_directory, args[0])
dst = os.path.join(self.current_directory, args[1])
os.rename(src, dst)
print()
def echo_command(self, args):
if '>' in args or '>>' in args:
redirect_type = '>>' if '>>' in args else '>'
index = args.index(redirect_type)
if index + 1 < len(args):
file_path = os.path.join(self.current_directory, args[index+1])
content = ' '.join(args[:index])
mode = 'a' if redirect_type == '>>' else 'w'
with open(file_path, mode) as f:
f.write(content + '\n')
else:
print(' '.join(args))
print()
def color_command(self, args):
if not args:
print()
return
"""设置控制台文字颜色(黑色背景)"""
color_map = {
'R': '4', # 红
'G': '2', # 绿
'B': '1', # 蓝
'Y': '6', # 黄
'P': '5', # 紫
'C': '3', # 浅绿
'W': '7', # 白
'K': '0', # 黑
'A': 'A', # 淡绿
'E': 'E' # 淡黄
}
letter = args[0].upper()
if letter in color_map:
os.system(f'color 0{color_map[letter]}')
print()
def tree_command(self, args):
if not args:
print("命令语法不正确。")
return
"""以树状图显示目录结构"""
path = self.current_directory
if args and args[0]:
path = os.path.join(self.current_directory, args[0])
print(f"\n{path} 的目录结构\n")
for root, _, files in os.walk(path):
level = root.replace(path, '').count(os.sep)
indent = ' ' * 4 * level
print(f"{indent}{os.path.basename(root)}/")
subindent = ' ' * 4 * (level + 1)
for f in files:
print(f"{subindent}{f}")
print()
def mmc_command(self):
"""打开MMC(Microsoft Management Console)"""
# 如果没有参数,直接打开mmc
subprocess.run(['mmc'], capture_output=True, text=True, check=True, shell=True, creationflags=subprocess.CREATE_NEW_CONSOLE)
print()
def more_command(self, args):
if not args:
print("命令语法不正确。")
return
"""分页显示文件内容"""
file_path = os.path.join(self.current_directory, args[0])
with open(file_path, 'r') as f:
lines = f.readlines()
page_size = os.get_terminal_size().lines - 2
for i in range(0, len(lines), page_size):
print(''.join(lines[i:i+page_size]))
if i + page_size < len(lines):
input("-- 按Enter继续 --")
print()
def attrib_command(self, args):
if not args:
print("命令语法不正确。")
return
"""显示文件属性"""
file_path = os.path.join(self.current_directory, args[0])
stat = os.stat(file_path)
print(f"\n{args[0]} 的属性:")
print(f"大小: {stat.st_size} 字节")
print(f"创建时间: {datetime.datetime.fromtimestamp(stat.st_ctime)}")
print(f"修改时间: {datetime.datetime.fromtimestamp(stat.st_mtime)}")
print(f"访问时间: {datetime.datetime.fromtimestamp(stat.st_atime)}")
print(f"只读: {'是' if not os.access(file_path, os.W_OK) else '否'}")
print()
def show_ver(self):
print(f"\nPhantom Ghost Trails STUDIO GHOST [版本 {VERSION}]\n")
def timedatecpl_command(self):
"""打开日期和时间设置"""
os.startfile('timedate.cpl')
print()
def title_command(self, args):
if not args:
print("命令语法不正确。")
return
"""设置控制台窗口标题"""
title = ' '.join(args)
os.system(f'title {title}')
print()
def cmd_command(self):
print("Phantom Ghost Trails STUDIO GHOST [版本 1.0.2]")
print("(c) Phantom Ghost Trails STUDIO。不保留所有权利。\n")
def show_help(self):
print("支持的命令及使用方法:")
print("color [字母] - 设置文字颜色(黑色背景)")
print(" 可用字母: R=红 G=绿 B=蓝 Y=黄")
print(" P=紫 C=浅绿 W=白 K=黑")
print(" A=淡绿 E=淡黄")
print(" 不带参数则恢复默认颜色")
print("dir - 列出当前目录的内容")
print("dir /s - 递归列出当前目录及其子目录的内容")
print("cd [目录路径] - 切换到指定目录")
print("copy [源文件] [目标文件] - 复制文件到指定位置")
print("move [源文件] [目标路径] - 移动文件到指定位置")
print("ren [旧名> <新名] - 重命名文件或目录")
print("del [文件或目录] - 删除指定文件或目录")
print("history - 显示最近的命令历史")
print("echo [内容] > [文件名+扩展名] - 新建文件并写入文本至文件")
print(" - 使用 > 覆盖写入文件")
print(" - 使用 >> 追加内容到文件")
print("echo > [文件名] - 新建文件")
print("cls或clear -清除控制台信息")
print("open [文件名] - 打开文件")
print("help - 显示本帮助信息")
print("tree [目录] - 以树状图显示目录结构")
print("more [文件名] - 分页显示文件内容")
print("attrib [文件名] - 显示文件属性")
print("calc [表达式] - 简单的计算器,仅支持加减乘除")
print("mkdir [名字] - 创建新的文件夹")
print("mmc - 打开控制台")
print("timedate.cpl - 打开日期和时间设置")
print("title [标题] - 设置控制台窗口标题")
print("cmd -启动 GHOST 命令提示符的一个新实例")
print("openbat [文件名+后缀名] -运行bat文件")
print("import [模块名] -导入外部模块")
print("start [网址名] -用默认浏览器打开网站")
print("exit - 退出cmd")
print("print 输出的内容 -输出内容")
print()
if __name__ == "__main__":
print(f"Phantom Ghost Trails STUDIO GHOST [版本 {VERSION}]")
print("(c) Phantom Ghost Trails STUDIO。不保留所有权利。\n")
title = ' '.join("命令提示符")
os.system(f'title {title}')
os_simulator = SimpleOS()
os_simulator.command_line()
然后在bin文件夹内创建三个文件:Get.py、Internet.py。
Get.py的代码:
import datetime
import time
import psutil
import homemade_cmd
import subprocess
class Get:
def __init__(self):
pass
def command(self, cmd):
if cmd == "date":
self.date_command()
elif cmd == "time":
self.time_command()
elif cmd == "timestamp":
self.timestamp_command()
elif cmd == "tomorrow":
self.tomorrow_date_command()
elif cmd == "yesterday":
self.yesterday_date_command()
elif cmd == "systeminfo":
self.system_info_command()
elif cmd == "cpu_usage":
self.cpu_usage_command()
elif cmd == "memory_usage":
self.memory_usage_command()
elif cmd == 'tasklist' or cmd == 'TASKLIST':
self.tasklist_command()
else:
print(f"'{cmd}'不是内部或外部命令,也不是可运行的程序或批处理文件。")
def date_command(self):
now = time.localtime()
date_str = time.strftime('%Y/%m/%d', now)
weekday_str = time.strftime('%A', now)
weekday_map = {
"Monday": "星期一",
"Tuesday": "星期二",
"Wednesday": "星期三",
"Thursday": "星期四",
"Friday": "星期五",
"Saturday": "星期六",
"Sunday": "星期日"
}
weekday_str = weekday_map.get(weekday_str, weekday_str)
print(f"当前日期: {date_str} {weekday_str}")
print()
def time_command(self):
now = datetime.datetime.now()
time_str = now.strftime('%H:%M:%S.%f')[:-3] # 获取毫秒并截取到小数点后三位
print(f"当前时间: {time_str}")
print()
def timestamp_command(self):
timestamp = time.time()
print(f"当前时间戳: {timestamp}")
print()
def tomorrow_date_command(self):
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
date_str = tomorrow.strftime('%Y/%m/%d')
weekday_str = tomorrow.strftime('%A')
weekday_map = {
"Monday": "星期一",
"Tuesday": "星期二",
"Wednesday": "星期三",
"Thursday": "星期四",
"Friday": "星期五",
"Saturday": "星期六",
"Sunday": "星期日"
}
weekday_str = weekday_map.get(weekday_str, weekday_str)
print(f"明天日期: {date_str} {weekday_str}")
print()
def yesterday_date_command(self):
yesterday = datetime.date.today() - datetime.timedelta(days=1)
date_str = yesterday.strftime('%Y/%m/%d')
weekday_str = yesterday.strftime('%A')
weekday_map = {
"Monday": "星期一",
"Tuesday": "星期二",
"Wednesday": "星期三",
"Thursday": "星期四",
"Friday": "星期五",
"Saturday": "星期六",
"Sunday": "星期日"
}
weekday_str = weekday_map.get(weekday_str, weekday_str)
print(f"昨天日期: {date_str} {weekday_str}")
print()
def cpu_usage_command(self):
cpu_usage = psutil.cpu_percent(interval=1)
print(f"CPU 使用率: {cpu_usage}%")
print()
def memory_usage_command(self):
memory = psutil.virtual_memory()
print("内存使用情况:")
print(f"总内存: {memory.total / (1024 ** 3):.2f} GB")
print(f"可用内存: {memory.available / (1024 ** 3):.2f} GB")
print(f"已用内存: {memory.used / (1024 ** 3):.2f} GB")
print(f"内存使用率: {memory.percent}%")
print()
def system_info_command(self):
"""显示系统信息"""
print("\n操作系统:ghostOS")
print(f"系统版本:{homemade_cmd.VERSION}")
print()
def tasklist_command(self):
"""显示运行中的进程"""
result = subprocess.run(['tasklist'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def show_help(self):
print("date - 获取当前日期")
print("time - 获取当前时间")
print("timestamp - 获取当前时间戳")
print("tomorrow - 获取明天日期")
print("yesterday - 获取昨天日期")
print("systeminfo - 获取系统信息")
print("cpu_usage - 获取CPU使用率")
print("memory_usage - 获取内存使用情况")
print("tasklist - 显示运行中的进程")
Internet.py的代码:
import subprocess
class Internet:
def __init__(self):
pass
def command(self, cmd, args):
if cmd == "ping":
self.ping_command(args)
elif cmd == 'ipconfig' or cmd == 'IPCONFIG':
self.ipconfig_command()
elif cmd == 'tracert' or cmd == 'TRACERT':
self.tracert_command(args)
elif cmd == 'netstat' or cmd == 'NETSTAT':
self.netstat_command(args)
elif cmd == 'nslookup' or cmd == 'NSLOOKUP':
self.nslookup_command(args)
elif cmd == 'arp' or cmd == 'ARP':
self.arp_command()
elif cmd == 'route' or cmd == 'ROUTE':
self.route_command()
elif cmd == 'netsh' or cmd == 'NETSH':
self.netsh_command(args)
elif cmd == 'whois' or cmd == 'WHOIS':
self.whois_command(args)
elif cmd == 'dig' or cmd == 'DIG':
self.dig_command(args)
elif cmd == 'telnet' or cmd == 'TELNET':
self.telnet_command(args)
elif cmd == 'netview' or cmd == 'NETVIEW':
self.netview_command()
elif cmd == 'nbtstat' or cmd == 'NBTSTAT':
self.nbtstat_command()
elif cmd == 'netcat' or cmd == 'NETCAT':
self.netcat_command(args)
elif cmd == 'routeprint' or cmd == 'ROUTEPRINT':
self.routeprint_command()
elif cmd == 'netconn' or cmd == 'NETCONN':
self.netconn_command()
elif cmd == 'nettraffic' or cmd == 'NETTRAFFIC':
self.nettraffic_command()
else:
print(f"'{cmd}'不是内部或外部命令,也不是可运行的程序或批处理文件。")
def ipconfig_command(self):
"""显示网络配置信息"""
result = subprocess.run(['ipconfig'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def ping_command(self, args):
'''ping命令'''
if not args:
print("命令语法不正确。")
return
"""执行ping命令"""
result = subprocess.run(['ping'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def tracert_command(self, args):
'''路由追踪命令'''
if not args:
print("命令语法不正确。")
return
result = subprocess.run(['tracert'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def netstat_command(self, args):
'''网络状态查看'''
default_args = ['-a'] if not args else args
result = subprocess.run(['netstat'] + default_args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def nslookup_command(self, args):
'''DNS查询'''
if not args:
print("命令语法不正确。")
return
result = subprocess.run(['nslookup'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def arp_command(self):
'''显示ARP缓存表'''
result = subprocess.run(['arp', '-a'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def route_command(self):
'''显示路由表'''
result = subprocess.run(['route', 'print'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def netsh_command(self, args):
'''显示网络配置信息'''
if not args:
print("命令语法不正确。")
return
result = subprocess.run(['netsh'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def whois_command(self, args):
'''WHOIS查询'''
if not args:
print("命令语法不正确。")
return
result = subprocess.run(['whois'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def dig_command(self, args):
'''DNS查询工具'''
if not args:
print("命令语法不正确。")
return
result = subprocess.run(['dig'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def telnet_command(self, args):
'''Telnet连接'''
if not args:
print("命令语法不正确。")
return
result = subprocess.run(['telnet'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def netview_command(self):
'''显示网络邻接表'''
result = subprocess.run(['net view'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def nbtstat_command(self):
'''显示NBT名称表解析缓存'''
result = subprocess.run(['nbtstat', '-a'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def netcat_command(self, args):
'''显示网络连接信息'''
if not args:
print("命令语法不正确。")
return
result = subprocess.run(['nc'] + args, capture_output=True, text=True, check=True)
print(result.stdout)
print()
def routeprint_command(self):
'''显示路由表'''
result = subprocess.run(['route', 'print'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def netconn_command(self):
'''显示网络连接信息'''
result = subprocess.run(['netstat', '-an'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def nettraffic_command(self):
'''显示网络流量信息'''
result = subprocess.run(['netsh', 'interface', 'ipv4', 'show', 'traffic'], capture_output=True, text=True, check=True)
print(result.stdout)
print()
def show_help(self):
print("ipconfig - 显示网络配置信息")
print("ping [主机] - 测试网络连接")
print("tracert [目标] - 路由追踪")
print("netstat [选项] - 网络状态查看")
print("nslookup [域名] - DNS查询")
print("arp - 显示ARP缓存表")
print("route - 显示路由表")
print("netsh [命令] - 显示网络配置信息")
print("whois [域名] - WHOIS查询")
print("dig [域名] - DNS查询工具")
print("telnet [主机] [端口] - Telnet连接")
print("netview - 显示网络邻接表")
print("nbtstat - 显示NBT名称表解析缓存")
print("netcat [选项] - 显示网络连接信息")
print("routeprint - 显示路由表")
print("netconn - 显示网络连接信息")
print("nettraffic - 显示网络流量信息")
print()
OK,这就是这个项目的源代码了。再见!