Python get instance address

Python get local address

22 Python code examples are found related to » get local address «. You can vote up the ones you like or vote down the ones you don’t like, and go to the original project or source file by following the links above each example.

Source File: ip.py From zstack-utility with Apache License 2.0 6 votes
def get_link_local_address(mac): ''' get ipv6 link local address from 48bits mac address, details are described at the https://tools.ietf.org/html/rfc4291#section-2.5.1 for example mac address 00:01:02:aa:bb:cc step 1. inverting the universal/local bit of mac address to 02:01:02:0a:0b:0c step 2. insert fffe in the middle of mac address to 02:01:02:ff:fe:0a:0b:0c step 3. convert to ip address with fe80::/64, strip the leading '0' in each sector between ':' fe80::201:2ff:fe0a:b0c ''' macs = mac.strip("\n").split(":") # step 1. inverting the "u" bit of mac address macs[0] = hex(int(macs[0], 16) ^ 2)[2:] # step 2, insert "fffe" part1 = macs[0] + macs[1] + ":" part2 = macs[2] + "ff" + ":" part3 = "fe" + macs[3] + ":" part4 = macs[4] + macs[5] #step 3 return "fe80::" + part1.lstrip("0") + part2.lstrip("0") + part3.lstrip("0") + part4.lstrip("0")
Source File: __init__.py From smarthome with GNU General Public License v3.0 6 votes
def get_local_ipv4_address(): """ Get's local ipv4 address of the interface with the default gateway. Return '127.0.0.1' if no suitable interface is found :return: IPv4 address as a string :rtype: string """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('8.8.8.8', 1)) IP = s.getsockname()[0] except: IP = '127.0.0.1' finally: s.close() return IP
Source File: hostingdrivermanager.py From opsbro with MIT License 6 votes
def get_local_address(self): # If I am in the DNS or in my /etc/hosts, I win try: addr = socket.gethostbyname(socket.gethostname()) if self._is_valid_local_addr(addr): return addr except Exception as exp: pass if sys.platform.startswith('linux'): # linux2 for python2, linux for python3 addrs = self._get_linux_local_addresses() if len(addrs) > 0: return addrs[0] # On windows also loop over the interfaces if os.name == 'nt': c = windowser.get_wmi() for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): for addr in interface.IPAddress: if self._is_valid_local_addr(addr): return addr return None # If we are not in a cloud or something, our public == best local address
Source File: utils.py From smarthome with GNU General Public License v3.0 6 votes
def get_local_ipv6_address(): """ Get's local ipv6 address TODO: What if more than one interface present ? :return: IPv6 address as a string :rtype: string """ try: s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) s.connect(('2001:4860:4860::8888', 1)) IP = s.getsockname()[0] except: IP = '::1' finally: if 's' in locals(): s.close() return IP
Source File: device.py From balena-sdk-python with Apache License 2.0 6 votes
def get_local_ip_address(self, uuid): """ Get the local IP addresses of a device. Args: uuid (str): device uuid. Returns: list: IP addresses of a device. Raises: DeviceNotFound: if device couldn't be found. DeviceOffline: if device is offline. """ if self.is_online(uuid): device = self.get(uuid) return list(set(device['ip_address'].split()) - set(device['vpn_address'].split())) else: raise exceptions.DeviceOffline(uuid)
Source File: aliddns.py From aliddns with MIT License 6 votes
def get_Local_ipv6_address_win(): """ Get local ipv6 """ # pageURL = 'https://ip.zxinc.org/ipquery/' # pageURL = 'https://ip.sb/' pageURL = 'https://api-ipv6.ip.sb/ip' content = urllib.request.urlopen(pageURL).read() webContent = content.decode("utf8") print(webContent) ipv6_pattern = '(([a-f0-9]:)[a-f0-9])' m = re.search(ipv6_pattern, webContent) if m is not None: return m.group() else: return None
Source File: aliddns.py From aliddns with MIT License 6 votes
def get_Local_ipv6_address_win2(): """ Get local ipv6 """ # pageURL = 'https://ip.zxinc.org/ipquery/' linelist = os.popen(''' ipconfig ''').readlines() webContent = "" for item in linelist: webContent += item print(linelist) ipv6_pattern = '(([a-f0-9]:)[a-f0-9])' m = re.search(ipv6_pattern, webContent) if m is not None: return m.group() else: return None
Source File: aliddns.py From aliddns with MIT License 6 votes
def get_Local_ipv6_address_linux(): """ Get local ipv6 """ # pageURL = 'https://ip.zxinc.org/ipquery/' # pageURL = 'https://ip.sb/' linelist = os.popen( ''' ip addr show eth0 | grep "inet6.*global" | awk \'\' | awk -F"/" \'\' ''').readlines() # 这个返回值是一个list if linelist: content = linelist[0].strip() else: return None ipv6_pattern = '(([a-f0-9]:)[a-f0-9])' m = re.search(ipv6_pattern, content) if m is not None: return m.group() else: return None
Source File: compat_interface.py From pfp with MIT License 5 votes
def ProcessGetHeapLocalAddress(params, ctxt, scope, stream, coord): raise NotImplementedError() # wchar_t[] ProcessGetHeapModule( int index )
Source File: context.py From mars with Apache License 2.0 5 votes
def get_local_address(self): """ Get local address :return: local address """ raise NotImplementedError
Source File: collect-hadoop-metrics.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 5 votes
def get_local_address_on_emr(): """ Gets the local/private IPv4 address of this instance, assuming we're on AWS. """ return query_metadata_service('local-ipv4')
Source File: spawner.py From cloudJHub with BSD 3-Clause «New» or «Revised» License 5 votes
def get_local_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] s.close() return ip_address
Source File: net.py From pyatv with MIT License 5 votes
def get_local_address_reaching(dest_ip: IPv4Address) -> Optional[IPv4Address]: """Get address of a local interface within same subnet as provided address.""" for iface in netifaces.interfaces(): for addr in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []): iface = IPv4Interface(addr["addr"] + "/" + addr["netmask"]) if dest_ip in iface.network: return iface.ip return None
Source File: mptcp_fragmenter.py From mptcp-abuse with GNU General Public License v2.0 5 votes
def get_local_ip_address(target): """Return the the IP address suitable for the target (ip or host) This appears to be the best cross platform approach using only the standard lib. Better ideas welcome. """ #TODO: handle err if no suitable IP s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((str(target), 8000)) ipaddr = s.getsockname()[0] s.close() return ipaddr
Source File: tftp.py From maas with GNU Affero General Public License v3.0 5 votes
def get_local_address(): """Return the ``(host, port)`` for the local side of a TFTP transfer. This is important on a cluster controller that manages multiple networks. This is populated by ``python-tx-tftp``, and is only available in ``IBackend.get_reader()`` and ``IBackend.get_writer()`` :return: A 2-tuple containing the address and port for the local side of the transfer. """ return extract_address(get("local"))
Source File: alexa_auth.py From AlexaDevice with MIT License 5 votes
def get_local_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("www.amazon.com", 80)) res = s.getsockname()[0] s.close() return res
Source File: PcapAddressOperations.py From ID2T with MIT License 5 votes
def get_local_address_range(self): """ Returns a tuple with the start and end of the observed local IP range. :return: The IP range as tuple """ return str(self.min_local_ip), str(self.max_local_ip)
Source File: addressManager.py From Thespian with MIT License 5 votes
def getLocalAddress(self, instanceNum): 'Returns ActorAddress corresponding to local address instance' ra = ActorAddress(ActorLocalAddress(self._thisActorAddr, instanceNum, self)) ra.eqOverride = types.MethodType(self.compareAddressEq, ra) ra.__getstate__ = types.MethodType(_pickle_if_translation, ra) return ra
Source File: __init__.py From smarthome with GNU General Public License v3.0 5 votes
def get_local_ip_address(self): """ Returns the local ip address under which the webinterface can be reached :return: ip address :rtype: str """ return self._ip
Source File: common_utils.py From cotopaxi with GNU General Public License v2.0 5 votes
def get_local_ipv6_address(): """Return IPv6 address of local node.""" sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.connect(("::1", 80)) local_ip = sock.getsockname()[0] sock.close() return local_ip
Source File: comm.py From dask-gateway with BSD 3-Clause «New» or «Revised» License 5 votes
def get_local_address_for(self, loc): host, port, path = parse_gateway_address(loc) host = ensure_ip(host) host = get_ip(host) return "%s:%d/%s" % (host, port, path)
Source File: base.py From scalyr-agent-2 with Apache License 2.0 5 votes
def getLocalAddress(self): # one evil OS does not seem to support getsockname() for DGRAM sockets try: return self.socket.getsockname() except: return ('0.0.0.0', 0) # asyncore API

Источник

Читайте также:  Java configuration property files

[OCI] Python script to get the IP address of a compute instance in Cloud Shell

This article is about [Writing Python scripts to run from the OCI Console Cloud Shell](https://medium.com/oracledevs/writing-python-scripts-to-run-from-the-oci-console-cloud-shell- This is the execution of the contents of a0be1091384c).

OCI Cloud Shell OCI Cloud Shell is a web browser-based Shell terminal accessible from the OCI web console. Cloud Shell has the following features:

—Pre-authenticated OCI CLI —No configuration required to start using CLI in Cloud Shell —A complete Linux shell with key developer tools to interact with Oracle Cloud Infrastructure services and a pre-installed language runtime —OCI SDK and Oracle Instant Client for each language —5 GB storage for home directory —You can save your work between Cloud Shell sessions —Console persistent frames that remain active when navigating to different pages of the console

Compute instance IP address acquisition script example)

list_ipaddress.py

 #!/usr/bin/env python import oci delegation_token = open('/etc/oci/delegation_token', 'r').read() signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner( delegation_token=delegation_token ) search_client = oci.resource_search.ResourceSearchClient(<>,signer=signer) compute_client = oci.core.ComputeClient(<>,signer=signer) network_client = oci.core.VirtualNetworkClient(<>,signer=signer) resp = search_client.search_resources( oci.resource_search.models.StructuredSearchDetails( type="Structured", query="query instance resources" ) ) for instance in resp.data.items: resp = compute_client.list_vnic_attachments( compartment_id=instance.compartment_id, instance_id=instance.identifier ) for vnic_attachment in resp.data: vnic = network_client.get_vnic(vnic_attachment.vnic_id).data print("\t".join([ instance.display_name, vnic.display_name, vnic.private_ip, vnic.public_ip ])) 

Execution example

$ python ./list_ipaddress.py fmwf fmwf 10.0.0.4 150.136.236.XXX db01 db01 10.0.0.3 150.136.37.XXX gpu01 gpu01 10.0.0.5 150.136.89.XXX fn fn 10.0.0.2 158.101.118.XXX 

Script supplement

singer When writing a Python script that runs inside the Cloud Shell, you can use the existing authentication of the Cloud Shell. You can omit the separate API key settings required to run the script. Load an existing instance principal delegation token and generate a signer.

#!/usr/bin/env python import oci delegation_token = open('/etc/oci/delegation_token', 'r').read() signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner( delegation_token=delegation_token ) 

Create an authenticated client

Search for all instances in the current region Inquire about instance details and get an IP address API client definition

search_client = oci.resource_search.ResourceSearchClient(<>,signer=signer) compute_client = oci.core.ComputeClient(<>,signer=signer) network_client = oci.core.VirtualNetworkClient(<>,signer=signer) 

Get an IP address

Find all attached vnics for each instance Get both public and private IP addresses for each vnic

for instance in resp.data.items: resp = compute_client.list_vnic_attachments( compartment_id=instance.compartment_id, instance_id=instance.identifier ) for vnic_attachment in resp.data: vnic = network_client.get_vnic(vnic_attachment.vnic_id).data print("\t".join([ instance.display_name, vnic.display_name, vnic.private_ip, vnic.public_ip ])) 

Reference information

Источник

Оцените статью