I got the following script output:
***************************************************
[g4u2680c]: searching for domains
---------------------------------------------------
host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]
host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]
* script completed Mon Jun 15 06:13:14 UTC 2015 **
* sleeping 30 to avoid DOS on dns via a loop **
I need to extract the 2 host list into a dictionary, with out the brackets.
Here is my code:
#!/bin/env python
import re
text="""***************************************************
[g4u2680c]: searching for domains
---------------------------------------------------
host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]
host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]
* script completed Mon Jun 15 06:13:14 UTC 2015 **
* sleeping 30 to avoid DOS on dns via a loop **
***************************************************
"""
seq = re.compile(r"host.+?\n\n",re.DOTALL)
a=seq.findall(text)
matches = re.findall(r'\w.+=.+', a[0])
matches = [m.split('=', 1) for m in matches]
matches = [ [m[0].strip().lower(), m[1].strip().lower()] for m in matches]
#should have function with regular expression to remove bracket here
d = dict(matches)
print d
What I got so far for the first host:
{'subnet': '[255.255.248.0]', 'vlan': '[352]', 'ipaddr': '[16.208.16.72]', 'cluster': '[g4u2679c g4u2680c g9u1484c g9u1485c]', 'host': 'g4u2680c.houston.example.com', 'gateway': '[16.208.16.1]'}
I need help to find the regex to remove the bracket as the value in the dictionary contain data with and without bracket.
Or if there is a better and simpler way to transform the original script output into dictionary.
You can use: (\w+)\s*=\s*\[?([^\n\]]+)\]?
demo
import re
p = re.compile(ur'(\w+)\s*=\s*\[?([^\n\]]+)\]?', re.MULTILINE)
test_str = u"host = g4u2680c.houston.example.com\n ipaddr = [16.208.16.72]\n VLAN = [352]\n Gateway= [16.208.16.1]\n Subnet = [255.255.248.0]\n Subnet = [255.255.248.0]\n Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]\n\nhost = g4u2680c.houston.example.com\n ipaddr = [16.208.16.72]\n VLAN = [352]\n Gateway= [16.208.16.1]\n Subnet = [255.255.248.0]\n Subnet = [255.255.248.0]\n Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]\n"
re.findall(p, test_str)
You can simply use re.findall and dict :
>>> dict([(i,j.strip('[]')) for i,j in re.findall(r'(\w+)\s*=\s*(.+)',text)])
{'Subnet': '255.255.248.0', 'VLAN': '352', 'ipaddr': '16.208.16.72', 'Cluster': 'g4u2679c g4u2680c g9u1484c g9u1485c', 'host': 'g4u2680c.houston.example.com', 'Gateway': '16.208.16.1'}
And about the brackets you can remove them by str.strip method.
You can try out this.
matches = [m.replace('[','').replace(']','').split('=', 1) for m in matches]
Related
I managed to have this code run after few hours of searches but unfortunately, this does not produce the output I wanted which is to get the LP Pool Address in (TOKEN/BNB LP).
Given the Token Address: 0xe56842ed550ff2794f010738554db45e60730371
I wanted to get the BIN/BNB Pool Address: 0xe432afB7283A08Be24E9038C30CA6336A7cC8218.
Any ideas what could be the problem?
from web3 import Web3
from eth_abi.packed import encode_abi_packed
from eth_abi import encode_abi
import eth_abi
"""
Contract: 0xe56842ed550ff2794f010738554db45e60730371
BIN/BNB Address: 0xe432afB7283A08Be24E9038C30CA6336A7cC8218
BIN/BNB LP URL: https://bscscan.com/token/0xe432afB7283A08Be24E9038C30CA6336A7cC8218#balances
"""
CONTRACTS = {"CONTRACT": "0xe56842ed550ff2794f010738554db45e60730371",}
PANCAKE_SWAP_FACTORY = "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73"
PANCAKE_SWAP_ROUTER = "0x10ED43C718714eb63d5aA57B78B54704E256024E"
WBNB_ADDRESS = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
hexadem_= '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
factory = PANCAKE_SWAP_FACTORY
abiEncoded_1 = encode_abi_packed(['address', 'address'], (CONTRACTS['CONTRACT'], WBNB_ADDRESS))
salt_ = Web3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])
abiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))
resPair = Web3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), hexadem_])[12:]
# resPair is the address for the pancakeswap CONTRACT /WBNB pair
print("Token Contract: ", CONTRACTS)
print("BNB-LP Address: ", resPair.hex()) #-- expecting to get 0xe432afB7283A08Be24E9038C30CA6336A7cC8218
Current Output:
BNB-LP Address: 0xde173b8a63b9641a531de0fbb1c5c9eee3b4bc0c
Expected Output:
Token Contract: 0xe56842ed550ff2794f010738554db45e60730371
BNB-LP Address: 0xe432afB7283A08Be24E9038C30CA6336A7cC8218 #-- correct LP Address
You need to enter the two coins in alphabetical order.
pair_traded = [token_a, token_b] #token_a, token_b are the address's
pair_traded.sort()
hexadem_1 = 0xff
abiEncoded_1 = encode_abi_packed(['address', 'address'], (token_list[0], token_list[1] ))
salt_ = w3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])
abiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))
pair_address = w3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), pair_code_hash])[12:]
For Pancake Swap the hexadem_ should be like this I think:
hexadem_= '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5' ## Pancake SWAP
The one in your code is for UniSwap
hexadem_ = '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5' # This is pancake right hex。
factory = PANCAKE_SWAP_FACTORY
abiEncoded_1 = encode_abi_packed(['address', 'address'], (CONTRACTS['CONTRACT'], WBNB_ADDRESS))
salt_ = Web3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])
abiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))
resPair = Web3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), hexadem_])[12:]
But the value I output is different from yours, my output value:
Token Contract: {'CONTRACT': '0xe56842ed550ff2794f010738554db45e60730371'}
BNB-LP Address: 0xdbb161367d9a2a852ebeef3cbfcbf2c43b85064b
I figured out you need to make sure both addresses are all lowercase or all uppercase. This makes a difference when sorting. This works for me:
def compute_pool_address(self, token_address_a, token_address_b):
pair_traded = [token_address_a.lower(), token_address_b.lower()]
pair_traded.sort()
hexadem = '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5'
abiEncoded_1 = encode_abi_packed(['address', 'address'], (pair_traded[0], pair_traded[1]))
salt_ = self.web3.solidityKeccak(['bytes'], ['0x' + abiEncoded_1.hex()])
abiEncoded_2 = encode_abi_packed(['address', 'bytes32'], (PANCAKE_FACTORY_ADDRESS, salt_))
return self.web3.toChecksumAddress(self.web3.solidityKeccak(['bytes', 'bytes'], ['0xff' + abiEncoded_2.hex(), hexadem])[12:])
(self.web3 is a web3.py Web3 instance)
I had similar problems when trying to recreate the functionality of the uniswap contract. It was resolved when I used the eth_abi.abi.encode(python) function inside an expression.
Solidity code what i wanted:
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
Python code which produces the same result:
encoded_internal_data = abi.encode(['address', 'address', 'uint24'], (token0, token1, fee))
key_hash = web3.solidityKeccak(['bytes'], [encoded_internal_data])
encoded_full_data = encode_abi_packed(
["bytes1", "address", "bytes", "bytes"],
(HexBytes('ff'), UNISWAPV3_FACTORY_ADDRESS, key_hash, HexBytes(UNISWAPV3_POOL_INIT_CODE_HASH))
)
pair_address = web3.solidityKeccak(['bytes'], [encoded_full_data])[12:].hex()
I'm trying to make a simple python script to ping all devices in my company, but I stuck in pinging between two networks: 192.168.0.x and 192.168.10.x
Is there a way to ping addresses in 192.168.10.x from 192.168.0.x without making changes in LAN configuration?
from pythonping import ping
ips = ['192.168.0.88', '192.168.0.253', '192.168.0.182', '192.168.0.9', '192.168.0.1', '192.168.10.10',
'192.168.10.5']
def check_by_ping(ip=[]):
ret = []
for ip in ips:
p = ping(ip, count=1)
if p.rtt_max_ms == 2000:
ret.append([ip, False])
print('Wynik: ', ip, ' = ', 'Nieosiągalne!!!')
else:
ret.append([ip, p.rtt_max_ms])
print('Wynik: ', ip, ' = ', p.rtt_max_ms)
return ret
c = 0
while c<100:
print('\n Test nr: ',c,'\n')
check_by_ping(ips)
c += 1
I'm trying to parse question field in a DNS packet where I can read domain and DNS response from a DNS server. I can extract a DNS header, but I'm having trouble to parse the question field because the size of the data is unknown.
I follow this example, but the part of extracting the question field is not working.
What I need is someone to show me the way to do it properly.
I have this code where everything is right...
This is my code:
#!/usr/bin/env python3
from socket import *
import struct
import binascii
def ethernet_frame(raw_data):
mac_dest, mac_src, protocol = struct.unpack('! 6s 6s H',
raw_data[:14])
return byte_to_hex_mac(mac_dest), byte_to_hex_mac(mac_src),
htons(protocol), raw_data[14:]
def byte_to_hex_mac(mac_bytes):
addr = binascii.hexlify(mac_bytes).decode("ascii")
return ":".join([addr[i:i+2] for i in range(0,12,2)])
def data_packet_udp(data):
tuple_data_udp = struct.unpack('! H H H H', data[:8])
port_src = tuple_data_udp[0]
port_dest = tuple_data_udp[1]
udp_len = tuple_data_udp[2]
udp_checksum = tuple_data_udp[3]
return port_src, port_dest, udp_len, udp_checksum, data[8:]
def data_packet_ipv4(data):
tuple_data_ipv4 = struct.unpack("!BBHHHBBH4s4s", data[:20])
version = tuple_data_ipv4[0]
header_len = version >> 4
type_service = tuple_data_ipv4[1]
length_total = tuple_data_ipv4[2]
identification = tuple_data_ipv4[3]
offset_fragment = tuple_data_ipv4[4]
ttl = tuple_data_ipv4[5]
protocols = tuple_data_ipv4[6]
checksum_header = tuple_data_ipv4[7]
ip_src = inet_ntoa(tuple_data_ipv4[8])
ip_dest = inet_ntoa(tuple_data_ipv4[9])
length_header_bytes = (version & 15) * 4
return version, header_len, type_service, + \
length_total, identification, offset_fragment, + \
ttl, protocols, checksum_header, ip_src, ip_dest,
data[length_header_bytes:]
def data_packet_dns(data):
tuple_data_dns = struct.unpack('!HHHHHH', data[:12])
identification = tuple_data_dns[0]
flags = tuple_data_dns[1]
number_queries = tuple_data_dns[2]
number_response = tuple_data_dns[3]
number_authority = tuple_data_dns[4]
number_additional = tuple_data_dns[5]
qr = (flags & 32768) != 0
opcode = (flags & 30720 ) >> 11
aa = (flags & 1024) != 0
tc = (flags & 512) != 0
rd = (flags & 256) != 0
ra = (flags & 128) != 0
z = (flags & 112) >> 4
rcode = flags & 15
return identification, flags, number_queries, number_response, + \
number_authority, number_additional, qr, opcode, aa, tc, + \
rd, ra, z, rcode
sock = socket(AF_PACKET, SOCK_RAW, ntohs(0x0003))
while True:
raw_dados, addr = sock.recvfrom(65536)
mac_dest, mac_src, protocol, payload = ethernet_frame(raw_dados)
if protocol == 8:
( version, header_len, type_service,
length_total, identification, offset_fragment,
ttl, protocols, checksum_header,
ip_src, ip_dest, data ) = data_packet_ipv4(payload)
if protocols == 17:
port_src, port_dest, udp_len, udp_checksum, data =
data_packet_udp(data)
print("--------- HEADER UDP ----------")
print("Port Source : {}".format(port_src))
print("Port Dest : {}".format(port_dest))
print("UDP Length : {}".format(udp_len))
print("UDP Checksum : {}\n".format(udp_checksum))
if port_src == 53 or port_dest == 53:
(identification, flags, number_queries, \
number_response,number_authority,number_additional, \
qr, opcode, aa, tc, rd, ra, z, rcode) = data_packet_dns(data)
print("\t--------- HEADER DNS ----------")
print("\tidentification : {}".format(identification))
print("\tFlags : {}".format(flags))
print("\tnumber_queries : {}".format(number_queries))
print("\tnumber_response : {}".format(number_response))
print("\tnumber_authority : {}".format(number_authority))
print("\tnumber_additional : {}".format(number_additional))
print("\tQr : {}".format(qr))
print("\tOpcode : {}".format(opcode))
print("\tAA : {}".format(aa))
print("\tTC : {}".format(tc))
print("\tRD : {}".format(rd))
print("\tRA : {}".format(ra))
print("\tZ : {}".format(z))
print("\tRCODE : {}".format(rcode))
I want to get the result of nmcli (linux) in a 3D list in python.
The sample output of nmcli device show is
GENERAL.DEVICE: wlan0
GENERAL.TYPE: wifi
GENERAL.HWADDR: :::::
GENERAL.MTU: 1500
GENERAL.STATE: 100 (connected)
GENERAL.CONNECTION:
GENERAL.CON-PATH: /org/freedesktop/NetworkManager/ActiveConnection/2
IP4.ADDRESS[1]: 192.168.1.106/16
IP4.GATEWAY: 192.168.1.1
IP4.ROUTE[1]: dst = 0.0.0.0/0, nh = 192.168.1.1, mt = 600
IP4.ROUTE[2]: dst = 192.168.0.0/16, nh = 0.0.0.0, mt = 600
IP4.DNS[1]: 192.168.1.1
IP6.ADDRESS[1]: :::::::/
IP6.ADDRESS[2]: :::::/
IP6.GATEWAY: :::::
IP6.ROUTE[1]: dst = :::::/, nh = ::, mt = 600
IP6.ROUTE[2]: dst = ::/0, nh = fe80::30ae:bfff:fe20:64d, mt = 600
IP6.ROUTE[3]: dst = ::/, nh = ::, mt = 256, table=255
IP6.ROUTE[4]: dst = ::/, nh = ::, mt = 256
IP6.ROUTE[5]: dst = ::/, nh = ::, mt = 600
IP6.DNS[1]: :::::
IP6.DNS[2]: :::::::
GENERAL.DEVICE: eth0
GENERAL.TYPE: ethernet
GENERAL.HWADDR: :::::
GENERAL.MTU: 1500
GENERAL.STATE: 20 (unavailable)
GENERAL.CONNECTION: --
GENERAL.CON-PATH: --
WIRED-PROPERTIES.CARRIER: off
GENERAL.DEVICE: lo
GENERAL.TYPE: loopback
GENERAL.HWADDR: 00:00:00:00:00:00
GENERAL.MTU: 65536
GENERAL.STATE: 10 (unmanaged)
GENERAL.CONNECTION: --
GENERAL.CON-PATH: --
IP4.ADDRESS[1]: 127.0.0.1/8
IP4.GATEWAY: --
IP6.ADDRESS[1]: ::1/128
IP6.GATEWAY: --
As you can see there are three interfaces : wlan0 , eth0 and lo.
I want a list of columns in a list of rows in a list of interfaces (3D).
I used subprocess to get the result
r1 = subprocess.run(['nmcli', 'device', 'show'], stdout=subprocess.PIPE)
r2 = [y.split() for y in [z.split('\n') for z in r1.split('\n\n')]]
But I get the following error
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcom>
AttributeError: 'list' object has no attribute 'split'
Any suggestions?
PS: I ran that on python 3.6.3 shell
The result of [z.split('\n') for z in r1.split('\n\n')] is a list of lists, so when you iterate over it you are trying to split a list instead of a string. The error is in y.split().
I think what you want is:
r2 = [[y.split() for y in z.split('\n')] for z in r1.split('\n\n')]
I'd like to make a very simple text (.txt) file. This python program needs to make a list of multiple ranges of IPs in a subnet, each taking up one line.
Example:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.51
10.10.27.52
10.10.27.53
10.10.27.54
The subnet mask will essentially always be a /24, so providing mask input is not necessary. The program can even default to only supporting a standard class C.
Also, I'd like to support common ranges for devices that we use. A prompt for say, "Printers?" will include .26 - .30. "Servers?" will include .5 - .7. "DHCP?" prompt always will include .51 - .100 of the subnet. "Abnormal?" will include .100 - .254.
Subnet? 10.10.27.1
Servers? Y
Printers? Y
DHCP? Y
Abnormal? N
Output being:
10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.7
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.30
10.10.27.51 (all the way to .100)
What is the best way to code this?
It looks like a few for loops are all you need:
network = '10.10.27'
for host in xrange(100, 255):
print("{network}.{host}".format(**locals()))
I would keep the script simple, just output all addresses as needed :)
def yesno(question):
output = input(question).lower()
if output == 'y':
return True
elif output == 'n':
return False
else:
print '%r is not a valid response, only "y" and "n" are allowed.' % output
return yesno(question)
addresses = []
subnet = input('Subnet? ')
# Remove the last digit and replace it with a %d for formatting later
subnet, address = subnet.rsplit('.', 1)
subnet += '%d'
addresses.append(int(address))
if yesno('Servers? '):
addresses += range(5, 8)
if yesno('Printers? '):
addresses += range(26, 31)
if yesno('DHCP? '):
addresses += range(51, 101)
if yesno('Abnormal? '):
addresses += range(100, 255)
for address in addresses:
print subnet % address
Here is a quick little script I threw together...
import socket
import sys
ranges = {'servers':(5, 8), 'printers':(26, 31), 'dhcp':(51, 101), 'abnormal':(101, 256)}
subnet = raw_input("Subnet? ")
try:
socket.inet_aton(subnet)
except socket.error:
print "Not a valid subnet"
sys.exit(1)
ip_parts = subnet.split(".")
if len(ip_parts) < 3:
print "Need at least three octets"
sys.exit(1)
ip_parts = ip_parts[:3]
ip = ".".join(ip_parts)
include_groups = []
last_octets = []
servers = raw_input("Servers? ")
printers = raw_input("Printers? ")
dhcp = raw_input("DHCP? ")
abnormal = raw_input("Abnormal? ")
if servers == "Y":
include_groups.append('servers')
if printers == "Y":
include_groups.append('printers')
if dhcp == "Y":
include_groups.append('dhcp')
if abnormal == "Y":
include_groups.append('abnormal')
for group in include_groups:
last_octets.extend([x for x in xrange(ranges[group][0], ranges[group][1])])
print "%s.1" %(ip)
for octet in last_octets:
print "%s.%s" %(ip, octet)