I'm trying to check reverse lookup of IP address and then write the result to txt file. How I can write the result to file using grep ?
My script:
import sys, os, re, shlex, urllib, subprocess
cmd = 'dig -x %s @192.1.1.1' % sys.argv[1]
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
out, err = proc.communicate()
sys.stdout = open("/tmp/test.txt", "w")
print(out)
sys.stdout.close()
Edited after comment To only print out a line containing the string 'PTR'
, first split the output into a list of lines (each line being a str
), then loop over the lines and check if they contain 'PTR'
:
import sys, os, re, shlex, urllib, subprocess
cmd = 'dig -x %s @192.1.1.1' % sys.argv[1]
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
out, err = proc.communicate()
# Convert to list of str lines
out = out.decode().split('\n')
# Only write the line containing "PTR"
with open("/tmp/test.txt", "w") as f:
for line in out:
if "PTR" in line:
f.write(line)
Further explanation of the syntax: The out
object returned from proc.communicate()
is not a str
but a bytes
object. The out.decode()
does the conversion from bytes
to str
. We then split the string up into lines using .split('\\n')
. We can now iterate over these lines using the for loop and ask whether "PTR"
is a substring of any of the lines. If it is, write the corresponding line to the file. Note that if multiple lines contain "PTR"
, they will all be written to the file, without a separating newline.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.