Python script for 'ps aux' command

Question:

I have tried to use subprocess.check_output() for getting the ps aux command using python but it looks like not working with the large grep string.
Can anyone have any solution?

subprocess.check_output('ps aux | grep "bin/scrapy" | grep "option1" | grep "option2" | grep "option3" | grep "option4" | grep "option5"' , shell =True)
Asked By: Manoj Bhatt

||

Answers:

You can use the following code snippet for executing commands on remote host

# create ssh client

ssh = paramiko.SSHClient()

# add host key

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# connect to host

ssh.connect(hostname='somehost', username='someuser', password='somepass')


# Login using RSA key

# ssh.connect(hostname='somehost', username='someuser', key_filename='/home/someuser/.ssh/id_rsa')

# execute command

stdin, stdout, stderr = ssh.exec_command('ps aux')

# print output

for line in stdout:
    print(line)

# close connection

ssh.close()

# Output

# $ python3 test.py
Answered By: codeaprendiz

Yes, I have found the solution to achieve the output, We can use the following code snippet to find the PID as output.

Instead of using ps aux we can use psutil python library.

import psutil

args_list = ["option1", "option2", "option3"]
for process in psutil.process_iter():
    try:
        process_args_list = process.cmdline()
    except psutil._exceptions.NoSuchProcess as err:
        logger.info(f"Found error in psutil, Error: {err}")
        continue
    if all(item in process_args_list for item in args_list):
        print(process.pid)

Answered By: Manoj Bhatt