格式化 Python Fabric 输出

问题描述

我正在尝试编写一个脚本来通过主机列表 ssh 并测试某个进程是否正在运行,然后为每个主机打印出该进程是否正在运行。下面是一个例子:

from fabric.api import *
import getpass

env.user = user'
env.password = getpass.getpass(prompt='Password: ',stream=None)
env.hosts = ['localhost']


def uptime():
    run("uptime")


def getinfo():
    hostname = run("hostname")
    run("ps aux | grep -i apache") 

这里的问题是有多个名为 apache 的进程,因此它输出一个巨大的列表,而不是在它遍历服务器列表时只说“Apache 正在主机 1 上运行”的效果。我如何使用 python 以这种方式格式化输出,或者在 Linux 中将其作为实际 shell 命令的一部分(ps aux | grep -i apache)?

解决方法

我想通了。问题是错误地打开文件,这实际上是有效的。

from fabric.api import *
import getpass

env.user = 'user'
env.password = getpass.getpass(prompt='Password: ',stream=None)
env.hosts = ['localhost']

def uptime():
    run("uptime")

def hostname():
    run("hostname")

def getinfo():
    hostname = run("hostname")
    f = open("output.txt","a")
    with hide('output'):
        var1 = run("ps aux | grep -i steam")
    if var1:
        print("Steam is running on " + hostname,file=f)
    elif var1:
        print("Steam is not running on " + hostname,file=f)
    
    f = open("output.txt","a")
    with hide('output'):
        var1 = run("ps aux | grep -i pidgin")
    if var1:
        print("Pidgin is running on " + hostname,file=f)
    elif var1:
        print("Pidgin is not running on " + hostname,"a")
    with hide('output'):
        var1 = run("ps aux | grep -i firefox")
    if var1:
        print("Firefox is running on " + hostname,file=f)
    elif var1:
        print("Firefox is not running on " + hostname,file=f)
    f.close()