Linux switch network to DHCP or Static

I just helped a co-worker regarding this particular task where she wants to switch her network interface from manual static IP to automatic IP by dhcp in a linux client using command line since it does not have x desktop so I quickly wrote following script

you can find your interface name quickly by executing nmcli dev status at the terminal

How to Configure Network Connection Using 'nmcli' Tool

switchStaticToDHCP.sh

requires passing by one argument which is your network interface name.

!/bin/bash
 nmcli con mod $1 ipv4.method auto
 nmcli con mod $1 ipv4.gateway ""
 nmcli con mod $1 ipv4.address ""
 nmcli con down $1
 nmcli con up $1
 dhclient $1

switchStaticToDHCP.sh Your_Network_Interface_Name

eg: bash switchStaticToDHCP.sh enp0s3

switchDHCPToStatic.sh

requires passing by 3 arguments – your network interface name, static ip address, & default gateway ip address.

!/bin/bash
 nmcli con mod $1 ipv4.method manual
 nmcli con mod $1 ipv4.addresses $2/24
 nmcli con mod $1 ipv4.gateway $3
 nmcli con down $1
 nmcli con up $1

swtichDHCPToStatic.sh Your_Network_Interface_Name IP_Address Default_Gateway

eg: bash switchDHCPToStatic.sh enp0s3 192.168.1.168 192.168.1.254

Leave a Reply

Your email address will not be published. Required fields are marked *