2019-08-17 13:55:58 -07:00
|
|
|
import subprocess
|
|
|
|
|
import netifaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ChangeIP:
|
2019-08-20 21:48:04 +03:00
|
|
|
def __init__(self, connection_type, ip, netmask, gateway, hostname):
|
2019-08-17 13:55:58 -07:00
|
|
|
|
|
|
|
|
adapter = self.find_adapter()
|
2019-08-21 12:49:17 -07:00
|
|
|
if adapter is not None:
|
|
|
|
|
self.shutdown_adapter(adapter)
|
2019-08-17 13:55:58 -07:00
|
|
|
|
2019-08-21 12:49:17 -07:00
|
|
|
if connection_type == "DHCP":
|
|
|
|
|
self.change_to_dhcp(adapter=adapter)
|
2019-08-17 13:55:58 -07:00
|
|
|
|
2019-08-21 12:49:17 -07:00
|
|
|
elif connection_type == "Static":
|
|
|
|
|
self.change_to_static(adapter=adapter, ip=ip, netmask=netmask, gateway=gateway)
|
|
|
|
|
|
|
|
|
|
self.start_adapter(adapter)
|
2019-08-21 23:01:27 +03:00
|
|
|
else:
|
|
|
|
|
print("not connected to robot radio cannot set ip")
|
2019-08-17 13:55:58 -07:00
|
|
|
self.change_hostname(hostname=hostname)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def change_to_dhcp(adapter):
|
2019-08-20 21:48:04 +03:00
|
|
|
subprocess.call(['dhclient',"-r", adapter])
|
2019-08-17 13:55:58 -07:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def change_to_static(adapter, ip, netmask, gateway):
|
|
|
|
|
subprocess.call(['ifconfig', adapter, ip, 'netmask', netmask])
|
2019-08-20 23:10:43 +03:00
|
|
|
subprocess.call(['route', 'add', 'default', 'gw', gateway, adapter])
|
2019-08-17 13:55:58 -07:00
|
|
|
|
|
|
|
|
@staticmethod
|
2019-08-20 23:10:43 +03:00
|
|
|
def shutdown_adapter(adapter):
|
2019-08-17 13:55:58 -07:00
|
|
|
subprocess.call(['ifconfig', adapter, 'down'])
|
2019-08-20 23:10:43 +03:00
|
|
|
@staticmethod
|
|
|
|
|
def start_adapter(adapter):
|
2019-08-17 13:55:58 -07:00
|
|
|
subprocess.call(['ifconfig', adapter, 'up'])
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def find_adapter():
|
|
|
|
|
for i_name in netifaces.interfaces():
|
|
|
|
|
interface = netifaces.ifaddresses(i_name)[netifaces.AF_INET][0]
|
|
|
|
|
address = interface['addr'].split('.')[0]
|
|
|
|
|
if address == "10":
|
|
|
|
|
return str(i_name)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def change_hostname(hostname):
|
2019-08-20 23:10:43 +03:00
|
|
|
subprocess.call(['hostnamectl', 'set-hostname', hostname])
|