-4

If i have a text file that contains an x number of lines like:

hostINFO = ['hostTYPE', 'hostOS', 'hostENV', 'hostNAME', 'hostIP', 'dbUNAME', 'dbPWD', 'dbPORT', 'orgNAME', 'nrdsTOKEN']

How would I create a python script that would:

  1. import a line as a variable list so that i can refer to it as hostINFO[0] or hostINFO[1] etc....
  2. execute the script against the variables
  3. when completed go back to the host.txt file and get the next line and continue till no more lined exist.

update....

i changed my hosts.txt file format to be a comma delimited:

hostTYPE,hostOS,hostENV,hostNAME,hostIP,dbUNAME,dbPWD,dbPORT,orgNAME,nrdsTOKEN`

deploy.py

with open("hosts.txt") as f:
for line in f:
    hostINFO = line.strip().split(',')
rainman
  • 1
  • 2

2 Answers2

1

Be aware that evaluating or executing code from files is a serious vulnerability, and you should really be sure that you have control of what's in the file.

You can convert text file content into variables with something like:

with open('myfile.txt') as f:
    for line in f.readline():
        exec(line)
        first_element = hostINFO[0]    # hostTYPE
        second_element = hostINFO[1]   # hostOS
        # ...

See also Why should exec() and eval() be avoided?

Thomas Fauskanger
  • 2,536
  • 1
  • 27
  • 42
0

Why you are not using some regex recipe :

import re
pattern='\w+'

with open('hosts.txt','r') as f:
    for i in f:
        hostINFO=re.findall(pattern,i)
        print(hostINFO)
        print(hostINFO[0])
        print(hostINFO[1])
        #after exec complete it goes for next_line in file

output:

['hostINFO', 'hostTYPE', 'hostOS', 'hostENV', 'hostNAME', 'hostIP', 'dbUNAME', 'dbPWD', 'dbPORT', 'orgNAME', 'nrdsTOKEN']
hostINFO
hostTYPE
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88