1

I have a script part that looks like this:

if ( pstree -s $$ | grep -q 'sshd' ); then
    SOME_VAR=foo
else
    SOME_VAR=boo
fi

I need to do the same thing in python. Is there a way that I can get bool output from the command inside if()? Maybe using the exit code or smth, so the code looks something like this:

if os.system("pstree -s $$ | grep -q 'sshd'"):
  os.environ['SOME_VAR']='foo'
else:
  os.environ['SOME_VAR']='boo'

I tried to use subprocess library like this:

args = shlex.split("pstree -s $$ | grep -q 'sshd'")
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
o, e = p.communicate()

print('Output: ' + o.decode('ascii'))
print('Error: ' + e.decode('ascii'))
print('code: ' + str(p.returncode))

but it says Error: pstree: invalid option -- 'q'

dsmoly
  • 11
  • 1
  • Have you tried the code you posted? The `os.system` version works fine for me. – Woodford Sep 15 '21 at 16:10
  • @Woodford in my case it sets boo, but It should set it "foo" – dsmoly Sep 15 '21 at 16:22
  • `grep -q` exits with `0` for success (pattern found) and `256` for failure (pattern not found). Check your result by grep-ing for a process name that should _not_ be found (e.g. `grep -q 'notsshd`) – Woodford Sep 15 '21 at 16:25
  • To be clear, `shlex.split()` doesn't make pipelines work. To use a pipeline without `shell=True`, you need a separate `subprocess.Popen` object for each side of the pipe. – Charles Duffy Sep 15 '21 at 16:32

1 Answers1

2

You could do it this way with psutil:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import psutil

def has_sshd():
    "Return True if process sshd exist."
    for p in psutil.process_iter(['name']):
        if p.info['name'] == 'sshd':
            return True
    return False

if has_sshd():
    os.environ['SOME_VAR']='foo'
else:
    os.environ['SOME_VAR']='boo'
Léa Gris
  • 17,497
  • 4
  • 32
  • 41