David Russo
David Russo

Reputation: 19

Name is not defined in Python

I'm using Python 2.7.12 and trying this code.

clientNet = []
class Client:
    def __init__(self, host, user, password):
        self.host = host
        self.user = user
        self.password = password
        self.session = self.connect()
    def connect(self):
        try:
            s = pxssh.pxssh()
            s.login(self.host, self.user, self.password)
            return s
        except Exception, e:
            print e
            print '[-] Error Connecting'
    def botnetCommand(command):
        for client in clientNet:
            output = client.send_command(command)
            print '[*] Output from ' + client.host
            print '[+] ' + output + '\n'
    def send_command(self, cmd):
        self.session.sendline(cmd)
        self.session.prompt()
        return self.session.before
    def addClient(host, user, password):
        client = Client(host, user, password)
        clientNet.append(client)

addClient('192.168.1.94','root','root')

And

 Traceback (most recent call last):
  File "host.py", line 33, in <module>
    addClient('192.168.1.94','root','root')
NameError: name 'addClient' is not defined

I tried to run Client.addClient(..) but didn't resolve my problem. I think I need some help to understand this.. How cannot be defined if it is inside of the Class?

Upvotes: 0

Views: 1746

Answers (1)

Igor Pejic
Igor Pejic

Reputation: 3698

You need to make an instance of the class to use its methods first:

client = Client('192.168.1.94','root','root')
client.addClient('192.168.1.95','root','root')

Otherwise you could use a static method if you define the method as:

...
@staticmethod
def addClient(host, user, password):
    client = Client(host, user, password)
    clientNet.append(client)

and use it like:

Client.addClient(...)

without having to make an instance.

Upvotes: 1

Related Questions