def __init__(self, client, **kwargs): if 'timeout' not in kwargs or kwargs['timeout'] is None: kwargs['timeout'] = 60 if 'newline' not in kwargs or kwargs['newline'] is None: kwargs['newline'] = '\r' if 'buffer_size' not in kwargs or kwargs['buffer_size'] is None: kwargs['buffer_size'] = 1024 if 'display' not in kwargs or kwargs['display'] is None: kwargs['display'] = False if 'conn_type' not in kwargs or kwargs['conn_type'] is None: self.conn_type = '' else: self.conn_type = kwargs['conn_type'] SSHClientInteraction.__init__(self, client, kwargs['timeout'], kwargs['newline'], kwargs['buffer_size'], kwargs['display'])
def __init__(self, logfile, instance, namespace, location, remote_conn_details): super(ConnectMUMPS, self).__init__() self.type = str.lower(instance) self.namespace = str.upper(namespace) self.prompt = self.namespace + '>' # Create a new SSH client object client = paramiko.SSHClient() # Set SSH key parameters to auto accept unknown hosts client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to the host client.connect(hostname=remote_conn_details.remote_address, port=remote_conn_details.remote_port, username=remote_conn_details.username, password=remote_conn_details.password) # Create a client interaction class which will interact with the host from paramikoe import SSHClientInteraction interact = SSHClientInteraction(client, timeout=10, display=False) self.connection = interact self.connection.logfile_read = file(logfile, 'w') self.client = client # apparently there is a deconstructor which disconnects (probably sends a FYN packet) when client is gone
def py_ssh(ip_add, u_name, p_word, com): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip_add, username=u_name, password=p_word) interact = SSHClientInteraction(ssh, timeout=10, display=True) for i in com: interact.send(com) interact.expect('*:~$') conData = interact.current_output_clean return conData
def main(): # Set login credentials and the server prompt hostname = 'localhost' username = '******' password = '******' prompt = 'fots@fotsies-ubuntu-testlab:~\$ ' # Use SSH client to login try: # Create a new SSH client object client = paramiko.SSHClient() # Set SSH key parameters to auto accept unknown hosts client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to the host client.connect(hostname=hostname, username=username, password=password) # Create a client interaction class which will interact with the host interact = SSHClientInteraction(client, timeout=10, display=False) interact.expect(prompt) # Send the tail command interact.send('tail -f /var/log/auth.log') # Now let the class tail the file for us interact.tail(line_prefix=hostname + ': ') except KeyboardInterrupt: print 'Ctrl+C interruption detected, stopping tail' except Exception: traceback.print_exc() finally: try: client.close() except: pass
def main(): # Set login credentials and the server prompt hostname = 'localhost' username = '******' password = '******' prompt = 'fots@fotsies-ubuntu-testlab:~\$ ' # Use SSH client to login try: # Create a new SSH client object client = paramiko.SSHClient() # Set SSH key parameters to auto accept unknown hosts client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to the host client.connect(hostname=hostname, username=username, password=password) # Create a client interaction class which will interact with the host interact = SSHClientInteraction(client, timeout=10, display=False) interact.expect(prompt) # Send the tail command interact.send('tail -f /var/log/auth.log') # Now let the class tail the file for us interact.tail(line_prefix=hostname+': ') except KeyboardInterrupt: print 'Ctrl+C interruption detected, stopping tail' except Exception: traceback.print_exc() finally: try: client.close() except: pass
def main(): # Set login credentials and the server prompt hostname = 'localhost' username = '******' password = '******' prompt = 'fots@fotsies-ubuntu-testlab:~\$ ' # Use SSH client to login try: # Create a new SSH client object client = paramiko.SSHClient() # Set SSH key parameters to auto accept unknown hosts client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to the host client.connect(hostname=hostname, username=username, password=password) # Create a client interaction class which will interact with the host interact = SSHClientInteraction(client, timeout=10, display=True) interact.expect(prompt) # Run the first command and capture the cleaned output, if you want # the output without cleaning, simply grab current_output instead. interact.send('uname -a') interact.expect(prompt) cmd_output_uname = interact.current_output_clean # Now let's do the same for the ls command but also set a timeout for # this specific expect (overriding the default timeout) interact.send('ls -l /') interact.expect(prompt, timeout=5) cmd_output_ls = interact.current_output_clean # To expect multiple expressions, just use a list. You can also # selectively take action based on what was matched. # Method 1: You may use the last_match property to find out what was # matched interact.send('~/paramikoe-demo-helper.py') interact.expect([prompt, 'Please enter your name: ']) if interact.last_match == 'Please enter your name: ': interact.send('Fotis Gimian') interact.expect(prompt) # Method 2: You may use the matched index to determine the last match # (like pexpect) interact.send('~/paramikoe-demo-helper.py') found_index = interact.expect([prompt, 'Please enter your name: ']) if found_index == 1: interact.send('Fotis Gimian') interact.expect(prompt) # Send the exit command and expect EOF (a closed session) interact.send('exit') interact.expect() # Print the output of each command print '-'*79 print 'Cleaned Command Output' print '-'*79 print 'uname -a output:' print cmd_output_uname print 'ls -l / output:' print cmd_output_ls except Exception: traceback.print_exc() finally: try: client.close() except: pass
def workon(host, username, password, scp_url, scp_pass): cmd1 = 'sshpass -p ' + scp_pass.rstrip() + ' scp -v -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ' \ + scp_url.rstrip() + ' /bootflash/' cmd2 = 'setup-bootvars.sh ' + scp_url[scp_url.rfind("/") + 1:].rstrip() + ' ' cmd3 = 'setup-clean-config.sh ; vsh -c "reload"' ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) host = host.rstrip() username = username.rstrip() password = password.rstrip() print '******** HOST IP ' + host + " ********" + '\n' try: ssh.connect(hostname=host, username=username, password=password) interact = SSHClientInteraction(ssh, timeout=50, display=True) try: interact.send(cmd1) interact.expect('.*Exit status 0.*', timeout=20) interact.current_output_clean except: print "\n" + host + " image did not download correctly. Please check scp information and try again." ssh.close() return try: interact.send(cmd2) interact.expect('.*Done.*') interact.current_output_clean except: print "\n" + host + " A issue arose while trying to set the boot variables. Please verify the switch is" \ " supported under this script" ssh.close() return try: interact.send(cmd3) interact.expect('Done') interact.current_output_clean except: print "\n" + host + " Something went wrong while trying to reload the switch. " \ "Please check the switch or reload manually" ssh.close() return except paramiko.AuthenticationException: print host + " is unable to authenticate with the credentials provided. Please double check them and try again." ssh.close() print '*' * 40 print '*' * 40
def main(): # Set login credentials and the server prompt hostname = 'localhost' username = '******' password = '******' prompt = 'fots@fotsies-ubuntu-testlab:~\$ ' # Use SSH client to login try: # Create a new SSH client object client = paramiko.SSHClient() # Set SSH key parameters to auto accept unknown hosts client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to the host client.connect(hostname=hostname, username=username, password=password) # Create a client interaction class which will interact with the host interact = SSHClientInteraction(client, timeout=10, display=True) interact.expect(prompt) # Run the first command and capture the cleaned output, if you want # the output without cleaning, simply grab current_output instead. interact.send('uname -a') interact.expect(prompt) cmd_output_uname = interact.current_output_clean # Now let's do the same for the ls command interact.send('ls -l /') interact.expect(prompt) cmd_output_ls = interact.current_output_clean # To expect multiple expressions, just use a list. You can also # selectively take action based on what was matched. # Method 1: You may use the last_match property to find out what was # matched interact.send('~/paramikoe-demo-helper.py') interact.expect([prompt, 'Please enter your name: ']) if interact.last_match == 'Please enter your name: ': interact.send('Fotis Gimian') interact.expect(prompt) # Method 2: You may use the matched index to determine the last match # (like pexpect) interact.send('~/paramikoe-demo-helper.py') found_index = interact.expect([prompt, 'Please enter your name: ']) if found_index == 1: interact.send('Fotis Gimian') interact.expect(prompt) # Send the exit command and expect EOF (a closed session) interact.send('exit') interact.expect() # Print the output of each command print '-'*79 print 'Cleaned Command Output' print '-'*79 print 'uname -a output:' print cmd_output_uname print 'ls -l / output:' print cmd_output_ls except Exception: traceback.print_exc() finally: try: client.close() except: pass
def main(): # Setup a command parset to handle user input parser = argparse.ArgumentParser(description="pylogin a python script " "with expect prompt handling and " "behavior similar to rancid\'s clogin") parser.add_argument("-c", dest="command", type=str, help="Command to " "be run on each router list on the command-line." " Multiple commands maybe listed by separating " "them with semi-colons (;)") parser.add_argument("-p", dest="password", type=str, help="Password to be " "used for the device. The script will prompt if not " "given one.") parser.add_argument("-prompt", dest="prompt", type=str, default=".*(>|#|%) ?", help="Prompt that pylogin should expect for a new " "line, defaults to Cisco IOS like.") parser.add_argument("-pagerprompt", dest="pagerprompt", type=str, default=".*((--More-- )|(---\(more ?\d?\d?%?\)---))", help="Prompt given by pager if " "enabled, defaults to Cisco IOS like.") parser.add_argument("-enablepassprompt", dest="enablepassprompt", type=str, default=".*password: "******"Password prompt given by " " the device when the enable command is sent. The " "default is cisco ios compatible.") parser.add_argument("-enablepass", dest="enablepass", type=str, help="Enable password, defaults to the same as " "password.") parser.add_argument("-t", dest="timeout", type=int, default=10, help="Time pylogin should allow to connect to the " "device.") parser.add_argument("-u", dest="username", type=str, default=getpass.getuser() , help="Username to be " "used for the device, defaults to current user.") parser.add_argument("-x", dest="commandFile", type=str, help="Specifies" " a file with commands to run on each device. They" "must not expect additional input. This option " "overrides -c") parser.add_argument("-r", dest="routerFile", type=str, help="Specifies a" " file with a list of routers to apply the commands " "against. This option overrides the router argument.") parser.add_argument("router", metavar="router", type=str, nargs=argparse.REMAINDER, help="One or my routers to " "connect to.") args = parser.parse_args() # Prompt for pass if one wasn't given. if not args.password: password = getpass.getpass() else: password = args.password # Check to see if we were given an enable pass and if so set the enable # password, if none specified default to same as password. if args.enablepass: enablePassword = args.enablepass else: enablePassword = password # Check to see if the routers were specified with a file or directly # through the cli. Then create the router list. if args.routerFile: routerFileObj = open(args.routerFile) routerList = routerFileObj.read().splitlines() routerFileObj.close() else: routerList = args.router # Counter to determine which router we are working with. routerId = 0 # Build the prompt list expectPrompt = [args.prompt, args.pagerprompt, args.enablepassprompt] # Use SSH client to login try: # Lets figure out what commands to Run if args.commandFile: # Commands were in a file specified with -x, open the file and read # all the lines. commandFileObj = open(args.commandFile) commandsToRun = commandFileObj.read().splitlines() commandFileObj.close() else: # Commands specified with -c option separated by ';' commandsToRun = args.command.split(";") while routerId < len(routerList): # Create a new SSH client object client = paramiko.SSHClient() # Set SSH key parameters to auto accept unknown hosts client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Connect to the host. client.connect(hostname=routerList[routerId], username=args.username, password=password) except: # Connecting to this router has failed we need to advance to # the next router and restart the loop. print ("Failed to connect to " + routerList[routerId] + ", " + "skipping.\n") routerId += 1 continue # Create a client interaction class which will interact with # the host. interact = SSHClientInteraction(client, timeout=args.timeout, display=True) # Counter to track which command we are running. commandId = 0 while commandId <= len(commandsToRun): # Watch the ssh session until we need to do something interact.expect(expectPrompt) if interact.last_match == args.prompt: #Our last command sent was successful, or we have our first # prompt now we check to see if we need to run another. if commandId < len(commandsToRun): # We need to send a command interact.send(commandsToRun[commandId]) # Advance the command counter commandId += 1 elif interact.last_match == args.pagerprompt: # We received a pager prompt and need to handle it interact.send(" ") elif interact.last_match == args.enablepassprompt: # Then enable command was sent and we need to send a # password. interact.send(enablePassword) # Send the exit command and expect EOF (a closed session) # This may need to be changed to support more devices interact.send('exit') interact.expect() # Advance to next router routerId += 1 except Exception: traceback.print_exc() finally: try: client.close() except: pass
def main(): # Set login credentials and the server prompt hostname = "localhost" username = "******" password = "******" prompt = "fots@fotsies-ubuntu-testlab:~\$ " # Use SSH client to login try: # Create a new SSH client object client = paramiko.SSHClient() # Set SSH key parameters to auto accept unknown hosts client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect to the host client.connect(hostname=hostname, username=username, password=password) # Create a client interaction class which will interact with the host interact = SSHClientInteraction(client, timeout=10, display=True) interact.expect(prompt) # Run the first command and capture the cleaned output, if you want the output # without cleaning, simply grab current_output instead. interact.send("uname -a") interact.expect(prompt) cmd_output_uname = interact.current_output_clean # Now let's do the same for the ls command interact.send("ls -l /") interact.expect(prompt) cmd_output_ls = interact.current_output_clean # To expect multiple expressions, just use a list. You can also selectively # take action based on what was matched. # Method 1: You may use the last_match property to find out what was matched interact.send("~/paramikoe-demo-helper.py") interact.expect([prompt, "Please enter your name: "]) if interact.last_match == "Please enter your name: ": interact.send("Fotis Gimian") interact.expect(prompt) # Method 2: You may use the matched index to determine the last match (like pexpect) interact.send("~/paramikoe-demo-helper.py") found_index = interact.expect([prompt, "Please enter your name: "]) if found_index == 1: interact.send("Fotis Gimian") interact.expect(prompt) # Send the exit command and expect EOF (a closed session) interact.send("exit") interact.expect() # Print the output of each command print "-" * 79 print "Cleaned Command Output" print "-" * 79 print "uname -a output:" print cmd_output_uname print "ls -l / output:" print cmd_output_ls except Exception as e: traceback.print_exc() finally: try: client.close() except: pass
def __init__(self, user, password, host, enablepass, timeout=60, display=False): """Constructor for NetDOer class. Arguments: user - user to connect with password - password to connect to device with host - host device to connect to. timeout - timeout for connection The constructed object will already be in privleged mode after the object is initialized if the devie is IOSlike. """ try: #Create paramiko session to device, it must be attached to object #so it isn't closed. self.SSHclient = paramiko.SSHClient() self.SSHclient.load_system_host_keys() self.SSHclient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.SSHclient.connect(hostname=host, username=user, password=password) self.SSHinteraction = SSHClientInteraction(self.SSHclient, timeout=timeout, display=display) self.DeviceType = False while True: self.SSHinteraction.expect(firstexpectvalues) #We saw JUNOS after login so the device is juniper if self.SSHinteraction.last_match == JUNOS_MATCH: self.DeviceType = "junos" #We need to see if we have the cli or shell junosshellre = re.compile(JUNOS_SHELL) match = junosshellre.search( self.SSHinteraction.current_output) junospromptre = re.compile(PROMPT) promptmatch = junospromptre.search( self.SSHinteraction.current_output) if match: #we have the shell need the CLI self.SSHinteraction.send("cli") elif promptmatch: #we have a prompt and are good to go. break #We have a prompt and no device type yet. elif (self.SSHinteraction.last_match == PROMPT and not self.DeviceType): self.DeviceType = "cisco" self.SSHinteraction.send("enable") #We need to send the enable pass elif self.SSHinteraction.last_match == ENABLE_PASS_PROMPT: self.SSHinteraction.send(enablepass) elif self.SSHinteraction.last_match == JUNOS_SHELL: #we got the junos shell need to get in the cli self.SSHinteraction.send("cli") #We have the device type and a prompt elif ((self.SSHinteraction.last_match == PROMPT or self.SSHinteraction.last_match == JUNOS_PROMPT) and self.DeviceType): break except: raise ValueError("Failed to connect to Device and initialize obj") pass
class netDOer: """This class interacts with a network device using an SSH connection, currently attempts to support IOS like devices and Junos devices""" def __init__(self, user, password, host, enablepass, timeout=60, display=False): """Constructor for NetDOer class. Arguments: user - user to connect with password - password to connect to device with host - host device to connect to. timeout - timeout for connection The constructed object will already be in privleged mode after the object is initialized if the devie is IOSlike. """ try: #Create paramiko session to device, it must be attached to object #so it isn't closed. self.SSHclient = paramiko.SSHClient() self.SSHclient.load_system_host_keys() self.SSHclient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.SSHclient.connect(hostname=host, username=user, password=password) self.SSHinteraction = SSHClientInteraction(self.SSHclient, timeout=timeout, display=display) self.DeviceType = False while True: self.SSHinteraction.expect(firstexpectvalues) #We saw JUNOS after login so the device is juniper if self.SSHinteraction.last_match == JUNOS_MATCH: self.DeviceType = "junos" #We need to see if we have the cli or shell junosshellre = re.compile(JUNOS_SHELL) match = junosshellre.search( self.SSHinteraction.current_output) junospromptre = re.compile(PROMPT) promptmatch = junospromptre.search( self.SSHinteraction.current_output) if match: #we have the shell need the CLI self.SSHinteraction.send("cli") elif promptmatch: #we have a prompt and are good to go. break #We have a prompt and no device type yet. elif (self.SSHinteraction.last_match == PROMPT and not self.DeviceType): self.DeviceType = "cisco" self.SSHinteraction.send("enable") #We need to send the enable pass elif self.SSHinteraction.last_match == ENABLE_PASS_PROMPT: self.SSHinteraction.send(enablepass) elif self.SSHinteraction.last_match == JUNOS_SHELL: #we got the junos shell need to get in the cli self.SSHinteraction.send("cli") #We have the device type and a prompt elif ((self.SSHinteraction.last_match == PROMPT or self.SSHinteraction.last_match == JUNOS_PROMPT) and self.DeviceType): break except: raise ValueError("Failed to connect to Device and initialize obj") pass def __getJuniperValue(self, commandstring): #Juniper values just happen to be #in the same position sometimes, lets take advantage. self.SSHinteraction.send(commandstring) self.SSHinteraction.expect(expectprompt) linesofoutput = self.SSHinteraction.current_output.split('\n') wordsofoutput = linesofoutput[1].split() return wordsofoutput[1] def __getCiscoCommandOutput(self, commandstring): #cisco commands can gennerate a lot of output but their pager at least #handles better than juniper. self.SSHinteraction.send(commandstring) self.SSHinteraction.expect(expectprompt) outputToReturn = self.SSHinteraction.current_output_clean while self.SSHinteraction.last_match == PAGER_PROMPT: self.SSHinteraction.send("") self.SSHinteraction.expect(expectprompt) outputToReturn += self.SSHinteraction.current_output_clean return outputToReturn def __setCiscoSetting(self, commandstring): self.SSHinteraction.send("configure terminal") self.SSHinteraction.expect(expectprompt) self.SSHinteraction.send(commandstring) self.SSHinteraction.expect(expectprompt) invalidcommandre = re.compile("Invalid input detected at") commandfailed = invalidcommandre.search( self.SSHinteraction.current_output) self.SSHinteraction.send("end") self.SSHinteraction.expect(expectprompt) if commandfailed: raise ValueError("IOS command was invalid") #The command was applied. return 0 def __setJuniperSetting(self, commandstring): self.SSHinteraction.send("edit") self.SSHinteraction.expect(expectprompt) self.SSHinteraction.send(commandstring) self.SSHinteraction.expect(expectprompt) invalidcommandre = re.compile("(syntax error)|(unknown command)") commandfailed = invalidcommandre.search( self.SSHinteraction.current_output) if commandfailed: #our command wasn't recognized we need to get out of edit and raise #an error. self.SSHinteraction.send("exit") self.SSHinteraction.expect(expectprompt) raise ValueError("Junos didn't recognize the command") else: #our command worked we can try to commit. self.SSHinteraction.send("commit") self.SSHinteraction.expect(expectprompt) commitre = re.compile("commit complete") commitsuccess = commitre.search(self.SSHinteraction.current_output) if commitsuccess: #it worked. self.SSHinteraction.send("exit") self.SSHinteraction.expect(expectprompt) return 0 else: #we need to rollback the commit failed self.SSHinteraction.send("rollback 0") self.SSHinteraction.expect(expectprompt) self.SSHinteraction.send("exit") self.SSHinteraction.expect(expectprompt) raise ValueError("Junos was unable to commit the change") def getSerial(self): """Returns the serial number of a device Arguments self Returns serial number for a device""" if self.DeviceType =="junos": return self.__getJuniperValue( "show chassis hardware | match Chassis") if self.DeviceType =="cisco": inventory = self.__getCiscoCommandOutput("show inventory") inventorylines = inventory.split("\n") words = inventorylines[1].split() return words[6] def getModel(self): """Returns model number of switch Arguments self returns string value for model of switch""" if self.DeviceType == "junos": return self.__getJuniperValue("show version | match Model") if self.DeviceType =="cisco": inventory = self.__getCiscoCommandOutput("show inventory") inventorylines = inventory.split("\n") words = inventorylines[1].split() return words[1] def getHostname(self): """Returns hostname of device Arguments self returns string value for hostname""" if self.DeviceType =="junos": return self.__getJuniperValue("show version | match Hostname") if self.DeviceType =="cisco": config = self.__getCiscoCommandOutput("show run | inc hostname") #in case there were two matches configlines = config.split("\n") configwords = configlines[0].split() return configwords[1] def getInterfaceList(self): #Cleaning up the output after handling the paging is going to take #effort skipping for now. if self.DeviceType =="junos": self.SSHinteraction.send("set cli screen-length 0") self.SSHinteraction.expect(expectprompt) self.SSHinteraction.send("show interfaces terse") self.SSHinteraction.expect(expectprompt) #returning a bunch of text. return self.SSHinteraction.current_output_clean if self.DeviceType == "cisco": return self.__getCiscoCommandOutput("show ip interface brief") def setHostname(self, hostname): if self.DeviceType == "junos": command = "set system host-name " + hostname return self.__setJuniperSetting(command) if self.DeviceType == "cisco": command = "hostname " + hostname return self.__setCiscoSetting(command) def setSNMPv2(self, community, write=False): if self.DeviceType =="junos": command = "set snmp community " + community if write: command += " authorization read-write" else: command += " authorization read-only" return self.__setJuniperSetting(command) if self.DeviceType == "cisco": command = "snmp-server community " + community if write: command += " RW" else: command += " RO" return self.__setCiscoSetting(command) def setNTPserver (self, ntpserver): if self.DeviceType =="junos": command = "set system ntp server " + ntpserver return self.__setJuniperSetting(command) if self.DeviceType == "cisco": command = "ntp server " + ntpserver return self.__setCiscoSetting(command)