0
votes

Im using telnetlib.Telnet function to connect to telnet devices but I can't figure out how to fix error UnboundLocalError: local variable 'ip_addressa' referenced before assignment None , I saw UnboundLocalError: local variable 'text' referenced before assignment and UnboundLocalError on local variable when reassigned after first usebut that did not helped me, so here is my code

import getpass
import sys
import telnetlib
import traceback
 
def h4ck_th3_w0rld(HOST):
    user = 'admin'
    password = 'password'
    tn = None
    try:
        tn = telnetlib.Telnet(HOST, 23, 11)
 
        tn.read_until("Username: ", 7)
        tn.write(user + "\n")
        if password:
            tn.read_until("Password: ", 7)
            tn.write(password + "\n")

    for a in range(200, 256):
        for b in range(7, 7):
            ip_addressa = '192.168.%d.%d' % (b, a)
          
            print(ip_addressa)
 

    tn.write("cd /var/tmp\n")
    tn.write("./busybox telnet" + ip_addressa + "\n")
        tn.write("exit\n")
 
        print(tn.read_all())
    except Exception as e:
        #print traceback.print_exc()
        print 'Error occurred'
    finally:
        if tn:
            tn.close()
 
 
for i in range(205, 206):
    for j in range(7, 8):
        ip_address = '192.168.%d.%d' % (j, i)
        h4ck_th3_w0rld(ip_address)
        print(ip_address)

So Im getting an error UnboundLocalError: local variable 'ip_addressa' referenced before assignment None

1

1 Answers

1
votes

Please post the traceback so we can see the failing line. And consider boiling this down to a minimal example that we can run to test. As stands I just have to guess. But...

    for b in range(7, 7):
        ip_addressa = '192.168.%d.%d' % (b, a)
        print(ip_addressa)

range(7,7) doesn't iterate anything so the loop doesn't run, ip_addressa isn't assigned and nothing is printed. What that range should be depends on how many addresses you want to iterate.

You have other problems in the posted code, like the for is not indented properly inside the "try/except" which is a syntax error. And tn.write("cd /var/tmp\n") should be inside the for. Maybe there is some tabs to spaces thing going on, so I can't really say.