From 91966f7e2d08b6004cd41fbd044e195e1e79989e Mon Sep 17 00:00:00 2001 From: rasmus Date: Mon, 21 Dec 2020 23:43:08 +0200 Subject: [PATCH] Starting to query blades. --- __pycache__/listServers.cpython-38.pyc | Bin 0 -> 971 bytes dt.py | 39 ------------ getme.py | 52 ---------------- listServers.py | 40 ++++++++++++ main.py | 83 +++++++++++++++++++++++++ test.py | 0 test2.py | 0 7 files changed, 123 insertions(+), 91 deletions(-) create mode 100644 __pycache__/listServers.cpython-38.pyc delete mode 100644 dt.py delete mode 100644 getme.py create mode 100644 listServers.py create mode 100644 main.py create mode 100644 test.py create mode 100644 test2.py diff --git a/__pycache__/listServers.cpython-38.pyc b/__pycache__/listServers.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a473bb67cc32d010862be979e44953ae53e8143 GIT binary patch literal 971 zcma)4&2AGh5VpO$*`GA1LZxjupgka@BFf%+KnMXXNL->yp&S;f%2}Ia$z~I5r=^wm zLg2=skB}aD2cEP&IU;R!yr&M+}3)4;{`ul?fR81u~`{R=uIC!-e?^B^lE?Q^F zLCHT&c&0du8C5hEJj?kpL??s1;Bk>lm6!ck)_ur_3)|Xn953uYaTdIN)|0$chYJ@% z1HiIh`DiOLelhO%q1FVM$W@-v!bERqG376W7z-2faysIIDsG&Dm!?4{6J9do30n36 z%S&ZEsYE_89^<`ff2(PtWgB)IY3s`0AImft&{L^sHcT5O=d9oc=LR38t5>v_IWL$r z{t}U?BgJvLc9q|q3IW5s9!*l`eZjsXamx;yB!lsYCm*sTOZvG=hTC#NGoJJc%J{aF zgTyYWd%2*=scBw|9Z--D;6mOCj&ML+C%`UV#hZAAK!k4+m#p9b-z5+5ZNMTNIbs9& fTSWNq)PCK_wQC&`CU`s=vuVMf*iRzu_Xx-z13>n* literal 0 HcmV?d00001 diff --git a/dt.py b/dt.py deleted file mode 100644 index 22674b4..0000000 --- a/dt.py +++ /dev/null @@ -1,39 +0,0 @@ -import logging - -serverName = ['Bay Server Name Serial Number Status Power UID Partner\r', '--- ------------------------------------------------- --------------- -------- ------- --- -------\r', ' 1 tty-lab-1 OK On Off \r', ' 2 tty-lab-2 CZ320263P9 OK On Off \r', ' 3 tty-lab-3 CZJ14410KP Failed On Off \r', ' 4 kspve1 CZJ14410KK OK On Off \r', ' 5 kspve2-2 OK On Off \r', ' 6 kspve3 OK On Off \r', ' 7 plaes-blade OK On Off \r', ' 8 Ringly-01 CZ3402Y48C OK On Off \r', ' 9 toomas-lepik CZ3217FNYE OK On Off \r', ' 10 toomas-lepik2 CZ3217FFSS OK On Off \r', ' 11 [Absent] \r', ' 12 erki-naumanis OK On Off \r', ' 13 [Absent] \r', ' 14 [Absent] \r', ' 15 [Absent] \r', ' 16 [Absent] \r'] - -serverNamePos = [] # Init list - -# https://stackoverflow.com/a/19842807 -haystack = serverName[1] -needle = " " -for i, _ in enumerate(haystack): - if haystack[i:i + len(needle)] == needle: - serverNamePos.append(i) # Add results to list. The last positions of each field are indexed, the next one being the seperator. - -serverNameFields = len(serverNamePos) # How many fields do we have to process - -n = 2 # What server, 2 is the first one. - -servers = [] # Init, the results of this. -for n in range(2, len(serverName)): # Loop through servers. | Adjust for the first two being headers. - # Fields: [BayNumber "Server Name", "Serial Number", "Status", "Power", "UID Partner"] - serverNameCurrentTmp = [] # Init - - for i in range(serverNameFields): - if i == 0: # Special case, as i-1 would loop around. - serverNameCurrentTmp.append( int( serverName[n][0:serverNamePos[i]].strip() ) ) # Also convert to int, as we know it's a number. - else: - serverNameCurrentTmp.append( serverName[n][serverNamePos[i-1]+1:serverNamePos[i]].strip() ) # Get ith field by character position. - servers.append(serverNameCurrentTmp) - -logging.debug('Bays:') -logging.debug(servers) -breakpoint() - -for n in range(len(servers)): - print(n) - -#print(servers) - -breakpoint() \ No newline at end of file diff --git a/getme.py b/getme.py deleted file mode 100644 index 989e57c..0000000 --- a/getme.py +++ /dev/null @@ -1,52 +0,0 @@ -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() diff --git a/listServers.py b/listServers.py new file mode 100644 index 0000000..5761ae5 --- /dev/null +++ b/listServers.py @@ -0,0 +1,40 @@ +import logging + +def listServers(serverName): + # Expected data: + # serverName = ['Bay Server Name Serial Number Status Power UID Partner\r', '--- ------------------------------------------------- --------------- -------- ------- --- -------\r', ' 1 tty-lab-1 OK On Off \r', ' 2 tty-lab-2 CZ320263P9 OK On Off \r', ' 3 tty-lab-3 CZJ14410KP Failed On Off \r', ' 4 kspve1 CZJ14410KK OK On Off \r', ' 5 kspve2-2 OK On Off \r', ' 6 kspve3 OK On Off \r', ' 7 plaes-blade OK On Off \r', ' 8 Ringly-01 CZ3402Y48C OK On Off \r', ' 9 toomas-lepik CZ3217FNYE OK On Off \r', ' 10 toomas-lepik2 CZ3217FFSS OK On Off \r', ' 11 [Absent] \r', ' 12 erki-naumanis OK On Off \r', ' 13 [Absent] \r', ' 14 [Absent] \r', ' 15 [Absent] \r', ' 16 [Absent] \r'] + + # Check if the first item in the list is the header. If this is true (data started at right place), most likely the other data is fine as well. + if not serverName[0] == 'Bay Server Name Serial Number Status Power UID Partner\r': + logging.critical(serverName) + raise ValueError('Unexpected data recieved while listing servers.') + + serverNamePos = [] # Init list + + # https://stackoverflow.com/a/19842807 + haystack = serverName[1] + needle = ' ' + for i, _ in enumerate(haystack): + if haystack[i:i + len(needle)] == needle: + serverNamePos.append(i) # Add results to list. The last positions of each field are indexed, the next one being the seperator. + + serverNameFields = len(serverNamePos) # How many fields do we have to process + + servers = [] # Init, the results of this. + for srv in range(2, len(serverName)): # Loop through servers. | Adjust for the first two being headers. + # Fields: [BayNumber "Server Name", "Serial Number", "Status", "Power", "UID Partner"] + serverNameCurrentTmp = [] # Init + + for fld in range(serverNameFields): + if fld == 0: # Special case, as i-1 would loop around. + serverNameCurrentTmp.append( int( serverName[srv][0:serverNamePos[fld]].strip() ) ) # Also convert to int, as we know it's a number. + else: + serverNameCurrentTmp.append( serverName[srv][serverNamePos[fld-1]+1:serverNamePos[fld]].strip() ) # Get ith field by character position. + if not ( serverNameCurrentTmp[1] == '[Absent]' and serverNameCurrentTmp[4] == '' ): # If name is Absent and power status isn't available, there probably isn't a server there. + servers.append(serverNameCurrentTmp) # Only append if the bay is actually in use. + + logging.debug('Servers:') + logging.debug(servers) + #breakpoint() + + return(servers) \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..f18ceb2 --- /dev/null +++ b/main.py @@ -0,0 +1,83 @@ +# External deps +import paramiko +import logging +from time import sleep + +# Local deps +import listServers + +# Debugging stuffs +logging.basicConfig() +logging.getLogger("paramiko").setLevel(logging.DEBUG) + +# Creds +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 REMOVE ME (though it doesn't kind of matter anyways) + +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 = "" # Init + while channel.recv_ready() or not cmdout[-2:] == '> ': # Fetch new output, if there is any or look for '> ' (prompt ready). The latter is useful when connecting to blades. + sleep(0.5) + cmdout += channel.recv(65536).decode("ascii") # Get output, capped to 64KiB, format ascii. | Must get, otherwise next command will get this command's output. + breakpoint() + cmdout = cmdout.split('\n')[2:-3] # Split to a list, per newlines. Remove first 2, and last 3 lines. + #cmdout = '\n'.join(cmdout) # DO NOT UNCOMMENT THIS, HERE FOR ONLY REFERENCE TO JOIN THE LINES BACK. + return(cmdout) # Return list of output stuff. + +### 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 +# TESTING DATA IN USE +# serverName = ssh_runcmd('show server names') +serverName = ['Bay Server Name Serial Number Status Power UID Partner\r', '--- ------------------------------------------------- --------------- -------- ------- --- -------\r', ' 1 tty-lab-1 OK On Off \r', ' 2 tty-lab-2 CZ320263P9 OK On Off \r', ' 3 tty-lab-3 CZJ14410KP Failed On Off \r', ' 4 kspve1 CZJ14410KK OK On Off \r', ' 5 kspve2-2 OK On Off \r', ' 6 kspve3 OK On Off \r', ' 7 plaes-blade OK On Off \r', ' 8 Ringly-01 CZ3402Y48C OK On Off \r', ' 9 toomas-lepik CZ3217FNYE OK On Off \r', ' 10 toomas-lepik2 CZ3217FFSS OK On Off \r', ' 11 [Absent] \r', ' 12 erki-naumanis OK On Off \r', ' 13 [Absent] \r', ' 14 [Absent] \r', ' 15 [Absent] \r', ' 16 [Absent] \r'] +servers = listServers.listServers(serverName) + +baysInUse = [x[0] for x in servers] # List of blades in use. +baysInUseCount = len(baysInUse) # How many bays in use. +logging.info("There are " + str(baysInUseCount+1) + "servers presenet.") # Further optimizations could be made by not connecting to servers, what are turned off. + +# TESTING DATA IN USE +baysInUseCount = 1 + +for b in range(1, baysInUseCount+1): + logging.info("Accessing server " + str(b)) + logging.debug( ssh_runcmd('connect server ' + str(b)) ) # Use the enc as a jump host. + sleep(7) + powerInfoTmp = ssh_runcmd('show system1/oemhp_power1') # Get the data + print(powerInfoTmp) + + logging.debug(ssh_runcmd('exit')) # Exit the blade's iLO, return to the enc's iLO SSH interface. + breakpoint() + +breakpoint() + +#print() + +# ServerList = re.sub('(Banana)', r'\1Toothpaste', oldstring) + +# connect server n +# show system1/oemhp_power1 +# exit + +# End sesion. +logging.debug(ssh_runcmd('exit')) +ssh.close() diff --git a/test.py b/test.py new file mode 100644 index 0000000..e69de29 diff --git a/test2.py b/test2.py new file mode 100644 index 0000000..e69de29