将小python代码段从telnet转换为ssh

时间:2018-02-07 01:35:25

标签: python ssh telnet

我有一个小的Python代码段,我们用它来监控来自crestron设备的信息。

是否有一种简单的方法可以将这个小片段转换为SSH。

我对python完全不熟悉,如果有明显的答案,请原谅我,这是一个免费的lance python程序员能够掀起的,或者这需要花费相当多的时间。

寻求任何帮助,我可以得到这个。

谢谢!

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)

1 个答案:

答案 0 :(得分:0)

您应该查看paramiko

打开SSH连接并运行'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()