def get_localhost_details(interfaces_eth, interfaces_wlan):
hostdata = "None"
hostname = "None"
windows_ip = "None"
eth_ip = "None"
wlan_ip = "None"
host_fqdn = "None"
eth_mac = "None"
wlan_mac = "None"
windows_mac = "None"
hostname = socket.gethostbyname(socket.gethostname())
if hostname.startswith("127.") and os.name != "nt":
hostdata = socket.gethostbyaddr(socket.gethostname())
hostname = str(hostdata[1]).strip('[]')
host_fqdn = socket.getfqdn()
for interface in interfaces_eth:
try:
eth_ip = get_ip(interface)
if not "None" in eth_ip:
eth_mac = get_mac_address(interface)
break
except IOError:
pass
for interface in interfaces_wlan:
try:
wlan_ip = get_ip(interface)
if not "None" in wlan_ip:
wlan_mac = get_mac_address(interface)
break
except IOError:
pass
else:
windows_ip = socket.gethostbyname(socket.gethostname())
windows_mac = uuid.getnode()
windows_mac = ':'.join(("%012X" % windows_mac)[i:i+2] for i in range(0, 12, 2))
hostdata = socket.gethostbyaddr(socket.gethostname())
hostname = str(socket.gethostname())
host_fqdn = socket.getfqdn()
return hostdata, hostname, windows_ip, eth_ip, wlan_ip, host_fqdn, eth_mac, wlan_mac, windows_mac
python类getnode()的实例源码
hostdetails.py 文件源码
项目:Python-Penetration-Testing-for-Developers
作者: PacktPublishing
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def init(browsing, mailing, printing, copyfiles, copysea, ssh, meeting, offline, private, breaks, attacking, t):
activities = createActivityList(browsing, mailing, printing, copyfiles, copysea, ssh, meeting, offline, private, breaks, attacking)
time.sleep(2)
parser = SafeConfigParser()
parser.read("packages/system/config.ini")
subnet, host, hostname = getSubnetHostAndHostname()
global myID
if platform.system() == "Linux":
myID = str(getnode())
else:
# For Windows, something must be trickled, since getnode () returns an incorrect value
hexMac = check_output(["getmac"])[162:180]
hexMacNoDash = hexMac.replace("-", "")
intMac = int(hexMacNoDash, 16)
myID = str(intMac)
global pathForLog
if platform.system() == "Linux":
pathForLog = "/home/debian/log/"
else:
pathForLog = "M:\\"
# In endless loop perform different activities
try:
while True:
if isWorkday(parser) and isWorkingHours(parser):
doSomething(activities)
else:
# Should be just the end of his work, he must wait until he has to work again
time.sleep(random.randint(1, 15)*60 - random.randint(1, 55))
except KeyboardInterrupt:
echoC(__name__, "SCRIPT STOPPED: KEYBOARDINTERRUPT")
sys.exit(0)
def copyRandomFile(fileNames, destination):
# Select a random file
fileNameWithPath = fileNames[randint(0, len(fileNames)-1)]
if platform.system() == "Linux":
separator = "/"
elif platform.system() == "Windows":
separator = "\\"
# If the file is copied to the VM, the MAC address (as an integer) is placed before the file names
# -> Avoid deadlocks when copying to the server
if "localstorage" in destination:
localFileName = str(getnode()) + "-" + fileNameWithPath.split(separator)[-1]
else:
localFileName = fileNameWithPath.split(separator)[-1]
# Path to the corresponding drive and filename
dstWithFileName = destination + localFileName
# Copy file
try:
copyfile(fileNameWithPath, dstWithFileName)
echoC(__name__, "Copied file " + localFileName + " to " + destination)
except Exception as e:
echoC(__name__, "copyfile() with destination " + destination + " error: " + str(e))
return -1
# copyfile() is not blocking
time.sleep(random.randint(15, 300))
return 0
# Select a file and copy it to the VM or the file server
def copyRandomFile(fileNames, destination):
# Pick a random file
fileNameWithPath = fileNames[randint(0, len(fileNames)-1)]
if platform.system() == "Linux":
separator = "/"
elif platform.system() == "Windows":
separator = "\\"
# If the file is copied to the VM, the MAC address (as an integer) is placed before the file names
# -> Avoid deadlocks when copying to the server
if "localstorage" in destination:
localFileName = str(getnode()) + "-" + fileNameWithPath.split(separator)[-1]
else:
localFileName = fileNameWithPath.split(separator)[-1]
# Path to the appropriate drive and filename
dstWithFileName = destination + localFileName
# Copy file
try:
copyfile(fileNameWithPath, dstWithFileName)
echoC(__name__, "Copied file " + localFileName + " to " + destination)
except Exception as e:
echoC(__name__, "copyfile() with destination " + destination + " error: " + str(e))
return -1
# copyfile() is not blocking
time.sleep(random.randint(15,120))
return 0
def test_getnode(self):
node1 = uuid.getnode()
self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)
# Test it again to ensure consistency.
node2 = uuid.getnode()
self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2))
def test_getnode(self):
node1 = uuid.getnode()
self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)
# Test it again to ensure consistency.
node2 = uuid.getnode()
self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2))
def getmac():
mac = get_mac()
mac = ':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2))
return mac
def mac_addresses():
mac = get_mac()
':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2))
arr = []
for iface in psutil.net_io_counters(pernic=True):
try:
addr_list = psutil.net_if_addrs()
mac = addr_list[str(iface)][2][1]
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str(
mac) != '00:00:00:00:00:00':
arr.append(mac.lower())
except Exception as e:
pass
return arr
def generate_uuid(self, depend_mac=True):
if depend_mac is False:
self.logger.debug('uuid creating randomly')
return uuid.uuid4() # make a random UUID
else:
self.logger.debug('uuid creating according to mac address')
return uuid.uuid3(uuid.NAMESPACE_DNS,
str(get_mac())) # make a UUID using an MD5 hash of a namespace UUID and a mac address
def login(self):
flag = True
if self.loginUrl is not None:
try:
mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
self.params.append(
('KEY', self.md5(self.softKey.upper() + self.user.upper()) + mac))
self.opener.addheaders = self.params
url = "http://" + self.loginUrl
url += "/Upload/Login.aspx?U=%s&p=%s" % (
self.user, self.md5(self.pwd))
try:
response = self.opener.open(url, None, 60)
if response.code == 200:
body = response.read()
if body is not None:
if body.find("-") > 0:
us = body.split("_")
self.uid = us[0]
self.uKey = body.strip()
print '???????ID??', self.uid
flag = True
else:
print '????,??????', body
flag = False
except Exception, e:
print "Error:Login Request"
print e
except Exception, e:
print "Error:Login Params "
print e
return flag
def send_init(self):
cpus=multiprocessing.cpu_count()
mac=':'.join('%02X' % ((get_mac() >> 8*i) & 0xff) for i in reversed(xrange(6)))
self.socket.sendto("init#"+str(cpus)+"#"+mac, (self.server_ip, self.tx_port))
def is_latest():
node = uuid.getnode()
jsn = uuid.UUID(int=node).hex[-12:]
with open(os.path.join(BASE_DIR, 'version')) as f:
current_version = f.read()
lastest_version = urllib.urlopen('http://www.jumpserver.org/lastest_version.html?jsn=%s' % jsn).read().strip()
if current_version != lastest_version:
pass
def get_mac_address():
node = uuid.getnode()
mac = uuid.UUID(int=node).hex[-12:]
return mac
def get_mac():
# ??mac?? link: http://stackoverflow.com/questions/28927958/python-get-mac-address
return ("".join(c + "-" if i % 2 else c for i, c in enumerate(hex(
uuid.getnode())[2:].zfill(12)))[:-1]).upper()
def Connect(self):
self.socket_mode = UDP_MODE
self.mac = uuid.getnode()
# Set up UDP receiver.
self.udp_rx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_rx_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Pack multicast group structure correctly.
mreq = struct.pack('=4sl', socket.inet_aton(MCAST_GRP),socket.INADDR_ANY)
# Request access to multicast group.
self.udp_rx_sock.setsockopt(socket.IPPROTO_IP,
socket.IP_ADD_MEMBERSHIP, mreq)
# Bind to all intfs.
self.udp_rx_sock.bind(('', MCAST_PORT))
self.udp_rx_sock.settimeout(TIMEOUT)
# Set up UDP transmitter.
self.udp_tx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_tx_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
# Get the MAC address of the local adapter.
msg = bytearray(8)
struct.pack_into('<Q', msg, 0, int(self.mac))
self.local_mac = ''.join('{:02x}'.format(x) for x in msg[0:6])
logging.debug('MAC Addr: %s', self.local_mac)
def getMac(self, format=2):
if format < 2:
format = 2
if format > 4:
format = 4
mac_num = hex(getnode()).replace('0x', '').upper()
mac = '-'.join(mac_num[i : i + format] for i in range(0, 11, format))
#debug("Mac:" + mac)
return mac
def get_machine_id():
machine_id = get_rpi_serial()
if machine_id:
return machine_id
return str(uuid.getnode())
def get_mac_address():
mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
return ":".join([mac[e:e+2] for e in range(0,11,2)])
def get_mac_address():
mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
return ":".join([mac[e:e+2] for e in range(0,11,2)])
def fetch(path, t='GET'):
url = 'http{}://{}:{}/'.format(PLEX_SSL, PLEX_HOST, PLEX_PORT)
headers = {'X-Plex-Token': PLEX_TOKEN,
'Accept': 'application/json',
'X-Plex-Provides': 'controller',
'X-Plex-Platform': platform.uname()[0],
'X-Plex-Platform-Version': platform.uname()[2],
'X-Plex-Product': 'Plexpy script',
'X-Plex-Version': '0.9.5',
'X-Plex-Device': platform.platform(),
'X-Plex-Client-Identifier': str(hex(getnode()))
}
try:
if t == 'GET':
r = requests.get(url + path, headers=headers, verify=False)
elif t == 'POST':
r = requests.post(url + path, headers=headers, verify=False)
elif t == 'DELETE':
r = requests.delete(url + path, headers=headers, verify=False)
if r and len(r.content): # incase it dont return anything
return r.json()
else:
return r.content
except Exception as e:
print e