0

Is it possible to write every line, I receive from this script, into a mysql table ? I want to have 2 columns: The ip-adress I need for the command (ipAdresse) and a part of the output of the command itself (I want to split some content of the output).. I do not want to ask for any code but I just want to know whether it's even possible to keep this code as it is and add some stuff to it or I have to rewrite it to get the results I want :) Now I just write the output of the command into a text file.

#!/usr/bin/python import subprocess import commands
import subprocess

ipAdresse_4 = 0

datei = open("pointerRecord.txt", "w")

while (ipAdresse_4 < 255):
        ipAdresse_4 = ipAdresse_4 + 1
        ipAdresse = '82.198.205.%d' % (ipAdresse_4,)
        subprocess.Popen("host %s" % ipAdresse, stdout=datei, shell=True)

2 Answers 2

1

here is an example using sqlite3, with minimal changes you can make it work with mysql

import sqlite3
con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()
cur.execute('''CREATE TABLE ipaddr (ip text, val text )''')

from subprocess import Popen, PIPE

for ip in [ '173.194.43.34', '17.172.224.47', '198.252.206.16' ]:
    pipe = Popen('host {}'.format( ip ), shell=True, stdout=PIPE )
    for line in pipe.stdout:
        cur.execute ( "INSERT INTO ipaddr VALUES ('{}','{}')".format( ip, line.strip( ) ))

and you can pull the data out of the table by:

cur.execute( 'SELECT * FROM ipaddr' ).fetchall( )
Sign up to request clarification or add additional context in comments.

Comments

1

you can run following mysql query -

sqlquery = "insert into table values (%s, subprocess.Popen('host %s', stdout=subprocess.PIPE, shell=True).communicate[0])"%(ipAdresse_4, ipAdresse_4)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.