change ff to unix

This commit is contained in:
S Groesz 2020-09-26 22:05:06 +00:00
parent 34e1ad1e39
commit fbfb32f8b1
2 changed files with 427 additions and 427 deletions

View File

@ -1,70 +1,70 @@
import socket import socket
import struct import struct
import array import array
import sys import sys
IOCTL_SIOCGIFCONF = 0x8912 IOCTL_SIOCGIFCONF = 0x8912
# /* # /*
# * Structure used in SIOCGIFCONF request. # * Structure used in SIOCGIFCONF request.
# * Used to retrieve interface configuration # * Used to retrieve interface configuration
# * for machine (useful for programs which # * for machine (useful for programs which
# * must know all networks accessible). # * must know all networks accessible).
# */ # */
# #
# struct ifconf { # struct ifconf {
# int ifc_len; /* size of associated buffer */ # int ifc_len; /* size of associated buffer */
# union { # union {
# caddr_t ifcu_buf; # caddr_t ifcu_buf;
# struct ifreq *ifcu_req; # struct ifreq *ifcu_req;
# } ifc_ifcu; # } ifc_ifcu;
# #
# /* # /*
# * Interface request structure used for socket # * Interface request structure used for socket
# * ioctl's. # * ioctl's.
# */ # */
# #
# struct ifreq { # struct ifreq {
# char ifr_name[16]; /* if name, e.g. "en0" */ # char ifr_name[16]; /* if name, e.g. "en0" */
# union { # union {
# struct sockaddr ifru_addr; # struct sockaddr ifru_addr;
# struct sockaddr ifru_dstaddr; # struct sockaddr ifru_dstaddr;
# struct sockaddr ifru_broadaddr; # struct sockaddr ifru_broadaddr;
# short ifru_flags; # short ifru_flags;
# int ifru_metric; # int ifru_metric;
# caddr_t ifru_data; # caddr_t ifru_data;
# } ifr_ifru; # } ifr_ifru;
# #
# #
# /* Socket address, DARPA Internet style */ # /* Socket address, DARPA Internet style */
# struct sockaddr_in { # struct sockaddr_in {
# short sin_family; # short sin_family;
# unsigned short sin_port; # unsigned short sin_port;
# struct in_addr sin_addr; # struct in_addr sin_addr;
# char sin_zero[8]; # char sin_zero[8];
# }; # };
# #
# #
# ioctl (fd, SIOCGIFCONF, &ifconf) # ioctl (fd, SIOCGIFCONF, &ifconf)
def enumIpUnix(): def enumIpUnix():
import fcntl import fcntl
struct_size = 40 if (sys.maxsize > 2**32) else 32 struct_size = 40 if (sys.maxsize > 2**32) else 32
inbytes = 128 * struct_size # Maximum 128 interfaces inbytes = 128 * struct_size # Maximum 128 interfaces
ifreq = array.array('B', b'\0' * inbytes) ifreq = array.array('B', b'\0' * inbytes)
ifconf = struct.pack('iL', inbytes, ifreq.buffer_info()[0]) ifconf = struct.pack('iL', inbytes, ifreq.buffer_info()[0])
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ifconf = fcntl.ioctl(s.fileno(), IOCTL_SIOCGIFCONF, ifconf) ifconf = fcntl.ioctl(s.fileno(), IOCTL_SIOCGIFCONF, ifconf)
outbytes = struct.unpack('iL', ifconf)[0] outbytes = struct.unpack('iL', ifconf)[0]
iplist = [socket.inet_ntoa(ifreq[i+20:i+24]) for i in range(0, iplist = [socket.inet_ntoa(ifreq[i+20:i+24]) for i in range(0,
outbytes, outbytes,
struct_size)] struct_size)]
return [ip for ip in iplist if ip != '127.0.0.1'] return [ip for ip in iplist if ip != '127.0.0.1']

View File

@ -1,357 +1,357 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import getopt import getopt
import socket import socket
import sys import sys
import os import os
import platform import platform
from nfutil import * from nfutil import *
from enumip import * from enumip import *
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
def usage(): def usage():
print print
print "Usage: nfcli --list --eth_addr=ADDR --ip_type=TYPE --ip_addr=IP, --netmask=MASK, --gateway=GW" print "Usage: nfcli --list --eth_addr=ADDR --ip_type=TYPE --ip_addr=IP, --netmask=MASK, --gateway=GW"
print "Search and configure Prologix GPIB-ETHERNET Controllers." print "Search and configure Prologix GPIB-ETHERNET Controllers."
print "--help : display this help" print "--help : display this help"
print "--list : search for controllers" print "--list : search for controllers"
print "--eth_addr=ADDR : configure controller with Ethernet address ADDR" print "--eth_addr=ADDR : configure controller with Ethernet address ADDR"
print "--ip_type=TYPE : set controller ip address type to TYPE (\"static\" or \"dhcp\")" print "--ip_type=TYPE : set controller ip address type to TYPE (\"static\" or \"dhcp\")"
print "--ip_addr=IP : set controller address to IP" print "--ip_addr=IP : set controller address to IP"
print "--netmask=MASK : set controller network mask to MASK" print "--netmask=MASK : set controller network mask to MASK"
print "--gateway=GW : set controller default gateway to GW" print "--gateway=GW : set controller default gateway to GW"
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
def enumIp(): def enumIp():
if platform.system() in ('Windows', 'Microsoft'): if platform.system() in ('Windows', 'Microsoft'):
return socket.gethostbyname_ex(socket.gethostname())[2]; return socket.gethostbyname_ex(socket.gethostname())[2];
return enumIpUnix() return enumIpUnix()
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
def ValidateNetParams(ip_str, mask_str, gw_str): def ValidateNetParams(ip_str, mask_str, gw_str):
try: try:
ip = socket.inet_aton(ip_str) ip = socket.inet_aton(ip_str)
except: except:
print "IP address is invalid." print "IP address is invalid."
return False return False
try: try:
mask = socket.inet_aton(mask_str) mask = socket.inet_aton(mask_str)
except: except:
print "Network mask is invalid." print "Network mask is invalid."
return False return False
try: try:
gw = socket.inet_aton(gw_str) gw = socket.inet_aton(gw_str)
except: except:
print "Gateway address is invalid." print "Gateway address is invalid."
return False return False
# Validate network mask # Validate network mask
# Convert to integer from byte array # Convert to integer from byte array
mask = struct.unpack("!L", mask)[0] mask = struct.unpack("!L", mask)[0]
# Exclude restricted masks # Exclude restricted masks
if (mask == 0) or (mask == 0xFFFFFFFF): if (mask == 0) or (mask == 0xFFFFFFFF):
print "Network mask is invalid." print "Network mask is invalid."
return False return False
# Exclude non-left-contiguous masks # Exclude non-left-contiguous masks
if (((mask + (mask & -mask)) & 0xFFFFFFFF) != 0): if (((mask + (mask & -mask)) & 0xFFFFFFFF) != 0):
print "Network mask is not contiguous." print "Network mask is not contiguous."
return False return False
# Validate gateway address # Validate gateway address
octet1 = ord(gw[0]) octet1 = ord(gw[0])
# Convert to integer from byte array # Convert to integer from byte array
gw = struct.unpack("!L", gw)[0] gw = struct.unpack("!L", gw)[0]
# Exclude restricted addresses # Exclude restricted addresses
# 0.0.0.0 is valid # 0.0.0.0 is valid
if ((gw != 0) and ((octet1 == 0) or (octet1 == 127) or (octet1 > 223))): if ((gw != 0) and ((octet1 == 0) or (octet1 == 127) or (octet1 > 223))):
print "Gateway address is invalid." print "Gateway address is invalid."
return False return False
# Validate IP address # Validate IP address
octet1 = ord(ip[0]) octet1 = ord(ip[0])
# Convert to integer from byte array # Convert to integer from byte array
ip = struct.unpack("!L", ip)[0] ip = struct.unpack("!L", ip)[0]
# Exclude restricted addresses # Exclude restricted addresses
if ((octet1 == 0) or (octet1 == 127) or (octet1 > 223)): if ((octet1 == 0) or (octet1 == 127) or (octet1 > 223)):
print "IP address is invalid." print "IP address is invalid."
return False return False
# Exclude subnet network address # Exclude subnet network address
if ((ip & ~mask) == 0): if ((ip & ~mask) == 0):
print "IP address is invalid." print "IP address is invalid."
return False return False
# Exclude subnet broadcast address # Exclude subnet broadcast address
if ((ip & ~mask) == (0xFFFFFFFF & ~mask)): if ((ip & ~mask) == (0xFFFFFFFF & ~mask)):
print "IP address is invalid." print "IP address is invalid."
return False return False
return True return True
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
#def ValidateAddress(address): #def ValidateAddress(address):
# if address is None: # if address is None:
# return False # return False
# parts = address.split(".") # parts = address.split(".")
# if len(parts) != 4: # if len(parts) != 4:
# return False # return False
# try: # try:
# for item in parts: # for item in parts:
# if not 0 <= int(item) <= 255: # if not 0 <= int(item) <= 255:
# return False # return False
# except: # except:
# return False # return False
# return True # return True
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
def main(): def main():
invalid_args = False invalid_args = False
showhelp = False showhelp = False
search = False search = False
ip_type = None ip_type = None
ip_addr = None ip_addr = None
netmask = None netmask = None
gateway = None gateway = None
eth_addr = None eth_addr = None
try: try:
opts, args = getopt.getopt(sys.argv[1:], '', ['help', 'list', 'eth_addr=', 'ip_type=', 'ip_addr=', 'netmask=', 'gateway=']) opts, args = getopt.getopt(sys.argv[1:], '', ['help', 'list', 'eth_addr=', 'ip_type=', 'ip_addr=', 'netmask=', 'gateway='])
except getopt.GetoptError, err: except getopt.GetoptError, err:
print str(err) print str(err)
sys.exit(1) sys.exit(1)
# Check for unparsed parameters # Check for unparsed parameters
if len(args) != 0: if len(args) != 0:
usage() usage()
sys.exit(1) sys.exit(1)
for o, a in opts: for o, a in opts:
if o == "--help": if o == "--help":
showhelp = True showhelp = True
elif o == "--list": elif o == "--list":
search = True search = True
elif o == "--eth_addr": elif o == "--eth_addr":
eth_addr = a eth_addr = a
elif o == "--ip_type": elif o == "--ip_type":
ip_type = a ip_type = a
elif o == "--ip_addr": elif o == "--ip_addr":
ip_addr = a ip_addr = a
elif o == "--netmask": elif o == "--netmask":
netmask = a netmask = a
elif o == "--gateway": elif o == "--gateway":
gateway = a gateway = a
if (len(opts) == 0) or (showhelp): if (len(opts) == 0) or (showhelp):
usage() usage()
sys.exit(1) sys.exit(1)
if search: if search:
if not eth_addr is None: if not eth_addr is None:
print "--list and --eth_addr are not compatible." print "--list and --eth_addr are not compatible."
invalid_args = True invalid_args = True
if not ip_type is None: if not ip_type is None:
print "--list and --ip_type are not compatible." print "--list and --ip_type are not compatible."
invalid_args = True invalid_args = True
if not ip_addr is None: if not ip_addr is None:
print "--list and --ip_addr are not compatible." print "--list and --ip_addr are not compatible."
invalid_args = True invalid_args = True
if not netmask is None: if not netmask is None:
print "--list and --netmask are not compatible." print "--list and --netmask are not compatible."
invalid_args = True invalid_args = True
if not gateway is None: if not gateway is None:
print "--list and --gateway are not compatible." print "--list and --gateway are not compatible."
invalid_args = True invalid_args = True
else: else:
try: try:
eth_addr = eth_addr.strip().replace(":", "").replace("-", "") eth_addr = eth_addr.strip().replace(":", "").replace("-", "")
eth_addr = eth_addr.decode('hex') eth_addr = eth_addr.decode('hex')
except: except:
print "Invalid Ethernet address." print "Invalid Ethernet address."
sys.exit(1) sys.exit(1)
if len(eth_addr) != 6: if len(eth_addr) != 6:
print "Invalid Ethernet address." print "Invalid Ethernet address."
sys.exit(1) sys.exit(1)
if ip_type in ["Static", "static"]: if ip_type in ["Static", "static"]:
ip_type = NF_IP_STATIC ip_type = NF_IP_STATIC
elif ip_type in ["Dynamic", "dynamic", "Dhcp", "dhcp"]: elif ip_type in ["Dynamic", "dynamic", "Dhcp", "dhcp"]:
ip_type = NF_IP_DYNAMIC ip_type = NF_IP_DYNAMIC
else: else:
print "--ip_type must be 'static' or 'dhcp'." print "--ip_type must be 'static' or 'dhcp'."
sys.exit(1) sys.exit(1)
if ip_type == NF_IP_STATIC: if ip_type == NF_IP_STATIC:
if not ValidateNetParams(ip_addr, netmask, gateway): if not ValidateNetParams(ip_addr, netmask, gateway):
invalid_args = True invalid_args = True
# if not ValidateIP(ip_addr): # if not ValidateIP(ip_addr):
# print "Invalid, or no, IP address specified." # print "Invalid, or no, IP address specified."
# invalid_args = True # invalid_args = True
# if not ValidateIP(netmask): # if not ValidateIP(netmask):
# print "Invalid, or no, netmask specified." # print "Invalid, or no, netmask specified."
# invalid_args = True # invalid_args = True
# if not ValidateIP(gateway): # if not ValidateIP(gateway):
# print "Invalid, or no, gateway address specified." # print "Invalid, or no, gateway address specified."
# invalid_args = True # invalid_args = True
else: else:
if ip_addr is None: if ip_addr is None:
ip_addr = "0.0.0.0" ip_addr = "0.0.0.0"
else: else:
print "--ip_addr not allowed when --ip_type=dhcp." print "--ip_addr not allowed when --ip_type=dhcp."
invalid_args = True invalid_args = True
if netmask is None: if netmask is None:
netmask = "0.0.0.0" netmask = "0.0.0.0"
else: else:
print "--netmask not allowed when --ip_type=dhcp." print "--netmask not allowed when --ip_type=dhcp."
invalid_args = True invalid_args = True
if gateway is None: if gateway is None:
gateway = "0.0.0.0" gateway = "0.0.0.0"
else: else:
print "--gateway not allowed when --ip_type=dhcp." print "--gateway not allowed when --ip_type=dhcp."
invalid_args = True invalid_args = True
if invalid_args: if invalid_args:
sys.exit(1) sys.exit(1)
global seq global seq
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
iplist = enumIp(); iplist = enumIp();
if len(iplist) == 0: if len(iplist) == 0:
print "Host has no IP address." print "Host has no IP address."
sys.exit(1) sys.exit(1)
devices = {} devices = {}
for ip in iplist: for ip in iplist:
print "Searching through network interface:", ip print "Searching through network interface:", ip
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
port = 0 port = 0
try: try:
s.bind((ip, port)) s.bind((ip, port))
except socket.error, e: except socket.error, e:
print "Bind error on send socket:", e print "Bind error on send socket:", e
sys.exit(1) sys.exit(1)
port = s.getsockname()[1] port = s.getsockname()[1]
r = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) r = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
r.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) r.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
r.setblocking(1) r.setblocking(1)
r.settimeout(0.100) r.settimeout(0.100)
try: try:
r.bind(('', port)) r.bind(('', port))
except socket.error, e: except socket.error, e:
print "Bind error on receive socket:", e print "Bind error on receive socket:", e
sys.exit(1) sys.exit(1)
d = Discover(s, r) d = Discover(s, r)
print print
for k in d: for k in d:
d[k]['host_ip'] = ip d[k]['host_ip'] = ip
devices[k] = d[k] devices[k] = d[k]
s.close() s.close()
r.close() r.close()
if search: if search:
print print
print "Found", len(devices), "Prologix GPIB-ETHERNET Controller(s)." print "Found", len(devices), "Prologix GPIB-ETHERNET Controller(s)."
for key in devices: for key in devices:
PrintDetails(devices[key]) PrintDetails(devices[key])
print print
else: else:
if eth_addr in devices: if eth_addr in devices:
print "Updating network settings of Prologix GPIB-ETHERNET Controller", FormatEthAddr(eth_addr) print "Updating network settings of Prologix GPIB-ETHERNET Controller", FormatEthAddr(eth_addr)
device = devices[eth_addr] device = devices[eth_addr]
if (device['ip_type'] == NF_IP_STATIC) or (ip_type == NF_IP_STATIC): if (device['ip_type'] == NF_IP_STATIC) or (ip_type == NF_IP_STATIC):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
port = 0 port = 0
try: try:
s.bind((device['host_ip'], port)) s.bind((device['host_ip'], port))
except socket.error, e: except socket.error, e:
print "Bind error on send socket:", e print "Bind error on send socket:", e
sys.exit(1) sys.exit(1)
port = s.getsockname()[1] port = s.getsockname()[1]
r = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) r = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
r.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) r.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
r.setblocking(1) r.setblocking(1)
r.settimeout(0.100) r.settimeout(0.100)
try: try:
r.bind(('', port)) r.bind(('', port))
except socket.error, e: except socket.error, e:
print "Bind error on receive socket:", e print "Bind error on receive socket:", e
sys.exit(1) sys.exit(1)
result = Assignment(s, r, eth_addr, ip_type, ip_addr, netmask, gateway) result = Assignment(s, r, eth_addr, ip_type, ip_addr, netmask, gateway)
print print
if len(result) == 0: if len(result) == 0:
print "Network settings update failed." print "Network settings update failed."
else: else:
if result['result'] == NF_SUCCESS: if result['result'] == NF_SUCCESS:
print "Network settings updated successfully." print "Network settings updated successfully."
else: else:
print "Network settings update failed." print "Network settings update failed."
else: else:
print "Prologix GPIB-ETHERNET Controller", FormatEthAddr(eth_addr), "already configured for DHCP." print "Prologix GPIB-ETHERNET Controller", FormatEthAddr(eth_addr), "already configured for DHCP."
else: else:
print "Prologix GPIB-ETHERNET Controller", FormatEthAddr(eth_addr), "not found." print "Prologix GPIB-ETHERNET Controller", FormatEthAddr(eth_addr), "not found."
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
if __name__ == "__main__": if __name__ == "__main__":
main() main()