Python Forum
How to rerun the program in a loop with different input?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to rerun the program in a loop with different input?
#1
Hi All!,

Following is my program, It asks for input, input is looked up in mysqldatabase, if host is found it will do a ssh, I'm new to python, I'm not sure where to begin to make the program take multiple comma separated input like like "172.31.200.1,172.31.200.2" it should execute the program query for each IP, How can this be achieved?

I tried split, it just passes it directly to select query which doesn't help and also throws exception. Help appreciated!

#! python3
import paramiko
import os,sys,time,xlwt
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from conf import ssh_conf as conf_file, MySQL_Connector as mysql
#from conf import MySQL_Connector as mysql
import socket
class Ssh_Util:    
    def __init__(self):
        self.ssh_output = None
        self.ssh_error = None
        self.client = None
        self.host = input("Hostname: ")
##        self.username = mysql.username
##        self.password = mysql.password
        self.timeout = float(conf_file.TIMEOUT)
        self.commands = conf_file.COMMANDS
        self.pkey = conf_file.PKEY
        self.port = conf_file.PORT
        self.wb = xlwt.Workbook()
        self.ws = self.wb.add_sheet("Host1")

        try:
            mycursor = mysql.db.cursor()
            mycursor.execute("select username,password, host from hosts where host = '%s';" % self.host)
            myresult = mycursor.fetchone()
            self.host = myresult[2]
            self.username = myresult[0]
            self.password = myresult[1]
            mycursor.close()
        except TypeError as e:
            print("Host not found!")
            sys.exit()

    def connect(self):
        #"Login to the remote server"
        try:
            #Paramiko.SSHClient can be used to make connections to the remote server and transfer files
            print ("Establishing ssh connection")
            self.client = paramiko.SSHClient()
            #Parsing an instance of the AutoAddPolicy to set_missing_host_key_policy() changes it to allow any host.
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            #Connect to the server
            if (self.password == ''):
                self.pkey = paramiko.RSAKey.from_private_key_file(self.pkey)
                self.client.connect(hostname=self.host, port=self.port, username=self.username,pkey=self.pkey ,timeout=self.timeout, allow_agent=False, look_for_keys=False)
                print ("Connected to the server",self.host)
            else:
                self.client.connect(hostname=self.host, port=self.port,username=self.username,password=self.password,timeout=self.timeout, allow_agent=False, look_for_keys=False)    
                print ("Connected to the server"),self.host
        except paramiko.AuthenticationException:
            print ("Authentication failed, please verify your credentials")
            result_flag = False
        except paramiko.SSHException as sshException:
            print ("Could not establish SSH connection: %s" % sshException)
            result_flag = False
        except socket.timeout as e:
            print ("Connection timed out")
            result_flag = False
        except Exception as e:
            print ('\nException in connecting to the server')
            print ('PYTHON SAYS:',e)
            result_flag = False
            self.client.close()

        else:
            result_flag = True
 
        return result_flag    
 
    def execute_command(self,commands):
        """Execute a command on the remote host.Return a tuple containing
        an integer status and a two strings, the first containing stdout
        and the second containing stderr from the command."""
        self.ssh_output = None
        result_flag = True
        try:
            if self.connect():
                for command in commands:
                    print ("Executing command --> {}".format(command))
                    stdin, stdout, stderr = self.client.exec_command(command,timeout=10)
                    #self.ssh_output = stdout.read()
                    self.ssh_output = stdout.readlines()
                    self.ssh_error = stderr.read()
                    if self.ssh_error:
                        print ("Problem occurred while running command:"+ command + " The error is " + self.ssh_error)
                        result_flag = False
                    else:    
                        print ("Command execution completed successfully")
                        print (''.join(self.ssh_output))
                        self.ws.write(0,0,(self.ssh_output))
                        self.wb.save("writing.xls")
                    self.client.close()
            else:
                print ("Could not establish SSH connection")
                result_flag = False   
        except socket.timeout as e:
            print ("Command timed out.", command)
            self.client.close()
            result_flag = False                
        except paramiko.SSHException:
            print ("Failed to execute the command!",command)
            self.client.close()
            result_flag = False    
 
        return result_flag

if __name__=='__main__':
    print ("\nStart of %s"%__file__)
 
    #Initialize the ssh object
    ssh_obj = Ssh_Util()
 
    #Sample code to execute commands
    if ssh_obj.execute_command(ssh_obj.commands) is True:
        print ("Commands executed successfully\n")
    else:
        print ("Unable to execute the commands")
 
    """
    #Sample code to upload a file to the server
    if ssh_obj.upload_file(ssh_obj.uploadlocalfilepath,ssh_obj.uploadremotefilepath) is True:
        print "File uploaded successfully", ssh_obj.uploadremotefilepath
    else:
        print  "Failed to upload the file"
 
    #Sample code to download a file from the server
    if ssh_obj.download_file(ssh_obj.downloadremotefilepath,ssh_obj.downloadlocalfilepath) is True:
        print "File downloaded successfully", ssh_obj.downloadlocalfilepath
    else:
        print  "Failed to download the file"
    """
Reply
#2
You can use the split() method to divide a string into a list based on the desired separator. Then it's just a simple for loop:

for address in addresses.split(','):
Or you could get the input as a list to start with:

addresses = []
while True:
    address = input('Enter an IP Address, or return to process: ')
    if address:
        addresses.append(address)
    else:
        break
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
This is untested code, but I think it's ok:
ips = "172.31.200.1,172.31.200.2"
ip_list = ips.split(',')
print(ip_list[0])
print(ip_list[1])
# or a better way:
for ip in ip_list:
    print(ip)
I had this sitting on my browser for about 14 minutes, didn't mean to step on Ichabod
Reply
#4
Thanks! I will try this out and revert back here.

I thought the loop had to be added at the bottom to rerun the function from beginning.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  WHILE LOOP NOT RETURNING USER INPUT AFTER ZerroDivisionError! HELP! ayodele_martins1 7 991 Oct-01-2023, 07:36 PM
Last Post: ayodele_martins1
  Code won't break While loop or go back to the input? MrKnd94 2 906 Oct-26-2022, 10:10 AM
Last Post: Larz60+
  Noob here. Random quiz program. Using a while loop function and alot of conditionals. monkeydesu 6 1,319 Sep-07-2022, 02:01 AM
Last Post: kaega2
  [Solved] Trying to rerun a snippet of code paracel 3 1,115 Jul-17-2022, 01:49 PM
Last Post: paracel
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,434 Apr-05-2022, 06:18 AM
Last Post: C0D3R
Exclamation question about input, while loop, then print jamie_01 5 2,616 Sep-30-2021, 12:46 PM
Last Post: Underscore
  I want to check if the input is str or is int & if it's str repeat the loop HLD202 4 2,723 Nov-23-2020, 11:01 PM
Last Post: perfringo
  Loop back through loop based on user input, keeping previous changes loop made? hbkpancakes 2 2,884 Nov-21-2020, 02:35 AM
Last Post: hbkpancakes
  Try-except in while loop: error with closing program Lupin_III 7 2,792 Jul-03-2020, 10:57 AM
Last Post: Lupin_III
  if-loop does not respond to input Kmarstein 1 2,195 Jan-28-2020, 09:29 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020