Question

I am new to python, I am writing a script to 'telenet' device IP in some cases and SSH username@deviceIp if telnet faiils..

For all Telnet IP's it work perfectly.. But when i am doing "ssh admin@153.88.127.21" the below code fails and I get error in try bloc itself like "socket.error" for ssh device's.

I want ssh devices to enter else block,, if telnet Ip fails in try block.

In my Main.py file

    try:
        #TELNET MODULE CALL
        tn= _telnetMOD._telnet(username, password, device)
        break
    else:
        #SSH MODULE CALL
        ssh= _sshMOD._ssh(username, password, device)

In _telnetMod file i have below code which works import telnetlib

def _telnet(_userVar,_passwordVAR, _device):
    tn=''
    tn = telnetlib.Telnet(_device,23)
    #PYTHON VERSION 2.6 AND HIGHER
    tn.read_until("Username: ",10)
    tn.write(_userVar + "\r")
    if _passwordVAR:
        tn.read_until("Password: ",10)
        tn.write(_passwordVAR + "\r")    
    return tn

In _sshMOD file i have below code which fails and not sure of below code

import paramiko 

def _ssh(_userVar,_passwordVAR, _device):
    ssh=''
    ssh= paramiko.SSHClient()
    ssh.connect(_device, username=_userVar,password=_passwordVAR)
    return ssh
Was it helpful?

Solution

Did you forgot the client.load_system_host_keys()? This is an example from the docs:

client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com')
stdin, stdout, stderr = client.exec_command('ls -l')

And you should use the try block like this:

try:
    telnet()
except:
    telnet = false
if telnet == false:
    try:
        ssh()
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top