analitics

Pages

Saturday, April 20, 2024

Python 3.12.1 : Using the subprocess python module - part 001.

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
See the official webpage for Python verison 3.12.3 same like version 3.12.1 I used.
Let's see two examples with this python module:
First script will get output of net users command and will parse all into a list:
import subprocess

def find_users():
    try:
        result = subprocess.run(["net", "users"], capture_output=True, text=True)
        users = result.stdout.splitlines()      
        # define list content         
        user_list = []
        for line in users[4:-2]:  # inser only some rows 
            #print(line) #only users        
            user = line.split()
            user_list += user
        # print the right result
        print(user_list)
    except Exception as e:
        print(f"Error : {str(e)}")

# run find_users
find_users()
The result is this:
python test_001.py
['Administrator', 'catafest', 'DefaultAccount', 'Guest', 'WDAGUtilityAccount']
This source code will show data from tasklist and will print result of this ... :
import subprocess

def find_processes():
    try:
        result = subprocess.run(['tasklist', '/v'], capture_output=True, text=True)
        output_lines = result.stdout.splitlines()

        for line in output_lines[3:]:
            columns = line.split()
            #print(columns)
            #if len(columns) >= 8 and columns[9] == 'N/A':
            if len(columns) >= 8 and columns[0] == 'tasklist.exe':
                print(line)
    except Exception as e:
        print(f"A apărut o eroare la găsirea proceselor suspendate: {str(e)}")

find_processes()
The result will be like this:
python test_pid_003.py
tasklist.exe 8348 Console 1 10,304 K Unknown DESKTOP-mycomputer 0:00:00 N/A