Python Forum

Full Version: Need help with for loop and variable value substitution in a function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear Sirs,

Good Day

Need help with the below code. Thanks in advance

Need a for loop here to run the below code on each of the IP Address provided in a file by a name file1 which has a list of IP Addresses separated by a new line. Instead of the IP address "10.137.111.31" mentioned below a variable needs to be put which substitutes its value (IP address) during each and every iteration of the for loop where in its value i.e. IP Address changes as stated in the file name file1 separated by a new line.


#!/usr/bin/python2

import pexpect

# Need a for loop here to run the below code on each of the IP Address provided in a file by a name file1 which has a list of IP Addresses separated by a new line. Instead of the IP address "10.137.111.31" mentioned below a variable needs to be put which substitutes its value (IP address) during each and every iteration of the for loop where in its value i.e. IP Address changes as stated in the file name file1 separated by a new line.
   
#Open connection and login. maintain the session output in /tmp/out
child = pexpect.spawn('ssh [email protected]')
child.logfile = open("/tmp/out", "a")
child.expect('password:')
child.sendline('Password1')

#Wait for prompt and run command
child.expect(".*\$ ")
child.sendline('hostname')

#Wait for prompt and run command
child.expect(".*\$ ")
child.sendline('uname -a')

#Wait for prompt and run command
child.expect(".*\$ ")
child.sendline('date')

#Logout
child.expect('e025711.*')
child.sendline('exit')
(Jul-21-2020, 05:30 AM)Yoriz Wrote: [ -> ]File tutorials
https://python-forum.io/Thread-Basic-Files
https://docs.python.org/3/tutorial/input...ting-files
for loop tutorials
https://python-forum.io/Thread-for-loops
https://docs.python.org/3/tutorial/contr...statements

I already checked these documents, but it didn't help much on my specific requirement. I am new to Python. I was able to do it with shell scripting, but couldn't find a way around in python.

shell script:

Output:
for i in `cat filename` #here around cat filename i inserted a special symbol that is on the tilde key sitting next to number 1 on the keyboard, it just doesn't get visible here. do ssh -l user@$i done ## Filename contains the list of IP Addresses separated by newline