import paramiko import logging from time import sleep logging.basicConfig() logging.getLogger("paramiko").setLevel(logging.DEBUG) hostname = '172.23.224.40' sshuser = 'Administrator' sshkeylocation = '/home/jc/.ssh/id_rsa' paramiko.transport.Transport._preferred_keys += ('ssh-dss',) # Allow the insecurities ssh = paramiko.SSHClient() # Alias ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Ignore host key ssh.connect(hostname, username=sshuser, key_filename=sshkeylocation) # Attempt to connect channel = ssh.invoke_shell() # Get a new shell(, and keep it open, since we need to exec multiple commands depending on the last command being executed successfully.) def ssh_runcmd(command): # ssh_runcmd # Input validation if not type(command) is str: raise TypeError("ssh_runcmd: command must be a string, '" + command + "' is not.") channel.send(command + '\n') # Execute command. while not channel.recv_ready(): # Wait for output to be recieved. sleep(0.5) # The command could still be writing to output buffer after running for 0.5s. Assuming during the period we read the buffer, cmd can keep up with us, or at least till the 8th KiB end. cmdout = channel.recv(65536).decode("ascii") # Get output, capped to 64KiB, format ascii. | Must get, otherwise next command will get this command's output. cmdout = cmdout.split('\n')[2:-3] # Split to a list, per newlines. Remove first 2, and last 3 lines. #cmdout = '\n'.join(cmdout) return(cmdout) ### MAIN ### logging.debug(ssh_runcmd('show date')) # Get rid of motd, init for next cmds. This is better than indefinitely reading buffer before any command as to counter this. # Get a list of blades ServerList = ssh_runcmd('show server names') breakpoint() print(ServerList) # ServerList = re.sub('(Banana)', r'\1Toothpaste', oldstring) # connect server n # show system1/oemhp_power1 # exit # End sesion. logging.debug(ssh_runcmd('exit')) ssh.close()