[英]Python Class inheritance and using variables
我是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
則可以直接從類中調用它們。
您只能從類的特定實例(在本例中為Scan
或Ping
)獲取並設置target_hosts
。 如果調用Scan.target_hosts
或Ping.target_hosts
,它將返回類似<property at 0x51cd188>
。 這基本上是從類返回一個不可用的函數。 就是說,“類字典在此處包含有關如何從<class>
INSTANCE返回一些有用內容的說明。”
如果您創建Ping或Scan實例,則現在可以訪問target_hosts
屬性。
>>> scan = Scan()
>>> scan.target_hosts = 'host1, host2, host3'
>>> scan.target_hosts
'host1 host2 host3'
>>> ping = Ping('stuff', 'nonsense')
>>> ping.hosts
'nonsense'
>>> ping.target_hosts = 'host4, host5, host6'
>>> ping.target_hosts
'host4 host5 host6'
您可以使用虛擬Ping實例運行腳本。 這應該工作。
from models.scan import Scan
from models.ping import Ping
dummy = Ping('ignore', 'this')
hosts = "192.168.0.0/24"
dummy.target_hosts = hosts
pinger = Ping(ping_string, dummy.target_hosts)
或者,如果Scan
具有staticmethod
, Ping
也可以使用它。
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"
@staticmethod
def prep_hosts(hosts):
return hosts.replace(", ", " ")
...
接着
from models.scan import Scan
from models.ping import Ping
hosts = "192.168.0.0/24"
input_hosts = Ping.prep_hosts(hosts) # or Scan.prep_hosts(hosts)
pinger = Ping(ping_string, input_hosts)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.