欢迎访问宙启技术站
智能推送

使用Python脚本实现SH命令的自定义函数库

发布时间:2024-01-19 20:58:30

要实现SH命令的自定义函数库,可以使用Python的subprocess模块来执行Shell命令,并且可以将这些操作封装成自定义函数。下面是一个实现SH命令自定义函数库的示例,包括常用的文件操作、进程管理和网络操作等函数。

import subprocess

def sh_execute(cmd:str):
    """执行Shell命令并返回输出结果"""
    try:
        output = subprocess.check_output(cmd, shell=True, text=True)
        return output
    except subprocess.CalledProcessError as e:
        return f"Error: {e.cmd} exited with code {e.returncode}"

def sh_copy(src:str, dest:str):
    """复制文件"""
    return sh_execute(f"cp {src} {dest}")

def sh_move(src:str, dest:str):
    """移动文件"""
    return sh_execute(f"mv {src} {dest}")

def sh_remove(file:str):
    """删除文件"""
    return sh_execute(f"rm {file}")

def sh_list_files(directory:str):
    """列出指定目录下的文件列表"""
    return sh_execute(f"ls {directory}")

def sh_create_process(cmd:str):
    """创建一个后台进程并返回进程ID"""
    try:
        subprocess.Popen(cmd, shell=True)
        return "Process created successfully"
    except Exception as e:
        return f"Error: {str(e)}"

def sh_kill_process(pid:int):
    """根据进程ID杀死进程"""
    return sh_execute(f"kill {pid}")

def sh_get_process_list():
    """获取当前运行的进程列表"""
    return sh_execute("ps aux")

def sh_ping(host:str):
    """Ping指定主机,并返回ping结果"""
    return sh_execute(f"ping -c 5 {host}")

# 使用例子
if __name__ == "__main__":
    # 执行Shell命令
    output = sh_execute("ls -l")
    print(output)
    
    # 复制文件
    result = sh_copy("file.txt", "file_copy.txt")
    print(result)
    
    # 创建后台进程
    result = sh_create_process("python script.py")
    print(result)
    
    # 获取进程列表
    output = sh_get_process_list()
    print(output)
    
    # 杀死进程
    result = sh_kill_process(1234)
    print(result)
    
    # Ping主机
    output = sh_ping("127.0.0.1")
    print(output)

以上是一个简单的示例,你可以根据需要自定义更多的函数,并结合subprocess模块提供的方法来实现更多的Shell命令操作。这样你就可以使用自定义的函数库来执行各种Shell命令,而无需直接使用Shell环境。