简体   繁体   中英

Convert small python snippet from telnet to ssh

I have a small Python snippet that a monitoring tool that we have uses to pull information from crestron devices.

Is there a simple way to convert this small snippet into SSH.

I am not familiar with python at all so excuse me if there is an obvious answer but is this something that a free lance python programmer would be able to whip up or would this take a considerable amount of time.

Looking for any help I can get on this.

Thanks!

import time
import telnetlib

#Globals:
CACHE_DATA          = {}
SNIPPET_NAME        = 'Crestron: DCM Cache'
FAILED_COUNT        = 0
COLLECTION_PROBLEM  = False
TELNET_PORT         = 23                     ##Crestron only support port 23, don't use cred_port
TELNET_TIMEOUT      = 2                      ##default timeout in seconds, note if cred_timeout >= 2000 we will readjust later.
FAILED_ITEMS         = []

self.logger.ui_debug('************** %s: Starting *******************' % (SNIPPET_NAME))

#Main:
if self.cred_details['cred_type'] == 5: ##only allow Snippet cred types...

    #set global telnet timeout... if one has not been set, set it now.
    if self.cred_details['cred_timeout'] >= 2000:
        TELNET_TIMEOUT = int(self.cred_details['cred_timeout']/1000)

    #start timer
    start_time = time.time()
    try:
        #connect to telnet
        tn = telnetlib.Telnet(self.cred_details['cred_host'], TELNET_PORT, TELNET_TIMEOUT)

        #todo: add password handling.
        tn.read_until(">", TELNET_TIMEOUT)

        for obj_oid in result_handler.oids:
            ##obj_name = result_handler[obj_oid]['name']
            try:
                #run oid as CLI call from result_handler
                tn.write(obj_oid+"\r")
                rawdata = tn.read_until(">", TELNET_TIMEOUT)

                if rawdata:
                    result_handler[obj_oid] = [(0,"Collection Ok")]
                    CACHE_DATA[obj_oid] = rawdata.strip()
                else:
                    FAILED_COUNT += 1
                    result_handler[obj_oid] = [(0,"Failed: No data found")]
                    FAILED_ITEMS.append(obj_oid)
            except:
                FAILED_ITEMS.append(obj_oid)
                result_handler[obj_oid] = [(0,'Failed: Collection: %s' % obj_oid)]
                FAILED_COUNT +=1

        #save job time for perf graph
        CACHE_DATA['dcm_run_time'] = round(time.time() - start_time,4)

        #gracefully quit the telnet session so as to not leave any defunct processes on the host device.
        tn.write("bye\r")
        tn.close()

        if FAILED_COUNT is 0:
            em7_cache_result(CACHE_DATA)
        else:
            COLLECTION_PROBLEM = True
            PROBLEM_STR = "%s: Some Requests Failed: %s" % (SNIPPET_NAME, FAILED_ITEMS)
    except:
        COLLECTION_PROBLEM = True
        PROBLEM_STR = "%s: Failed to Connect to Remote Device: %s: Port %s" % (SNIPPET_NAME, self.cred_details['cred_host'], TELNET_PORT)
else:
    COLLECTION_PROBLEM = True
    PROBLEM_STR = "%s: Wrong Credential Type Aligned to This Dynamic Application" % (SNIPPET_NAME)

You should check out paramiko .

Example for opening an SSH connection and running 'ls':

import base64
import paramiko
key = paramiko.RSAKey(data=base64.b64decode(b'AAA...'))
client = paramiko.SSHClient()
client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
client.connect('ssh.example.com', username='strongbad', password='thecheat')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print('... ' + line.strip('\n'))
client.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM