2017-08-09 65 views
0

我正在使用Python 2.7.12并尝试此代码。名称未在Python中定义

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') 

而且

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 

我试图运行Client.addClient(..),但并没有解决我的问题。 我想我需要一些帮助来理解这个..如果它不在类里面怎么定义?

+0

您需要首先创建'Client'实例...'myClient = Client('192.168.1.94','root','root')' –

+0

除了所有其他答案,您还需要添加' self'到'addClient'的参数(并且可能也适用于其他方法) – DeepSpace

+0

请参阅https://stackoverflow.com/questions/735975/static-methods-in-python –

回答

1

你需要做的类的实例首先使用它的方法:

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

和:

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

否则,你可以,如果你定义的方法,使用静态方法使用它像:

Client.addClient(...) 

而不必马一个实例。

+2

这仍然不起作用。 'addClient'是一个实例方法,但它不为该实例保留一个参数。 – DeepSpace

+0

我完全意识到它不会完全工作。但是我回答了他的问题,我不需要解决他的任务。 – Igor

+0

感谢您的答案,我不明白为什么如果我把方法静态我可以使用只需添加客户,否则没有 –