我对Python还不熟悉,尝试使用类继承,但还不能完全理解共享变量。到目前为止,我有两个类,Scan
和Ping
:
scan.py
class Scan(object):
""" Super class for scans """
identifier = str(random.getrandbits(128))
timestamp = int(time.time())
results_dir = "/tmp/{}/".format(identifier)
total_hosts = 0
def __init__(self, target_hosts=None, target_ports=None):
self.__target_hosts = target_hosts
self.__target_ports = target_ports
self.scan_string = "-sT -O --script auth,vuln"
@property
def target_hosts(self):
return self.__target_hosts
@target_hosts.setter
def target_hosts(self, hosts):
""" Sets target hosts for scan """
""" Nmap Expects to be single-spaced '1 2 3' separated """
self.__target_hosts = hosts.replace(", ", " ")
ping.py
import nmap
from .scan import Scan
class Ping(Scan):
""" Ping sweep """
def __init__(self, ping_string, hosts):
super(Scan, self).__init__()
self.ping_string = ping_string
self.hosts = hosts
在我的脚本中,几乎调用了所有内容,我尝试:
from models.scan import Scan
from models.ping import Ping
s = Scan()
hosts = "192.168.0.0/24"
s.target_hosts = hosts
pinger = Ping(ping_string, s.target_hosts)
这句话对我来说毫无意义。。。如果Ping从Scan继承,为什么只有在调用s.targets_hosts
时才起作用?难道我不能像Ping.target_hosts
那样从我的Ping
类调用target_hosts
吗
让人难以理解的是,这是一个奇怪的例子。在您的示例中,生成
Ping
实例所需的hosts
参数的正确输入需要来自只能从Ping
实例(或其父级Scan
)访问的属性任何以
self
作为参数的方法(或属性)都依赖于需要首先创建的类的特定实例。如果存在staticmethod
或classmethod
,则可以直接从类中调用它们只能从类的特定实例获取和设置
target_hosts
(在本例中为Scan
或Ping
)。如果调用Scan.target_hosts
或Ping.target_hosts
,它将返回类似<property at 0x51cd188>
的内容。这基本上是从类返回一个不可用的函数。它的意思是,“类字典包含了关于如何从<class>
实例返回一些有用信息的说明。”如果创建Ping或Scan的实例,现在就可以访问
target_hosts
属性可以使用一个伪Ping实例运行脚本。这应该管用
或者,如果
Scan
有一个staticmethod
,那么Ping
也可以使用它然后呢
相关问题 更多 >
编程相关推荐