python sh库 快速写运维脚本

sh 是一个非常强大的 Python 库,用来 像写 Shell 一样在 Python 中执行命令。 它让运维自动化脚本既保留 Shell 的直观,又能享受 Python 的逻辑控制。

sh 仅支持类 Unix 系统(Linux/macOS),不支持 Windows。

实时查看执行进度


for line in sh.tail("-f", "/var/log/syslog", _iter=True):
    print(line.strip())
		

传入回调函数

def handler(line):
    print(f"[OUT]: {line.strip()}")

sh.ping("-c", "4", "baidu.com", _out=handler)

管道(Pipe)操作

result = sh.grep(sh.ls("-l"), "py")
print(result)

作者:spike

分类: Python

创作时间:2025-10-22

更新时间:2025-10-23

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1