静态ip地址

 

有时候需要频繁在静态ip和动态ip中切换, 这时使用脚本就比较方便

netsh

查询名称

netsh interface ipv4 show interfaces

设置静态ip

netsh interface ip set address name="本地连接" source=static addr=10.101.192.3 mask=255.255.255.0 gateway=10.101.192.1 1
netsh interface ip set dns name="本地连接" source=static addr=202.196.64.1
netsh interface ip add dns name="本地连接" source=static addr=114.114.114.114

设置动态ip

netsh interface ip set address name="本地连接" source=dhcp
netsh interface ip set dns name="本地连接" source=dhcp

powershell

查询名称

Get-NetAdapter

比如要设置的接口是3

设置静态ip

New-NetIPAddress -InterfaceIndex 3 -IPAddress 10.1.4.220 -PrefixLength 24 -DefaultGateway 10.1.4.254
Set-DnsClientServerAddress -InterfaceIndex 3 -ServerAddresses("114.114.114.114")

设置dhcp

Set-NetIPInterface -InterfaceIndex 3 -dhcp enabled
Set-DnsClientServerAddress -InterfaceIndex 3 -ResetServerAddresses

ubuntu

编辑文件

vi /etc/network/interfaces

静态ip

auto eth0
iface eth0 inet static 
  address 192.168.0.100
  netmask 255.255.255.0
  gateway 192.168.0.1
  dns-nameservers 4.4.4.4
  dns-nameservers 8.8.8.8

dhcp

auto eth0
iface eth0 inet dhcp

dns配置, /etc/resolv.conf

nameserver 8.8.8.8 # Replace with your nameserver ip
nameserver 4.4.4.4 # Replace with your nameserver ip

重启

systemctl restart network

ubuntu 17

编辑netplan文件夹下的文件

vi /etc/netplan/01-netcfg.yaml

添加以下内容, 设置的网卡名称, 如eth0

network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
     dhcp4: no
     addresses: [192.168.2.2/24]
     gateway4: 192.168.1.1
     nameservers:
       addresses: [8.8.8.8,8.8.4.4] 

其中dhcp4配置为yes, 则为动态ip

应用网络配置

netplan apply

CentOS

编辑配置

vi /etc/sysconfig/network-scripts/ifcfg-eth0

修改为以下内容

HWADDR=$SOMETHING
TYPE=Ethernet
BOOTPROTO=none // turns off DHCP
IPADDR=192.168.2.2 // set your IP
PREFIX=24 // subnet mask
GATEWAY=192.168.2.254
DNS1=1.1.1.2 // set your own DNS
DNS2=1.0.0.2
DNS3=9.9.9.9
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
NAME=eth0
DEVICE=eth0
ONBOOT=yes // starts on boot

其中BOOTPROTO设置为none或者static为静态ip, DHCP为动态ip

应用配置

/etc/init.d/network restart
# or
systemctl restart network

参考