名称未在Python中定义
我正在使用Python2.7.12并尝试这段代码名称未在Python中定义,python,class,methods,Python,Class,Methods,我正在使用Python2.7.12并尝试这段代码 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):
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')
及
回溯(最近一次呼叫最后一次):
文件“host.py”,第33行,在
addClient('192.168.1.94','root','root'))
NameError:未定义名称“addClient”
我试图运行Client.addClient(..)
,但没有解决我的问题。
我想我需要一些帮助来理解这一点。。如果它在类内部,如何定义它 首先需要创建类的实例以使用其方法:
client = Client('192.168.1.94','root','root')
client.addClient('192.168.1.95','root','root')
否则,如果将方法定义为:
...
@staticmethod
def addClient(host, user, password):
client = Client(host, user, password)
clientNet.append(client)
然后像这样使用它:
Client.addClient(...)
无需创建实例。您需要先创建
客户机的实例。
myClient=Client('192.168.1.94','root','root')
除了所有其他答案之外,您还需要将self
添加到addClient
的参数中(可能也添加到其他方法中),看这仍然不起作用addClient
是一个实例方法,但它没有为实例保留参数。我完全知道它无法完全工作。但是我回答了他的问题,我没有必要解决他的任务。谢谢你的回答,我不明白为什么如果我把这个方法变成静态的,我可以用它来添加客户,否则就不用了
Client.addClient(...)