How to get only COMx in Serial.Tools.List (Python)? - python

I created a program, which sorts all connected Devices (Serials). I only want the List to get COMx Ports instead of their description.
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
List1 = []
for port in sorted(ports):
List1.append(port)
print(*List1)
It always shows the description too, and i don't know what to do?
Can anyone help me to solve this problem? Any Ideas?
I also read the pyserial documentation and tried to divide results into port, desc, hwid, didn't work...

If you are on Windows, you will be able to list only the COM port names with one of the following:
List1.append(port.name)
or
List1.append(port.device)
If you stick to the string named COMx, you can change comports() to:
ports = serial.tools.list_ports.grep("COM[1-9][0-9]*")
serial.tools.list_ports
classserial.tools.list_ports.ListPortInfo
device
Full device name/path, e.g. /dev/ttyUSB0. This is also the information returned as first element when accessed by index.
name
Short device name, e.g. ttyUSB0.

Related

Split a list of results from devcon in python

I'm writing a python script where I'm trying to gather a list device connected via USB with the goal of removing the USB ports so I can readd them guaranteeing a specific cable is COM3. I have a batch file that does this, however I need to add more functionality than the batch file can handle.
list = []
#This section finds all connected USB ports and works
ports = subprocess.run("devcon FindAll =ports", stdout=subprocess.PIPE).stdout.splitlines()
for x in ports:
list.append(x.decode('utf-8'))
#This section splits the results from above and places them in a list
print(list[0])
cmd_0 = str('devcon remove #\\" + list[0])
list2 = [cmd_0.split(" ", 1 [1] for item in list]
print(cmd_0)
when I run the code I get the following result:
**devcon remove #usb\ACPI\PNP0501\0** : Communications Port (COM1)
What I can't figure out is how to get rid of everything after the bold section.
Thanks in advance for the help.
I have tried various methods for splitting the cmd_0 output but can't find the correct method.

Get all FQDN for an IP address in Python

I've the following problem : I'm actually making a script for an ovirt server to automatically delete virtual machine which include unregister them from the DNS. But for some very specific virtual machine there is multiple FQDN for an IP address example:
myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10.10.10
I've tried to do it with socket in Python but it return only one answer, I've also tried python with dnspython but I failed.
the goal is to count the number of type A record on the dns server
Anyone have an idea to do stuff like this?
That's outright impossible. If I am in the right mood, I could add an entry to my DNS server pointing to your IP address. Generally, you cannot find it out (except for some hints in some protocols like http(s)).
Given a zone file in the above format, you could do something like...
from collections import defaultdict
zone_file = """myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10.10.10"""
# Build mapping for lookups
ip_fqdn_mapping = defaultdict(list)
for record in zone_file.split("\n"):
fqdn, record_class, record_type, ip_address = record.split()
ip_fqdn_mapping[ip_address].append(fqdn)
# Lookup
ip_address_to_lookup = "10.10.10.10"
fqdns = ip_fqdn_mapping[ip_address_to_lookup]
print(fqdns)
Note: Using socket can be done like so - Python lookup hostname from IP with 1 second timeout
However this does require that DNS server that you are querying has correctly configured PTR reverse records.
https://www.cloudns.net/wiki/article/40/

interfaces eth0 nothing en0 list error for mac os

import netifaces as ni
ip = ni.ifaddresses("eth0")[ni.AF_INET]['addr']
error
ip = ni.ifaddresses("eth0")[ni.AF_INET]['addr']
ValueError: You must specify a valid interface name.
ip = ni.ifaddresses("en0")[ni.AF_INET]['addr']
error
ip = ni.ifaddresses("en0")[ni.AF_INET]['addr']
TypeError: list indices must be integers or slices, not str
Does anyone know why the mac is giving such errors?
The first error means that there is no interface named eth0. Indeed, this is a common interface name on Linux, but not on MacOS.
The second error means that you are trying to extract a field which doesn't exist. There is information about en0 but it is an array, not a dict. This is like saying "hello"["addr"], there is no way to access the "addr":th element of a sequence. You apparently mean something like
ip = ni.ifaddresses("en0")[ni.AF_INET][0]['addr']
though there is no way out of context to tell whether getting only one address is actually what you want. The array you get represents a number of bindings; perhaps you want all of them?
addrs = ni.ifaddresses('en0')
ips = [x['addr'] for x in addrs[ni.AF_INET]]
The netifaces documentation actually explains this in quite some detail.

Python compare two lists of IPs and return the lowest to 0 IP entry in list?

I have managed to compile two lists of IP addresses. used and unused ips as such
unused_ips = ['172.16.100.0/32', '172.16.100.1/32', '172.16.100.2/32', '172.16.100.3/32', '172.16.100.4/32', '172.16.100.5/32', '172.16.100.6/32', '172.16.100.7/32', '172.16.100.8/32', '172.16.100.9/32'...]
used_ips = ['172.16.100.1/32','172.16.100.33/32']
what I want to be able to do now is compare these lists and return the next free IP. in the above example the next ip would be 172.16.100.2/32, until it handed out all of those from 1 to 32 then it would hand out 34.
im not sure where to begin with this, I can convert these to IPv4Network objects if there is something built in for this but I couldn't find anything in documentation
Thanks
I'd keep a set of ipaddress objects and manipulate them to allocate and de-allocate the addresses, like so:
import ipaddress
def massage_ip_lists():
global unused_ips, used_ips
unused_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
for ip in unused_ips)
used_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
for ip in used_ips)
def allocate_next_ip():
new_ip = min(unused_ips - used_ips)
used_ips.add(new_ip)
return new_ip
unused_ips = [
'172.16.100.0/32',
'172.16.100.1/32',
'172.16.100.2/32',
'172.16.100.3/32',
'172.16.100.4/32',
'172.16.100.5/32',
'172.16.100.6/32',
'172.16.100.7/32',
'172.16.100.8/32',
'172.16.100.9/32']
used_ips = ['172.16.100.1/32', '172.16.100.33/32']
massage_ip_lists()
print(allocate_next_ip())
print(allocate_next_ip())
Note:
/32 is a nomenclature for IP networks, not IP hosts.
ipaddress objects are comparable, so functions like min() work on them.
172.16.100.0 is a perfectly valid IP address, depending upon the netmask. If you don't want to allocate it, either keep it out of unused_ips, or make the program aware of the netmask in use.
You want ips that are in unused but not used:
available_ips = [ip for ip in unused_ips if ip not in used_ips]
You want to sort them to get the one that's closest to zero. Naive sorting will not work as you have strings; 172.16.xxx.xxx is sorted higher than 172.100.xxx.xxx for example. You can convert the IPs into lists of numbers to sort them correctly.
import re
available_ips = sorted(available_ips, key=lambda ip: (int(n) for n in re.split(r'[./]', ip)))
If you're just trying to iterate through a list of the available ips, you could do something like this:
# Filter unavailable ips from the list of all ips
available_ips = set(unused_ips) - set(used_ips)
# Iterate through list of available ips
for ip in available_ips:
print(ip) # Or whatever you want to do with the next available ip

Python and Netbios

I have been toying with a few ideas and would like to use Netbios to do some checks on the network. So after some research decided pysmb's nmb.Netbios was a good place to start.
I have constructed a simple queryName function that I was hoping would return an ip address. But it seems after checking some wireshark pcap dumps it isnt even broadcasting.
Ive found an example in the pysmb docs but that doesnt seem to broadcast either. Below is my test function, any pointers would be appreciated.
from nmb.NetBIOS import NetBIOS
def queryNam(name):
n = NetBIOS(broadcast=True, listen_port=0)
ip = n.queryName(name, timeout=30)
return ip
name = "Computer-Name"
ip = queryNam(name)
print ip
I worked out the issue myself. Initially I wasnt using the correct computername as NetBios Broadcasts seem to broadcast the name in uppercase. I was presenting a lowercase so the system was not responding.
So supplying the value in uppercase resolved the problem. (Even though a hostname check on the client showed an Uppercase followed by lowercase characters.

Categories

Resources