如何用脚本模拟系统命令

wen 实用脚本 2

本文目录导读:

如何用脚本模拟系统命令

  1. Python 模拟系统命令
  2. Shell脚本模拟(Bash)
  3. 使用方法

我可以为您提供几种模拟系统命令的方法,包括Python和Shell脚本实现:

Python 模拟系统命令

基础命令模拟器

import os
import subprocess
import shlex
import sys
class CommandSimulator:
    def __init__(self):
        self.current_dir = os.getcwd()
        self.commands = {
            'ls': self.list_files,
            'cd': self.change_directory,
            'pwd': self.print_working_directory,
            'cat': self.cat_file,
            'echo': self.echo_text,
            'mkdir': self.make_directory,
            'rm': self.remove_file,
            'cp': self.copy_file,
            'mv': self.move_file,
            'touch': self.touch_file,
            'help': self.show_help,
            'exit': self.exit_shell
        }
    def list_files(self, args):
        """模拟ls命令"""
        path = args[0] if args else self.current_dir
        try:
            files = os.listdir(path)
            for f in files:
                if os.path.isdir(os.path.join(path, f)):
                    print(f"{f}/")
                else:
                    print(f)
        except Exception as e:
            print(f"ls: {e}")
    def change_directory(self, args):
        """模拟cd命令"""
        if not args:
            path = os.path.expanduser("~")
        else:
            path = args[0]
        try:
            os.chdir(path)
            self.current_dir = os.getcwd()
        except Exception as e:
            print(f"cd: {e}")
    def print_working_directory(self, args):
        """模拟pwd命令"""
        print(self.current_dir)
    def cat_file(self, args):
        """模拟cat命令"""
        if not args:
            print("cat: no file specified")
            return
        for filename in args:
            try:
                with open(filename, 'r') as f:
                    print(f.read())
            except Exception as e:
                print(f"cat: {e}")
    def echo_text(self, args):
        """模拟echo命令"""
        text = ' '.join(args)
        print(text)
    def make_directory(self, args):
        """模拟mkdir命令"""
        if not args:
            print("mkdir: missing operand")
            return
        for dirname in args:
            try:
                os.mkdir(dirname)
                print(f"Created directory: {dirname}")
            except Exception as e:
                print(f"mkdir: {e}")
    def remove_file(self, args):
        """模拟rm命令"""
        if not args:
            print("rm: missing operand")
            return
        for filename in args:
            try:
                os.remove(filename)
                print(f"Removed file: {filename}")
            except Exception as e:
                print(f"rm: {e}")
    def copy_file(self, args):
        """模拟cp命令"""
        if len(args) < 2:
            print("cp: missing file operand")
            return
        import shutil
        src, dst = args[0], args[1]
        try:
            shutil.copy2(src, dst)
            print(f"Copied {src} to {dst}")
        except Exception as e:
            print(f"cp: {e}")
    def move_file(self, args):
        """模拟mv命令"""
        if len(args) < 2:
            print("mv: missing file operand")
            return
        import shutil
        src, dst = args[0], args[1]
        try:
            shutil.move(src, dst)
            print(f"Moved {src} to {dst}")
        except Exception as e:
            print(f"mv: {e}")
    def touch_file(self, args):
        """模拟touch命令"""
        if not args:
            print("touch: missing file operand")
            return
        for filename in args:
            try:
                with open(filename, 'a'):
                    os.utime(filename, None)
                print(f"Touched file: {filename}")
            except Exception as e:
                print(f"touch: {e}")
    def show_help(self, args):
        """显示帮助信息"""
        print("可用命令:")
        for cmd in self.commands:
            print(f"  {cmd}")
    def exit_shell(self, args):
        """退出模拟器"""
        print("Goodbye!")
        sys.exit(0)
    def run(self):
        """主循环"""
        print("欢迎使用命令模拟器 (输入 'help' 查看命令)")
        while True:
            prompt = f"simulator:{self.current_dir}> "
            user_input = input(prompt)
            if not user_input.strip():
                continue
            # 解析命令
            parts = shlex.split(user_input)
            cmd = parts[0]
            args = parts[1:] if len(parts) > 1 else []
            # 执行命令
            if cmd in self.commands:
                self.commands[cmd](args)
            else:
                print(f"未知命令: {cmd} (输入 'help' 查看可用命令)")
# 使用示例
if __name__ == "__main__":
    simulator = CommandSimulator()
    simulator.run()

高级命令模拟器(带管道和重定向)

import os
import sys
import shlex
import subprocess
from typing import List, Dict, Callable
class AdvancedCommandSimulator:
    """高级命令模拟器,支持管道和重定向"""
    def __init__(self):
        self.environment = {}
        self.current_dir = os.getcwd()
        self.commands = {
            'ls': self.cmd_ls,
            'cd': self.cmd_cd,
            'pwd': self.cmd_pwd,
            'cat': self.cmd_cat,
            'echo': self.cmd_echo,
            'mkdir': self.cmd_mkdir,
            'rm': self.cmd_rm,
            'cp': self.cmd_cp,
            'mv': self.cmd_mv,
            'grep': self.cmd_grep,
            'sort': self.cmd_sort,
            'wc': self.cmd_wc,
            'head': self.cmd_head,
            'tail': self.cmd_tail,
            'help': self.cmd_help,
            'exit': self.cmd_exit,
        }
    def parse_command(self, cmd_str):
        """解析命令,支持管道和重定向"""
        # 处理管道
        if '|' in cmd_str:
            return self.execute_pipeline(cmd_str)
        # 处理重定向
        if '>' in cmd_str or '<' in cmd_str:
            return self.execute_redirect(cmd_str)
        # 普通命令
        parts = shlex.split(cmd_str)
        if not parts:
            return None
        cmd = parts[0]
        args = parts[1:]
        if cmd in self.commands:
            return self.commands[cmd](args)
        else:
            print(f"未找到命令: {cmd}")
            return None
    def execute_pipeline(self, cmd_str):
        """执行管道命令"""
        commands = cmd_str.split('|')
        processes = []
        for i, cmd_part in enumerate(commands):
            cmd_list = shlex.split(cmd_part.strip())
            if not cmd_list:
                continue
            cmd = cmd_list[0]
            args = cmd_list[1:]
            if i == 0:
                p1 = subprocess.Popen(cmd_list, stdout=subprocess.PIPE)
                processes.append(p1)
            elif i == len(commands) - 1:
                p2 = subprocess.Popen(cmd_list, stdin=processes[-1].stdout)
                processes.append(p2)
            else:
                p2 = subprocess.Popen(cmd_list, stdin=processes[-1].stdout, stdout=subprocess.PIPE)
                processes.append(p2)
            if i > 0:
                processes[-2].stdout.close()
        # 等待所有进程完成
        for p in processes:
            p.wait()
    def execute_redirect(self, cmd_str):
        """执行重定向命令"""
        # 简单重定向处理
        parts = shlex.split(cmd_str)
        if '>' in parts:
            idx = parts.index('>')
            cmd_parts = parts[:idx]
            output_file = parts[idx+1:]
            cmd = cmd_parts[0]
            args = cmd_parts[1:]
            # 保存stdout
            orig_stdout = sys.stdout
            with open(' '.join(output_file), 'w') as f:
                sys.stdout = f
                if cmd in self.commands:
                    self.commands[cmd](args)
                sys.stdout = orig_stdout
        else:
            # 普通执行
            parts = shlex.split(cmd_str)
            cmd = parts[0]
            args = parts[1:]
            if cmd in self.commands:
                self.commands[cmd](args)
    def cmd_ls(self, args):
        """模拟ls命令"""
        path = args[0] if args else self.current_dir
        files = os.listdir(path)
        for f in sorted(files):
            print(f)
    def cmd_cd(self, args):
        """模拟cd命令"""
        try:
            os.chdir(' '.join(args))
            self.current_dir = os.getcwd()
        except Exception as e:
            print(f"cd: {e}")
    def cmd_pwd(self, args):
        """模拟pwd命令"""
        print(self.current_dir)
    def cmd_cat(self, args):
        """模拟cat命令"""
        for file in args:
            try:
                with open(file, 'r') as f:
                    print(f.read())
            except Exception as e:
                print(f"cat: {e}")
    def cmd_echo(self, args):
        """模拟echo命令"""
        print(' '.join(args))
    def cmd_mkdir(self, args):
        """模拟mkdir命令"""
        for dirname in args:
            try:
                os.mkdir(dirname)
            except Exception as e:
                print(f"mkdir: {e}")
    def cmd_rm(self, args):
        """模拟rm命令"""
        for file in args:
            try:
                os.remove(file)
            except Exception as e:
                print(f"rm: {e}")
    def cmd_cp(self, args):
        """模拟cp命令"""
        import shutil
        if len(args) == 2:
            try:
                shutil.copy2(args[0], args[1])
            except Exception as e:
                print(f"cp: {e}")
    def cmd_mv(self, args):
        """模拟mv命令"""
        import shutil
        if len(args) == 2:
            try:
                shutil.move(args[0], args[1])
            except Exception as e:
                print(f"mv: {e}")
    def cmd_grep(self, args):
        """模拟grep命令"""
        pattern = args[0] if args else ""
        files = args[1:] if len(args) > 1 else []
        if not files:
            # 从stdin读取
            for line in sys.stdin:
                if pattern in line:
                    print(line, end='')
        else:
            for file in files:
                try:
                    with open(file, 'r') as f:
                        for line_num, line in enumerate(f, 1):
                            if pattern in line:
                                print(f"{file}:{line_num}:{line}", end='')
                except Exception as e:
                    print(f"grep: {e}")
    def cmd_sort(self, args):
        """模拟sort命令"""
        lines = []
        if args:
            for file in args:
                try:
                    with open(file, 'r') as f:
                        lines.extend(f.readlines())
                except:
                    pass
        else:
            for line in sys.stdin:
                lines.append(line)
        for line in sorted(lines):
            print(line, end='')
    def cmd_wc(self, args):
        """模拟wc命令"""
        if args:
            total_lines = 0
            total_words = 0
            total_chars = 0
            for file in args:
                try:
                    with open(file, 'r') as f:
                        content = f.read()
                        lines = content.count('\n')
                        words = len(content.split())
                        chars = len(content)
                        print(f"{lines:8d} {words:8d} {chars:8d} {file}")
                        total_lines += lines
                        total_words += words
                        total_chars += chars
                except:
                    pass
            if len(args) > 1:
                print(f"{total_lines:8d} {total_words:8d} {total_chars:8d} total")
        else:
            content = sys.stdin.read()
            print(f"{content.count(chr(10)):8d} {len(content.split()):8d} {len(content):8d}")
    def cmd_head(self, args):
        """模拟head命令"""
        lines_num = 10
        files = []
        for arg in args:
            if arg.isdigit():
                lines_num = int(arg)
            else:
                files.append(arg)
        for file in files:
            try:
                with open(file, 'r') as f:
                    for _ in range(lines_num):
                        line = f.readline()
                        if not line:
                            break
                        print(line, end='')
            except Exception as e:
                print(f"head: {e}")
    def cmd_tail(self, args):
        """模拟tail命令"""
        lines_num = 10
        files = []
        for arg in args:
            if arg.isdigit():
                lines_num = int(arg)
            else:
                files.append(arg)
        for file in files:
            try:
                with open(file, 'r') as f:
                    lines = f.readlines()
                    for line in lines[-lines_num:]:
                        print(line, end='')
            except Exception as e:
                print(f"tail: {e}")
    def cmd_help(self, args):
        """帮助命令"""
        print("可用命令:")
        for cmd in sorted(self.commands.keys()):
            print(f"  {cmd}")
    def cmd_exit(self, args):
        """退出命令"""
        sys.exit(0)
    def run(self):
        """运行模拟器"""
        print("高级命令模拟器 (输入 'help' 查看命令)")
        while True:
            try:
                prompt = f"simulator:{self.current_dir}> "
                user_input = input(prompt)
                if not user_input.strip():
                    continue
                self.parse_command(user_input)
            except KeyboardInterrupt:
                print("\n使用 'exit' 退出")
            except Exception as e:
                print(f"错误: {e}")
# 使用示例
if __name__ == "__main__":
    simulator = AdvancedCommandSimulator()
    simulator.run()

Shell脚本模拟(Bash)

#!/bin/bash
# 简单的Linux命令模拟器
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# 显示帮助
show_help() {
    echo -e "${BLUE}可用命令:${NC}"
    echo "  ls, cd, pwd, cat, echo, mkdir, rm"
    echo "  cp, mv, grep, sort, head, tail"
    echo "  help, exit"
}
# 模拟ls命令
sim_ls() {
    local path="${1:-.}"
    echo -e "${GREEN}目录 $path 的内容:${NC}"
    ls -la "$path" 2>/dev/null || echo -e "${RED}无法访问: $path${NC}"
}
# 模拟cd命令
sim_cd() {
    local path="$1"
    if [ -d "$path" ]; then
        cd "$path"
        echo -e "${GREEN}当前目录: $(pwd)${NC}"
    else
        echo -e "${RED}目录不存在: $path${NC}"
    fi
}
# 模拟cat命令
sim_cat() {
    for file in "$@"; do
        if [ -f "$file" ]; then
            echo -e "${YELLOW}=== $file ===${NC}"
            cat "$file"
        else
            echo -e "${RED}文件不存在: $file${NC}"
        fi
    done
}
# 模拟echo命令
sim_echo() {
    echo "$*"
}
# 模拟mkdir命令
sim_mkdir() {
    for dir in "$@"; do
        mkdir -p "$dir" && echo -e "${GREEN}创建目录: $dir${NC}" || echo -e "${RED}创建失败: $dir${NC}"
    done
}
# 主循环
main() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}      Linux命令模拟器 v1.0${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo -e "输入 'help' 查看所有可用命令"
    echo ""
    while true; do
        echo -en "${GREEN}$(basename $(pwd)):${YELLOW}$(basename $HOME)${NC}> "
        read -r input
        # 解析输入
        IFS=' ' read -r -a args <<< "$input"
        cmd="${args[0]}"
        params=("${args[@]:1}")
        case "$cmd" in
            "ls") sim_ls "${params[0]}" ;;
            "cd") sim_cd "${params[0]}" ;;
            "pwd") pwd ;;
            "cat") sim_cat "${params[@]}" ;;
            "echo") sim_echo "${params[@]}" ;;
            "mkdir") sim_mkdir "${params[@]}" ;;
            "rm") rm -r "${params[@]}" 2>/dev/null || echo -e "${RED}删除失败${NC}" ;;
            "cp") cp "${params[@]}" 2>/dev/null || echo -e "${RED}复制失败${NC}" ;;
            "mv") mv "${params[@]}" 2>/dev/null || echo -e "${RED}移动失败${NC}" ;;
            "grep") grep "${params[@]}" ;;
            "sort") sort "${params[@]}" ;;
            "head") head "${params[@]}" ;;
            "tail") tail "${params[@]}" ;;
            "help") show_help ;;
            "exit"|"quit") echo -e "${BLUE}再见!${NC}"; exit 0 ;;
            "") continue ;;
            *) echo -e "${RED}未知命令: $cmd ${NC}" ;;
        esac
    done
}
# 运行主函数
main

使用方法

运行Python模拟器:

python3 command_simulator.py

运行Shell模拟器:

chmod +x command_simulator.sh
./command_simulator.sh

这些脚本模拟了基本的Linux命令功能,可以根据需要进行扩展和修改,它们适合学习、测试或在一个安全环境中模拟系统命令。

抱歉,评论功能暂时关闭!