2010年9月14日 星期二

server network setting script (only for ubuntu)

<1>初版
#!/bin/bash
[ "$USER" != "root" ] && echo "need root" && exit 1
clear

function MainMenu {
echo "############################################################################"
echo "<1>IP網路設定"
echo "<2>DNS設定"
echo "<3>Default Gateway 設定"
echo "<4>個人燈入檔設定"
echo "<5>重設MAC"
echo "<6/q>離開"
echo "############################################################################"

echo ""
read -p "your choice? " choice
clear

case $choice in
        "1")
                vim /etc/network/interfaces
                ;;
        "2")
                vim /etc/resolv.conf
                ;;
        "3")
                vim /etc/rc.local
                ;;
        "4")
                read -p "要修改的使用者: " user
                if [ -d /home/$user ]; then
                        vim /home/$user/.bashrc
                elif [ $user == "root" ]; then
                        vim /root/.bashrc
                else
                        echo "找不到使用者"
                fi
                ;;
        "5")
                file="/etc/udev/rules.d/70-persistent-net.rules"
                if [ ! -f file ]; then
                        echo "找不到檔案"
                else
                        rm $file
                fi
                ;;
        "6"|"q"|"Q")
                read -p "are you sure (Y/N)? " ans
                [ "$ans" == "Y" ] || [ "$ans" == "y" ] && exit 0
esac
}

while [ 1 ]
do
        clear
        MainMenu
        echo ""
        echo -ne "Return to Main Menu ..."
        read
done
                       

<2>修正版(基本功能完成,個人測試ok)
#!/bin/bash
#Author : Marcus Tsai  
#20100914 初版
#20100916 第二次修正版
#20100918 第三次修正版,基本功能完成
##################################################################################

[ "$USER" != "root" ] && echo "Error:拒絕不符權限的操作" && exit 1
[ "$LANG" != "zh_TW.UTF-8" ] && echo "please use zh_TW.UTF-8" && exit 1
clear
echo ""
echo ""
echo "請注意!!"
echo "執行本程式會修改系統設定檔,在輸入相關參數時,"
echo "請特別小心,以免造成系統的異常或損毀...."
echo ""
echo ""
echo ""
sleep 5
clear

netfile=/etc/network/interfaces
dnsfile=/etc/resolv.conf
ethfile=/etc/udev/rules.d/70-persistent-net.rules

function MainMenu {
echo "#####################[ 網路設定程式主選單 ]####################"
echo ""
echo "<1> 網路相關設定"                                                           
echo "<2> 設定預設閘道"
echo "<3> DNS 設定"
echo "<4> 個人參數檔案設定"
echo "<5> 更換網卡,刪除網路檔案"
echo "<6> 增加路由設定"
echo "<7> 啟動路由器模式"
echo "<8> 設定主機NAT設定"
echo "<9> 設定完成,將系統重新啟動"
echo " 離開"
echo ""
echo "####################################################"

echo ""
read -p "請問要執行哪一項設定(1~9)? " choice
clear

case $choice in
        "1")
                [ -f /tmp/int.txt ] && rm /tmp/int.txt
        cat $netfile > /tmp/int.txt
                read -p "請輸入要修改的網路卡(ex.eth0): " eth
       
        if [ ! -z "$eth" ]; then
            read -p "Please input IP info: " ip
                    read -p "Please input Netmask info: " mask
            f=/tmp/int.txt       
            i=$(grep -A 3 "$eth" "$f" |grep addr)
            j=$(grep -A 3 "$eth" "$f" |grep mask)
            k=$(grep -A 3 "$eth" "$f" |grep gate )
            if [ -z "$i" ]; then
                sed -i -e  /$eth/d $f
                echo -e "\nauto $eth \niface $eth inet static \n  address $ip\n  netmask $mask" >> $f
            else
                sed -i -e /$eth/,/netmask/d $f
                [ ! -z "$k" ] && sed -i -e /gateway/d $f
                echo -e "\nauto $eth \niface $eth inet static \n  address $ip\n  netmask $mask" >> $f
            fi
            [ -f $f ] && cat $f > $netfile
        else
            echo "沒有這個裝置"
            return
        fi
                ;;
    "2")
        read -p "請輸入要增加預設路由的網路卡(ex.eth0): " eth
        if [ ! -z "$eth" ]; then
            cat $netfile > /tmp/gw.txt
            f=/tmp/gw.txt
            dhcp=$(grep "$eth" "$f" |grep dhcp)
            i=$(grep -A 3 "$eth" "$f" |grep addr)
                        j=$(grep -A 3 "$eth" "$f" |grep mask)
            k=$(grep -A 3 "$eth" "$f" |grep gate )
            if [ ! -z "$dhcp" ]||[ -z "$i" ]; then
                echo "該裝置使用DHCP或沒有設定ip"
                return
            else
                read -p "請輸入預設閘道IP: " gwip
                sed -i -e "/$eth/,/netmask/d" $f
                sed -i -e "/gateway/d" $f
                echo -e "\nauto $eth \niface $eth inet static\n  address ${i##* }\n  netmask ${j##* }" >> $f
                echo "  gateway $gwip" >> $f
                cat $f > $netfile
            fi
        else
            echo "沒有這個裝置"
        fi
        ;;
    "3")
        read -p "請輸入DNS IP: " dns
        i=$(cat $dnsfile)
        if [ ! -z "$dns" ]; then
            if [ ! -z "$i" ]; then
                j=$(grep nameserver $dnsfile )
                sed -i -e "s/${j##* }/$dns/g" $dnsfile
            else
                echo "nameserver $dns" > $dnsfile
            fi
        else
            echo "取消設定DNS"
        fi
        ;;
    "4")
        read -p "要修改的使用者: " user
                if [ -d /home/$user ]; then
                        vim /home/$user/.bashrc
                elif [ $user == "root" ]; then
                        vim /root/.bashrc
                else
                        echo "找不到使用者"
                fi
                ;;
    "5")
        echo -ne "確定要刪除$ethfile嗎?"
        read ans
        if [ "$ans" == "y" -o "$ans" == "Y" ]; then
            if [ -f $ethfile ]; then
                            rm $ethfile
            else
                echo "找不到檔案!!"
            fi
                fi

        ;;
    "6")
        read -p "要加入路由表的網段(ex:192.168.1.0): " dest
        read -p "該網段的netmask: " mask
        read -p "透過哪一個gateway ip: " gwip
        read -p "透過哪一張網路卡: " nic
        sed -i -e /exit/d /etc/rc.local
        echo -e "route add -net $dest netmask $mask gw $gwip dev $nic" >> /etc/rc.local
        echo "exit 0" >> /etc/rc.local
        ;;
    "7")
        read -p "確定要啟動路由器服務(y/n)?" ans
        if [ "$ans" == "y" ] || [ "$ans" == "Y"  ]; then
            sed -i -e s/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g /etc/sysctl.conf
            sysctl -p &> /dev/null
            echo "設定完成"
        else
            echo "不明選項"
        fi
        ;;
    "8")
        read -p "透過本機哪張網卡上網(ex.eth0): " eth
        if [ ! -z "$eth" ]; then
            check=$(grep $eth $netfile)
            if [ -z "$check" ]; then
                echo "裝置不存在"
                return
            else
                sed -i -e /exit/d /etc/rc.local
                echo "iptables -t nat -A POSTROUTING -o $eth -j MASQUERADE" >> /etc/rc.local
                echo "exit 0" >> /etc/rc.local
                sed -i -e s/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g /etc/sysctl.conf
                            sysctl -p &> /dev/null
                            echo "設定完成"
            fi
        else
            echo "不明的裝置"
        fi
        ;;
    "9")
        read -p "你確定要重開機?(y/n)" ans
        if [ $ans == "y" ] || [ $ans == "Y" ]; then
                        reboot
                elif [ $ans == "n" ] || [ $ans == "N" ]; then
                        echo ""
                else
                        echo "不明選項"
                fi
        ;;       
        "q"|"Q")

        echo ""
                read -p  " 確定要離開程式?(y/n) " ans
                if [ $ans == "y" ] || [ $ans == "Y" ]; then
            clear
            echo ""
            exit 0
        elif [ $ans == "n" ] || [ $ans == "N" ]; then
            echo ""

        else
            echo "不明選項"
        fi
                ;;
esac
}

while [ 1 ]
do
        clear
        MainMenu

        echo ""
        echo -ne "Return to Main Menu..."
        read
done

建立帳號script

1,建立文字檔(包含帳號密碼資訊)
$vim users.txt
a001:a001
a002:a002
a003:a003
        :

修正版:(互動式自動產生帳號流水號)
#!/bin/bash
#自動產生帳號,密碼與帳號一致

while [ -z "$filename" ]
do
   echo ""
   read -p  "請輸入要建立的檔案名稱: " filename
   if [ "${filename##*.}" != "txt" ]
   then
      echo "僅能接受txt文字檔格式"
      unset filename
   fi
done

if [ -f "$filename" ]
then
   read -p "該檔案已存在,是否要刪除(default: no)? " ans
   if [ "$ans" == "Y" ]||[ "$ans" == "y" ]
   then
      rm $filename
   else
      unset filename
      while [ -z "$filename" ]
      do
         echo ""
         read -p  "另一個名稱: " filename
         if [ "${filename##*.}" != "txt" ]
         then
             echo "僅能接受txt文字檔格式"
         unset filename
         fi
      done
   fi
fi

while [ -z "$num" ]
do
   echo ""
   read -p "請輸入要產生的帳號數量: " num

   s=$(echo $num|tr -d "0-9")
   if [ -n "$s" ]||[ "$num" -le "0" ]
   then
      echo "請輸入合法且大於零的數字"
      unset num
   fi
done

while [ -z "$name" ]
do
   echo ""
   read -p "請輸入要產生的帳號名稱: " name

   n=$(echo $name|tr -d "a-z" |tr -d "A-Z")
   if [ -n "$n" ]
   then
      echo ""
      echo "帳號名稱不可使用特殊字元或數字"
      unset name
   fi
done

touch $filename
count=1
if [ "$num" -lt 10 ]
then
   while [ "$count" -le "$num" ]
   do
      echo -e $name"0"$count:$name"0"$count >> $filename
      count=$(($count+1))

   done
else
   while [ "$count" -lt 10 ]
   do
      echo -e $name"0"$count:$name"0"$count >> $filename
      count=$(($count+1))
   done
   while [ "$count" -le "$num" ]
   do
      echo -e "$name$count:$name$count" >> $filename
      count=$(($count+1))
   done
fi


2.建立批次程式:
$vim makeuser.sh
#!/bin/bash
#Author : Marcus Tsai  20100914
#檔案固定,判斷是否由root執行,判斷檔案是否存在
filename=/home/student/bin/users.txt
[ "$USER" != "root" ] && echo "need root permision" && exit 1
[ ! -f "$filename" ] && echo "file not found" && exit 1
s=$(cat $filename)

for us in $s
do
        uname="${us%%:*}"
        passwd="${us##*:}"

        useradd -m -s /bin/bash $uname
        echo "$uname:$passwd" |chpasswd

done

exit 0

<1>程式修正版:
#修改成由使用者自帶檔案位置
#!/bin/bash
#Author : Marcus Tsai  20100914
#filename=/home/student/bin/users.txt

#判斷是否root執行,參數是否沒給或超過1個,判斷檔案是否存在
[ "$USER" != "root" ] && echo "need root permision" && exit 1
[ "$#" != "1" ] && echo "wrong parameter!!just one please. " && exit 1
[ ! -f "$1" ] && echo "file not found" && exit 1

s=$(cat $1)

for us in $s
do
        uname="${us%%:*}"
        passwd="${us##*:}"

        useradd -m -s /bin/bash $uname
        echo "$uname:$passwd" |chpasswd

done

exit 0

選單程式(Case)

<1>mycase.sh
#判斷輸入的檔案為哪一類的壓縮檔
#!/bin/bash

read -p "filename: " x
case "${x##*.}"  in
        gz)
                echo this is gz file.
                ;;
        bz2)
                echo this is bz2 file.
                ;;
        1)
                clear
                ;;
        *)
                echo "Archive format not recognized."
                exit 1
                ;;
esac
exit 0

<2>menu.sh
#選單程式,1.使用vim編輯檔案 2.離開
#!/bin/bash
clear

function Menu {
echo "<1> Edit file"
echo "<2> Quit"

echo ""
echo -ne "choice: "
read userchoice
clear

case $userchoice in
        "1")
#利用check來決定迴圈執行與否。預設0,檔案存在變1,不存在還是給0重來
                check=0
                while [ "$check" == "0" ]
                do
                        read -p "please input filename or input q exit: " filename
                        [ $filename == "q" -o $filename == "Q" ] && return
                        if [ ! -f "$filename" ]; then
                                echo "請輸入正確檔案位置"
                                check=0
                        else
                                check=1
                        fi
                done
                vim $filename

                ;;
        "2")
                echo -n "Do you really want to quit (y/n)?"
                read -e ans
                [ "$ans" == "y" -o "$ans" == "Y" ] && exit 0
                echo ""
                ;;
        *)
                echo "Unknowm $userchioce"
                ;;
esac
}

while [ 1 ]
do
        clear
        Menu

        echo ""
        echo -ne "Return to Main Menu ..."
        read
done

2010年9月13日 星期一

Shell script 練習(while do...done,for do...done)

<1>mywhile.sh
#由0開始+1到值變為10後停止
#!/bin/bash
myvar=0
while [ $myvar -ne 10 ]
do
        echo $myvar
        myvar=$(( $myvar + 1 ))
done
exit 0

執行方式:
$./mywhile.sh

修正版:
a.
#修正為手動輸入參數,判斷是否為數字0-9
#~/bin/bash
myvar="$1"
for (( i=0; i<=9; i=i+1 ))
do
        if [ "$i" == "$myvar" ]; then
                while [ $myvar -ne 10 ]
                do
                        echo $myvar
                        myvar=$(( $myvar + 1 ))
                done
        fi
done
echo "Please input num 0-9"
exit 0

執行方式:
1.$./mywhile.sh 12515    出現錯誤訊息
2.$./mywhile.sh abc    出現錯誤訊息
3.$./mywhile.sh 5     正確執行,在畫面上秀出5,6,7,8,9

b.
#!/bin/bash
[ "$#" != "1" ] && echo "parameter too much" && exit 1
myvar="$1"

s=$(echo $1 |tr -d 0-9)
[ -n "$s" ] && echo "$myvar not number" && exit 1

if [ $myvar -gt "9" -o $myvar -lt "0" ]; then
        echo "Please input 0-9"
        exit 0
else
        while [ $myvar -ne 10 ]
        do
                echo $myvar
                myvar=$(( $myvar + 1 ))
        done
fi

exit 0

<2>myfor1.sh
#秀出所給的所有參數
#!/bin/bash
for thing in "$@"                   #thing 表示變數
do
        echo you typed $thing
done
exit 0

執行方式:
1../myfor1.sh aaa bbb ccc  畫面依序秀出you typed aaa,you typed bbb,you typed ccc

進階練習:
a. 
#將後面給的參數IP,交由ping來執行,然後在螢幕上秀出有無成功
#!/bin/bash

for ip in "$@"
do
        ping -c 2  $ip &> /dev/null
        if [ "$?" != "0" ]; then
                echo ping $ip fail
        else
                echo ping $ip ok
        fi
done
exit 0

執行方式:
1.$./myfor1.sh 192.168.120.1 168.95.1.1 192.168.1.1
正確執行,依序秀出ping 192.168.120.1 ok,ping 168.95.1.1 ok,ping 192.168.1.1 fail
b.
#在畫面上秀出類似99乘法表
#!/bin/bash
#writer:Marcus Tsai 20100913
read -p "請輸入第一個數字:" fn
s=$(echo $fn |tr -d 0-9)
[ -n "$s" ] && echo "Error: $fn 不是數字" && exit 1
read -p "請輸入第二個數字:" sn
s=$(echo $sn |tr -d 0-9)
[ -n "$s" ] && echo "Error: $sn 不是數字" && exit 1

for (( i=1 ; i<=$fn ; i=i+1 ))
do
        for (( j=1 ; j<=$sn ; j=j+1 ))
        do
                total=$(($i*$j))
                echo "$i X $j = $total"
        done
done
exit 0
b修正版:
#在畫面上將結果分開秀出,而不是都在同一列,並增加錯誤判斷
#!/bin/bash
#Author : marcus Tsai 20100913
read -p "請輸入第一個數字1-9:" fn
s=$(echo $fn |tr -d 0-9)
[ -n "$s" ] && echo "Error: $fn 不是數字" && exit 1

[ $fn -gt "10" -o $fn -lt "1" ] && echo "Error: 請輸入1-9的數字" && exit 1
read -p "請輸入第二個數字1-9:" sn
s=$(echo $sn |tr -d 0-9)
[ -n "$s" ] && echo "Error: $sn 不是數字" && exit 1
[ $sn -gt "10" -o $sn -lt "1" ] && echo "Error: 請輸入1-9的數字" && exit 1
for (( i=1 ; i<=$sn ; i=i+1 ))
do
        for (( j=1 ; j<=$fn ; j=j+1 ))
        do
                total=$(($i*$j))
                printf "%s\t " "echo $j X $i = $total"
        done
    echo -e "\n"
done
exit 0

Shell script 練習(if then...else...)

<1>testroot.sh
#判斷執行程式的帳號是否為root
#!/bin/bash

w=$(whoami)
[ "$w" != "root" ] && echo "$w have no permission,need root " && exit 1
[ "$w" == "root" ] && echo "you are root"
exit 0


<2>param01.sh
#判斷option是否為"-a"
#!/bin/bash


if [ "$#" != "1" ] || [ "$1" != "-a" ]; then
        echo "error option"
        exit 1
fi

echo "-a ok"
exit 0

<3>mytar.sh
#判斷接續的檔案副檔名是否為.tar
#!/bin/bash

if [ "${1##*.}" == "tar" ]; then        
#${1}=$1,{}是為了執行##*.表示由左向右抓出最後一個.右邊的所有文字,單一個#表示由左向右第一個.右邊的所有文字
        echo "This appears to be a tarball."
else
        echo "At firs glance,this does not appear to be a tarball"
fi
exit 0

<4>touchsh
#判斷檔案是否附檔名為.sh如是給予執行權限
#!/bin/bash

[ ! -f "$1" ] && echo "file no exist!" && exit 1
if [ "$#" != "1" ] || [ "${1##*.}" != "sh" ]; then
        echo "error option"
        exit 1
fi
chmod +x $1
exit 0

2010年9月10日 星期五

bash下的字串處理

1. 向左刪除
字串處理方向是由
$ myvar=foodforthought.jpg
$ echo ${myvar##*fo}    #由左自右找到最後一個符合fo的將之後的顯示出來,*表示fo左邊可以有任意字元  
rthought.jpg

$ echo  ${myvar#*fo}    #由左自右找到第一個符合fo的將之後的顯示出來
odforthought.jpg

# 顯示 DNS IP 位址
$ mydns=$(cat /etc/resolv.conf | grep nameserver)
$ echo ${mydns##* }
192.168.56.2

顯示最後一個參數
$ nano lastargv.sh
myargv="$@"
echo ${myargv##* }

$ bash lastargv.sh a b c
c

2. 向右刪除
字串處理方向是由
$ myfoo=“chickensoup.tar.gz”
$ echo  ${myfoo%%.*}
chickensoup


$ echo  ${myfoo%.*}
chickensoup.tar

3. 截取字串
$ ex=cowabungaxyz
$ echo  ${ex:0:3}                # 0 代表起始位址, 3 代表抓三個字
Cow

$ echo  ${ex:3:7}
abungax

## 顯示 Dsfault Gateway
$ mygw=$(netstat -r | grep default)
$ echo $mygw
default              192.168.200.2 0.0.0.0 UG 0 0 0 eth0
$ echo ${mygw:16:15}
192.168.200.2

2010年9月6日 星期一

用VMware+Ubuntu-server做網路NAT與ROUTE lab



1>NAT
(1)$sudo vim /etc/network/interfaces ;加入
auto eth0
iface eth0 inet static
address 192.168.213.5
netmask 255.255.255.0
gateway 192.168.213.2

auto eth1
iface eth1 inet static
address 192.168.120.254
netmask 255.255.255.0

(2)$sudo vim /etc/sysctl.conf
#net.ipv4.ip_forward=1
將上面那行的註解拿掉變:
net.ipv4.ip_forward=1

(3)$sudo vim /etc/rc.local
route add -net 192.168.87.0 netmask 255.255.255.0 gw 192.168.120.5 dev eth1
route add -net 192.168.160.0 netmask 255.255.255.0 gw 192.168.120.7 dev eth1
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

(4)$sudo rm /etc/udev/rules.d/70-persistent-net.rules
避免網路設備有異常,可將上列檔案刪除

(5)$ sudo reboot #重開機,NAT設定完畢

(6)顯示文字如果有問題可以做下面修正:
$sudo locale-gen 'en_US.UTF-8'
$vim .bashrc ;在最後面加入底下幾行,表示用SSH方式還是使用zh_TW

2>Router
(1)sudo vim /etc/network/interfaces ;加入
auto eth0
iface eth0 inet static
address 192.168.120.5
netmask 255.255.255.0
gateway 192.168.120.254

auto eth1
iface eth1 inet static
address 192.168.87.254
netmask 255.255.255.0

(2))$sudo vim /etc/sysctl.conf
#net.ipv4.ip_forward=1
將上面那行的註解拿掉變:
net.ipv4.ip_forward=1

(3)$sudo rm /etc/udev/rules.d/70-persistent-net.rules
避免網路設備有異常,可將上列檔案刪除

(4)$ sudo reboot #重開機,Router設定完畢

R2同樣設定方式只是IP不同

3>NS
(1)sudo vim /etc/network/interfaces ;加入
auto eth0
iface eth0 inet static
address 192.168.87.10
netmask 255.255.255.0
gateway 192.168.87.254

(2)$sudo rm /etc/udev/rules.d/70-persistent-net.rules
避免網路設備有異常,可將上列檔案刪除

NS2與NS1一樣設定方式,修改ip即可

(3)$ sudo reboot #重開機,Router設定完畢

2010年9月4日 星期六

KVM install on Ubuntu 10.04

Max以前在Ubuntu上一直都是使用VirtualBox來建制虛擬環境。曾經也想試試Xen,
不過在Ubuntu上安裝一直失敗。前一陣子得知新的虛擬技術已經相當成熟且很多Linux發行版本
都有支援,更重要的是KVM是Kernel Based的虛擬化技術,當然值得來研究一下

參考資料:
1.KVM 官網
2.Ubuntu install 文件

安裝步驟:
1.檢查CPU是否支援硬體虛擬技術,沒有支援也可以安裝,但效能會相當低落,不如使用virtualbox
$egrep -c '(vmx|svm)' /proc/cpuinfo

If 0 it means that your CPU doesn't support hardware virtualization.

If 1 (or more) it does - but you still need to make sure that virtualization is enabled in the BIOS.

2.由於max使用的是64bit kernel,所以以下安裝操作以64bit為主,32bit請參考官方文件
<1>更新套件庫:
$sudo apt-get update
<2>安裝KVM相關套件:
$sudo apt-get install kvm libvirt-bin ubuntu-vm-builder bridge-utils virt-viewer
<3>將使用者帳號加入相關群組(kvm and libvirtd):
$groups
marcus adm kvm libvirtd
<4>在使用KVM前可能需要重開機或relogin一次
$sudo reboot or logout
<5>檢查是否有安裝成功
$virsh -c qemu:///system list
 Id Name                 State
----------------------------------

$
<6>安裝圖形管理工具
$
sudo apt-get install virt-manager
<7>安裝好後在系統-->偏好設定-->主選單 中,找到『虛擬機器管理員』,
選擇屬性,在指令前方加入gksudo以root權限啟動管理介面