1stenjoydmoment
1stenjoydmoment

Reputation: 249

How to check shell commands are used in a file in Python

I want to check whether any shell command like sed, awk, scp, ssh and etc., is used in a shell script or not. these commands will be used in shell script in many possible ways.

For Ex: cat run.sh

#/usr/bin/sh
echo "This is test file"
#hello world
#sed -i king
`sed -i hello` . -- use of backtics
x=$(sed -e king) . -- surrounded with $()
echo "Hello" 
echo "cat"|sed -i /s/test/use/g .  -- pipe without space
echo "cat"| sed -i /s/test/use/g .  -- pipe with space

below is my snippet which is working for basic functionality.

commands = ["scp", "sed", "awk"]
with open("run.sh", "r") as f:
            lines = f.readlines()
        for line in lines[:]:
            if line.strip().startswith('#'):
                continue
            print(line.split())
            for cmd in commands:
                if cmd in line.split():
                    print(line.split())
                    print("comamnd found and its available in file"

can someone pls suggest/advise how to handle this case in Python3?

Upvotes: 0

Views: 81

Answers (1)

GiovaniSalazar
GiovaniSalazar

Reputation: 2094

Here an example using subprocess with command shell:

import subprocess

file='run.sh'
# Your command that you want
cmd='grep -w "sed" '+ file
process = subprocess.Popen(cmd,shell=True,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result=process.stdout.readlines()
#How many time found sed
print(cmd+' found: '+str(len(result)))
# Output grep command
if len(result) >= 1:
    for line in result:
        print(line.decode("utf-8"))

The result is like a you are using command shell directly in your console with how many time found it

Upvotes: 1

Related Questions