Python Forum
Grep command and variable in a script - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Networking (https://python-forum.io/forum-12.html)
+--- Thread: Grep command and variable in a script (/thread-15902.html)



Grep command and variable in a script - searching1 - Feb-06-2019

Hi, I'm creating a script wherein I want to grep all a specific address based on the list?

before what I usually do run a grep 1 by 1 using this command ex. grep "192.168.1.1" *

Now I'm creating a script.

Example of the output.
print(i) output.
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3

but how to call the list and put into loop under os.system so I can grep all the list?

import ipaddress
import os
    
#Ask the ipaddress in CIDR format
ip = input("Enter the IP/CIDR: ")

os.chdir("/rs/configs")
print("pwd=%s" % os.getcwd())

for i in ipaddress.IPv4Network(ip):
    print (i)
    os.system("grep" +i+ "*") #Grep from list and run to all directory *
Thanks


RE: Grep command and variable in a script - marienbad - Feb-21-2019

set addr equal to the ip you want to grep:

import subprocess

cmd = "grep " + addr

returned_value = subprocess.check_output(cmd)

print('returned value:', returned_value)