Python,Shell:如何提取数据并存储在iterable变量中(特别是在list中)?

2024-09-29 23:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做我自己的项目。其中必须执行以下步骤:

  1. 连接到远程服务器。你知道吗
  2. 获取pid、进程名、cpu使用率、交换内存使用率,这些数据是在远程服务器上的每个进程每天的某个特定时间(比如4点钟)运行的。你知道吗
  3. 我必须将每天的结果与前一天的结果进行比较(例如,day1 pid与day2 pid、day1进程名称与day2进程名称等)

到目前为止,我已经完成了第二步。现在我想知道如何从远程服务器中提取pid、进程名、cpu使用率、交换内存使用率,并将其存储在某个iterable变量中。这样我就可以比较它来检查记忆尖峰? 除了我的想法之外,任何其他的方法都是值得赞赏的。 我的代码示例如下:

import paramiko
import re
import psutil
class ShellHandler:
    def __init__(self, host, user, psw):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(host, username=user, password=psw, port=22)

        channel = self.ssh.invoke_shell()
        self.stdin = channel.makefile('wb')
        self.stdout = channel.makefile('r')

    def __del__(self):
        self.ssh.close()

    @staticmethod
    def _print_exec_out(cmd, out_buf, err_buf, exit_status):
        print('command executed: {}'.format(cmd))
        print('STDOUT:')
        for line in out_buf:
            print(line, end="")
        print('end of STDOUT')
        print('STDERR:')
        for line in err_buf:
            print(line, end="")
        print('end of STDERR')
        print('finished with exit status: {}'.format(exit_status))
        print('------------------------------------')
        #print(psutil.pids())

        pass

    def execute(self, cmd):
        """

        :param cmd: the command to be executed on the remote computer
        :examples:  execute('ls')
                execute('finger')
                execute('cd folder_name')
        """
        cmd = cmd.strip('\n')
        self.stdin.write(cmd + '\n')
        finish = 'end of stdOUT buffer. finished with exit status'
        echo_cmd = 'echo {} $?'.format(finish)
        self.stdin.write(echo_cmd + '\n')
        shin = self.stdin
        self.stdin.flush()

        shout = []
        sherr = []
        exit_status = 0
        for line in self.stdout:
            if str(line).startswith(cmd) or str(line).startswith(echo_cmd):
                # up for now filled with shell junk from stdin
                shout = []
            elif str(line).startswith(finish):
                # our finish command ends with the exit status
                exit_status = int(str(line).rsplit(maxsplit=1)[1])
                if exit_status:
                    # stderr is combined with stdout.
                    # thus, swap sherr with shout in a case of failure.
                    sherr = shout
                    shout = []
                break
            else:
                # get rid of 'coloring and formatting' special characters
                shout.append(re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]').sub('', line).replace('\b', '').replace('\r', ''))

        # first and last lines of shout/sherr contain a prompt
        if shout and echo_cmd in shout[-1]:
            shout.pop()
        if shout and cmd in shout[0]:
            shout.pop(0)
        if sherr and echo_cmd in sherr[-1]:
            sherr.pop()
        if sherr and cmd in sherr[0]:
            sherr.pop(0)

        self._print_exec_out(cmd=cmd, out_buf=shout, err_buf=sherr, exit_status=exit_status)
        return shin, shout, sherr

obj=ShellHandler('Servername','username','password')
pID=[]
## I want this(pid, cmd, swap memory) to store in a varible which would be iterable.
pID=ShellHandler.execute(obj,"ps -eo pid,cmd,lstart,%mem,%cpu|awk '{print $1}'")
print(pID[0])##---------------------------------Problem not giving any output.

Tags: ofinechoselfcmdstatuswithstdin
2条回答

ps aux命令应该包含您需要的所有信息(pid、进程名、cpu、内存)

您的ShellHandlerexecute方法返回三项,第一项是您发送给它的输入。你知道吗

无论如何,你应该直接这样称呼它:

obj = ShellHandler('Servername','username','password')
in, out, err = obj.execute("ps -eo pid,lstart,%mem,%cpu,cmd")
for line in out.split('\n'):
    pid, lstartwd, lstartmo, lstartdd, lstartm, lstartyy, mem, cpu, cmd = line.split(None, 8)

我最后移动了cmd,因为它可能包含空格。lstart值还包含多个空格分隔的字段。Debian的输出如下:

19626 Tue Jan 15 15:03:57 2019  0.0  0.0 less filename

关于如何更详细地解析ps输出有许多问题;我将向您介绍如何准确地处理来自split的结果。你知道吗

相关问题 更多 >

    热门问题