analitics

Pages

Showing posts with label subprocess. Show all posts
Showing posts with label subprocess. Show all posts

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

Monday, October 7, 2019

Python 3.7.4 : Example with subprocess - part 001.

This is a simple example with the python 3 subprocess package.
The source code is simple to understand.
The execute_proceess_with_communicate let run the ls command with the sudo user permissions:
import os
import sys
import string
import subprocess
import codecs

inp = ''
cmd = 'ls'
password = ''

def execute_proceess_with_communicate(inp):
    """Return a list of hops from traceroute command."""
    p = subprocess.Popen(
            ['sudo', cmd, inp],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            shell=False)
    text, _ = p.communicate(password)
    #print(type(text))
    outp = codecs.decode(text,'utf8')
    out_split=outp.split('\n')
    return out_split

def normalize_out(list_outp):
    """Extract information from traceroute line per line."""

    normalized_out = []
    for op in list_outp:
        # filer out if an empty line
        if len(op) is 0:
            continue
        op_split = op.split()
        normalized_out.append(op_split)
    return normalized_out

if __name__ == '__main__':
    inp = sys.argv[1]

    out = execute_proceess_with_communicate(inp)
    n_out = normalize_out(out)
    print(n_out)
The result is this:
[mythcat@desk scripts]$ python3 subprocess_001.py '/' 
[['bin'], ['boot'], ['dev'], ['etc'], ['home'], ['lib'], ['lib64'], ['media'], ['mnt'], ['opt'], ['proc'],
 ['root'], ['run'], ['sbin'], ['srv'], ['sys'], ['tmp'], ['usr'], ['var']]

Friday, September 1, 2017

The beauty of Python: subprocess module - part 004 .

This series of python tutorials that we started at the beginning of this blog and called "The beauty of Python" is part of the series of tutorials aimed at the simplicity and beauty of the Python programming language.
The main goal for us is how to use this programming language in everyday life with different tasks.
Today I will come up with examples to cover this goal and show you how to use the subprocess python module.
  • using the PowerShell with python :
  • >>> import subprocess
    >>> process=subprocess.Popen(["powershell","Get-Childitem C:\\Windows\\*.log"],stdout=subprocess.PIPE);
    >>> result=process.communicate()[0]
    >>> print result
  • get and print the hostname :
  • >>> print subprocess.check_output("hostname")
  • print the output of ping command :
  • >>> print subprocess.check_output("ping localhost", shell=True)
  • print the output of dir command :
  • >>> cmd = 'dir *'
    >>> supcmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    >>> print supcmd.communicate()[0]
    
  • run the python script like python shell :
  • >>> import sys
    >>> import subprocess
    >>> pid = subprocess.Popen([sys.executable, "calc.py"])

Sunday, September 22, 2013

Check system , distro and commands using python scripts .

This is a simple example with two functions.

First will check the linux command : ls linux command.

The next function will give us some infos about system.

import shlex 
import subprocess
from subprocess import Popen, PIPE

import platform

def check_command(command):
    cmd='which ' + command 
    output = Popen(shlex.split(cmd), stdout=PIPE).communicate()[0]
    command_path =output.split('\n')[0]
    print command_path
    return command_path

def check_platform():
    arch, exe = platform.architecture()
    my_system = platform.system()
    if my_system == 'Linux':
        distro_name, distro_version, distro_id = platform.linux_distribution()
    elif my_system == 'Darwin':
        distro_name, distro_version, distro_id = platform.mac_ver()
    elif my_system == 'Windows':
 distro_name, distro_version, distro_id = platform.win32_ver()
    elif my_system == 'Java':
 distro_name, distro_version, distro_id = platform.java_ver()
    processor = platform.processor() or 'i386'
    print processor, my_system, arch, distro_name, distro_version, distro_id
    return processor, my_system, arch, distro_name, distro_version, distro_id

check_command('ls')

check_platform()

This python script can be use with any scripts when we need to test commands and system , distro version.

Saturday, May 22, 2010

The beauty of Python: subprocess module - part 3

This is just a simple example about module subprocess.
We need to install "espeak" . On fedora usse this command:
#yum install espeak

Now the example is:

>>> import subprocess   
>>> subprocess.call(["espeak", "-s 120","-p 100","This is a test"])
0
>>>   

This will speak "This is a test".
This is all .