您的位置:首页 > 理论基础 > 计算机网络

Linux shell应用1-自动配置网络

2011-10-18 00:07 316 查看
1. 概述

Linux shell给我们提供了很多有用的命令,利用这些命令,能够自动的完成许多复杂的任务。如察看每个用户所占用的磁盘容量,CPU负载及内存情况,自动管理网络,定时下载等功能。而这篇文章中主要是介绍一下,利用脚本来实现自动配置网络。特别是固定IP的配置,对于初学者来说,配置网络可能比较麻烦,而通过shell脚本,就可以轻松的完成配置网络的功能。

2. shell配置网络

(1)网络知识介绍

在前面的文章中,我们已经介绍了Linux shell基础编程,正则表达式和高级编程。简单回忆一下,其中基础编程,主要包括结构化命令,用户输入,流式编辑器sed和gawk基础知识,而高级编程主要有正则表达式的应用,sed,gawk高级部分等。对于配置静态IP上网,通过需要配置以下内容,IP地址,网关,子网掩码,DNS服务器,网卡MAC地址。Linux系统中有几个重要的配置文件:

/etc/resolv.conf- DNS配置文件

/etc/hosts-主机名到IP地址的映射

/etc/sysconfig/network-所有的网络接口和路由信息

/etc/sysconfig/network-script/ifcfg-<interface-name>-每一个网络接口的配置信息

(2)自动配置网络的shell脚本

#!/bin/bash

read -p "do you want to configure nework[Y/N]?" reply #读入信息,是否配置网络

case $reply in

Y|y)

echo

echo "***************************************"

echo "--------network configuration----------"

echo

ifconfig eth0 down #关闭网卡,在配置之前先关闭网卡,我的机器上是eth0

while true

do

read -p "please input IP:" IP

if echo $IP|grep "/([0-9]/{1,3/}/.[0-9]/{1,3/}/.[0-9]/{1,3/}/.[0-9]/{1,3/}/)

/(/([0-9]/{1,3/}/./)/{3/}[0-9]/{1,3/}/)" #IP地址的正则表达式

then

ifconfig eth0 $IP #配置IP

break

else

echo "please check IP format..."

fi

done

while true

do

read -p "please input netmask:" NETMASK

if ifconfig eth0 netmask $NETMASK #配置子网掩码

then

break

fi

echo "please check netmask format..."

done

while true

do

read -p "please input gateway:" GATEWAY

if route add default gw $GATEWAY #配置网关

then

break

fi

echo "please check gateway format..."

done

while true

do

ifconfig eth0 down

read -p "please input MAC:" MAC

if ifconfig eth0 hw ether $MAC #配置对应网卡的MAC

then

break

fi

echo "please check MAC format..."

done

while true

do

read -p "please input DNS:" DNS

if echo $DNS|grep "/([0-9]/{1,3/}/.[0-9]/{1,3/}/.[0-9]/{1,3/}/.[0-9]/{1,3/}/)

/(/([0-9]/{1,3/}/./)/{3/}[0-9]/{1,3/}/)"

then

DNS=`echo nameserver $DNS` #配置DNS

echo $DNS >>/etc/resolv.conf

break

else

echo "please check DNS format..."

fi

done

ifconfig eth0 up #激活网卡

/etc/rc.d/init.d/network restart #重新启动网络

mentohust=`whereis mentohust`

if [ mentohust="mentohust:" ] #如果是锐捷拨号

then

echo "there is no mentohust...."

else

mentohust & #以后台的方式启动锐捷

fi

TEMP=`mktemp -t temp.XXXXXX`

echo $TEMP

echo "Testing Network......" #测试网络连通性

exec 2>$TEMP

`echo ping -c 5 www.sina.com.cn` >>$TEMP

if grep "unknown host" $TEMP #测试一下ping的数据包是否含有unknown host

then

echo "network timeout,please check network configuration"

else

echo

echo "*******************************************"

echo "OK,good luck!"

fi

rm -rf $TEMP;;

N|n)

exit;;

esac

就此,利用这个shell脚本就可以轻松的配置网络了。

关于Linux shell脚本配置自动配置网络就介绍到这里了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: