Python Forum
How to rerun the program in a loop with different input? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to rerun the program in a loop with different input? (/thread-14221.html)



How to rerun the program in a loop with different input? - bharaths - Nov-20-2018

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"
    """



RE: How to rerun the program in a loop with different input? - ichabod801 - Nov-20-2018

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



RE: How to rerun the program in a loop with different input? - Larz60+ - Nov-20-2018

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


RE: How to rerun the program in a loop with different input? - bharaths - Nov-23-2018

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.