Monday, April 9, 2012

SA hw3

上學期 SA 的 shell script 作業

http://people.cs.nctu.edu.tw/~huanghs/course/sysadm2011/slides/hw3.pdf


hw3-1

作業是一個分析 sockstat 指令的 sh one liner

Use one-line command to show per-user socket statistic





在 apua 提示下用 awk 完成了...

sockstat | tail -n+2 | sort | awk '{print $1" "$2}' | xargs | 
awk '{split($0,a);for (i=1;i<=NF;i+=2){c[a[i]" "a[i+1]]++;}
for (i in c) {print c[i]" "i}}' | sort -k2 | xargs | 
awk '{split($0,a);for(i=1;i<=NF;i+=3){b[a[i+1]]+=a[i];c[a[i+1]]=sprintf("%s %s",c[a[i+1]],a[i+2]);}
for (i in b){printf("%s: %s (%s )\n", i, b[i],c[i]);}}' | sort -nk2 -r | 
awk -v T=$THRESHOLD '{if ($2 > T) print $0}'

http://pastie.org/2794451






一步一步分析

sockstat |                    # 這步不用說吧XD 
 
tail -n+2 |                   # 從第2行開始印 
                              # 把 USER COMMAND PID  ....  濾掉 
 
sort |                        # 對第一欄 (user) 排序 
 
awk '{print $1" "$2}' |       # 取出前兩欄 
 
xargs |                       # 把東西通通黏起來 
 
 
awk ' { 
    split($0,a);              # 東西全部裝進 a 這個 hash 裡面 
    for (i = 1; i <= NF; i += 2) { 
        c[a[i]" "a[i+1]]++;   # 把 "user process" 做為 key 並統計 
    } 
    for (i in c) { 
        print c[i]" "i        # 印出 "sum user process" 
    } 
}' | 
 
 
sort -k2 |                    # 對 user 做排序 
 
xargs |                       # 黏起來 
 
awk '{ 
    split($0,a);              # 通通裝進 a 
    for(i=1;i<=NF;i+=3){ 
        b[a[i+1]]+=a[i];      # 算出所有開啟 sock 數 
        c[a[i+1]]=sprintf("%s %s",c[a[i+1]],a[i+2]); 
                              # append 其他 process 到後面 
    } 
    for (i in b){ 
        printf("%s: %s (%s )\n", i, b[i],c[i]); 印答案出來 
    } 
}' | 
 
sort -nk2 -r |                # 降序 sort 
 
awk -v T=$THRESHOLD '{        # 處理 THRESHOLD 
    if ($2 > T) 
        print $0 
}'


===========================================

結論

    把 awk 當成 Perl 來寫就沒問題囉 ^.<







作業二是比較麻煩的 zfs Snapshot Management

然後順便玩玩 parsing 指令參數這樣






這個作業學到 logger 指令的用法、然後也更熟悉 zfs 了XD

#!/bin/sh                                                                                                                              
                                                                                                                                       
                                                                                                                                       
# get args                                                                                                                             
d=0                                                                                                                                    
count=0                                                                                                                                
while getopts f:n:c:d op                                                                                                               
do                                                                                                                                     
    case $op in                                                                                                                        
        f) fs=$OPTARG;;                                                                                                                
        n) name=$OPTARG;;                                                                                                              
        c) count=$OPTARG;;                                                                                                             
        d) d=1;;                                                                                                                       
        *) echo "TAs are so evil Q____Q"                                                                                               
           echo "Usage: sudo ./zfsSnap.sh -f <fs> -n <name> <-c <count> | -d>."                                                        
           exit 1;                                                                                                                     
           ;;                                                                                                                          
    esac                                                                                                                               
done
                                                                                                                                       
# $count should be digits and can't start by 0                                                                                         
count=`echo $count | grep -v [^0-9] | grep -v ^0`                                                                                      
                                                                                                                                       
# all args are not NULL strings                                                                                                        
if [ -z $count ] || [ -z $fs ] || [ -z $name] ; then                                                                                   
  echo "TAs are so evil Q____Q"                                                                                                        
  echo "Usage: sudo ./zfsSnap.sh -f <fs> -n <name> <-c <count> | -d>."                                                                 
  exit 1;                                                                                                                              
fi                                                                                                                                     
          
# rolling                                                                                                                              
if [ $count -gt 0 ] ; then       # i don't know how to write && in shell script :(                                                     
    if [ $d -eq 0 ] ; then                                                                                                             
                                                                                                                                       
        # list of snapshots we want                                                                                                    
        shotlist=`zfs list -r -t snapshot | cut -f1 -d' ' | tail -n+2 | grep $fs | grep $name | sort`                                  
                                                                                                                                       
        # how many lines                                                                                                               
        line=`zfs list -r -t snapshot | cut -f1 -d' ' | tail -n+2 | grep $fs | grep $name | wc -l | xargs`                             
        num=$count                                                                                                                     
                                                                                                                                       
        # need to delete something                                                                                                     
        del=1                                                                                                                          
                                                                                                                                       
        # don't need to delete                                                                                                         
        if [ $line -lt $num ] ; then                                                                                                   
          num=$line                                                                                                                    
          del=0                                                                                                                        
        fi                                                                                                                             
                                                                                                                                       
        # create $num .. 0 and store it in $num                                                                                        
        while [ $num -ge 0 ]                                                                                                           
        do                                                                                                                             
          echo $num >> QQ             # TA changed requirements, so i feel Q____Q                                                      
          num=$(( $num -1 ))                                                                                                           
        done
        done                                                                                                                           
        num=`cat QQ`                                                                                                                   
        rm QQ                                                                                                                          
                                                                                                                                       
                                                                                                                                       
        # rolling (J.K. ?)                                                                                                             
        for i in $num                                                                                                                  
        do                                                                                                                             
            old=$(( $i-1 ))                                                                                                            
            if [ $i -gt 0 ] ; then                                                                                                     
                zfs rename $fs@$name.$old $fs@$name.$i                                                                                 
                logger -p local7.notice "zfsSnap.sh [$$]: Old snapshot: $fs@$name.$old rotated"                                        
            fi                                                                                                                         
        done                                                                                                                           
                                                                                                                                       
        # kil oldest shot                                                                                                              
        if [ $del -eq 1 ] ; then                                                                                                       
          zfs destroy $fs@$name.$count                                                                                                 
          logger -p local7.notice "zfsSnap.sh [$$]: Delete snapshots: $fs@$name.$(($count - 1))"                                       
        fi                                                                                                                             
                                                                                                                                       
        # make a new one                                                                                                               
        zfs snapshot $fs@$name.0                                                                                                       
        logger -p local7.notice "zfsSnap.sh [$$]: New snapshot: $fs@$name.0"                                                           
    fi                                                                                                                                 
fi
                                                                                                                                      
# delete                                                                                                                               
if [ $d -eq 1 ] ; then                                                                                                                 
    # fine all shots and just destroy them                                                                                             
    shotlist=`zfs list -r -t snapshot | cut -f1 -d' ' | tail -n+2 | grep $fs | grep $name`                                             
    for i in $shotlist                                                                                                                 
    do                                                                                                                                 
        zfs destroy $i                                                                                                                 
        logger -p local7.notice "zfsSnap.sh [$$]: Delete snapshots: $i"                                                                
    done                                                                                                                               
fi



作業三是最好玩也是最麻煩的

RSS Feed Reader!

用 shell script 的 cdialog 做出一個 command line 底下的 RSS feed reader




為了避免麻煩,助教ㄉㄉ很 nice 的有用 Python 寫了一個 RSS parser 工具

不過我那時候還不會 Python,同時也是為了挑戰自己,用 Perl hack 了一個XD






這個 code 版本少了當初修好的 bug ...

demo 時的 code 忘記丟到哪了 orz  現在留下來的版本是後來改給 Ubuntu 的


read 功能沒有濾掉 RSS 吐給我的 XML 標籤,後還是用 sed 解決的

 sed -e 's/<[^>]*>//g'




#!/bin/sh
# welcome msg
cdialog --title "Welcome" --msgbox "Hello world!" 5 40

# main manu
menu () {

  cdialog --title "Main Menu" --menu "Choose Action" 12 45 5 \
    R "Read - read subscribed feeds" \
    S "Subscrib - new subscription" \
    D "Delete - delete subscription" \
    U "Update - update subscription" \
    Q "Bye~" 2>/tmp/menuitem
  menuitem=`cat /tmp/menuitem`
  rm /tmp/menuitem
  case $menuitem in
    R ) return 1 ;;
    S ) return 2 ;;
    D ) return 3 ;;
    U ) return 4 ;;
    Q ) return 5 ;;
  esac
}

Read () {
  cdialog --title "Read" --menu "choose subscription" 12 45 5 `cat who | awk '{print NR" "$1}'` 2>/tmp/menuitem

  menuitem=`cat /tmp/menuitem`
  rm /tmp/menuitem
  
#  cdialog --title "Read" --menu "foo" 20 45 10 `cat iamben/titles | awk '{print "\""NR"\" \""$0"\""}'` 2>/tmp/menuitem
#  menuitem=`cat /tmp/menuitem`
#  rm /tmp/menuitem
  cdialog --msgbox "$menuitem" 5 40 

}

Update () {
# i did it with a Perl script
  ./fetchRSS.pl > /dev/null
}

Subscrib () {
  cdialog --title "Subscrib" --inputbox "Enter feed url" 8 60 2>/tmp/url
  url=`cat /tmp/url`
  rm /tmp/url
  
  cdialog --title "Subscrib" --inputbox "Enter feed name" 8 60 2>/tmp/name
  name=`cat /tmp/name`
  rm /tmp/name
  
  echo $name >> who
  echo $url >> subscription
  Update
}


Delete () {
  cdialog --title "Delete" --menu "choose subscription" 12 45 5 `cat who | awk '{print NR" "$1}'` 2>/tmp/menuitem
  menuitem=`cat /tmp/menuitem`
  rm /tmp/menuitem
  rm -r $menuitem
  cat subscription | awk -v m=$menuitem '{if ( NR == m ) ; else print $0}' > s
  cat who | awk -v m=$menuitem '{if (NR == m) ; else print $0}' > w
  rm subscription
  rm who
  mv s subscription
  mv w who
}

# an infinity loop
while [ 1 ] ; do
  menu
  m=$? 
  case $m in
      1 ) Read;;
      2 ) Subscrib;;
      3 ) Delete ;;
      4 ) Update ;;
      5 ) exit 0;;
  esac
done




#!/usr/bin/perl
use strict;

use LWP::Simple;
use XML::Feed;

my @subs = ();

open SUBSCRIPTION , "subscription" or die "file subscription open error: $!";
while (<SUBSCRIPTION>) {
    chomp;
    push @subs, $_;
}

while (<*>) {
  chomp;
  if (-d $_) {
    chdir $_;
    system ("rm *");
    chdir "..";
    rmdir $_ or die "QQ:$_ $!";
  }
}

my $z = 1;
for my $sub (@subs) {
    my $feed = XML::Feed->parse(URI->new($sub))
        or die XML::Feed->errstr;
     
    mkdir $z or die "can't write directory [$z]: $!";
    chdir $z or die "can't cd to directory [$z]: $!";

    system("rm titles");
    for my $entry ($feed->entries) {
        open W, sprintf(">>titles") , or die "can't write file [$z/titles] :$!";
        print W $entry->title, "\n";
        close W;
    }

    my $count = 1;
    for my $entry ($feed->entries) {
        open W, sprintf(">%s", $count) , or die "can't write file [$z/$count] :$!";
        print W "---\n";
        print W "Title: ", $entry->title, "\n";
        print W "Link: \n  ", $entry->link, "\n";
        print W "---\n";
        print W $entry->content->body, "\n";
        $count++;
        close W;
    }
    chdir "..";
    $z++;
}

SA class 6





periodic process                 #    do things at right time automatically

cron deamon
    wakes up every minute and reads the cron table and executes command on time
    /etc/rc.c/cron               # FreeBSD
    /etc/cron.d                  # Linux
    portaudit


crontab (cron table)
    "user's" cron
    named the uid
    under /var/cron/tabs         # FreeBSD
    /etc/crontab                 # system cron


configution                      # use crontab -e
    ignored blank lines or leading spaces and tabs
    comments start with '#'

    env setting                  # important
        name=value
        LOGNAME
        SHELL
        PATH                     # full pathname is better
        HOME
        MAILTO                   # to record outputs and send to your mailbox

    format
        min hour day month weekday command
            minute      0 .. 59
            hour        0 .. 23
            day         1 .. 31
            month       1 .. 12
            weekday     0 ..  6  # 0 for Sunday

        matche rules
            * everything
            - matches ranges
            , listed value
            / skips of the number's value through the range

            special strings
                @reboot          # once at startup
                @yearly          # once a year         0 0 1 1 *
                @annually        # the same
                @monthly         # once a month        0 0 1 * *
                @weekly          # once a week         0 0 * * 0
                @daily           # once a day          0 0 * * *
                @midnight        # the same
                @hourly          # once an hour        0 * * * *


'crontab' command
    crontab -e
        edit user's cron with your editer such as 'vim'

    crontab -l
        list the crontab

     crontab -r
        remove the crontab

    crontab filename
        install filename as your crontab

    to allow and deny users
        /var/cron/{allow,deny}

system crontab
    /etc/crontab
    min hour mday month wday who command
                             ^^^
    control the permission as who

periodic
    in /etc/crontab

    periodic daily
             weekly
             monthly
    /etc/defaults/periodic.conf
    /usr/ports/ports-mgmt/portaudit


'at' command
    12:15am root@satest # at -t 201110200016
    echo Hello world
    ^D
    Job 2 will be executed using /bin/sh
    12:15am root@satest # atq
    Date                            Owner           Queue   Job#
    2011年10月20日 周四 00時16分00秒 CST    root            c       2

'atq'
    run jubs queueed by 'at'
    'atrun'  run per 5 min  see /etc/crontab
    /var/at/at.{allow,deny}
    batch exec commands when system load drops then 1.

===========================================

drivers and kernel

UNIX system
    user level programers
    kernel
    hardware

    kernel manages and resourtces
        CPU process managemant
        memory managemant
        I/O devices managemant

    kernel provides methods for
        IPC inter-process communication
        process request resources
            system call

                      user applications
          +-- Kernel ---------- | ---------------------+
          |            syscall interface               |
          |            |               |               |
          |            V               V               |
          |      filesystem        process control     |
          |           |            IPC, scheduler      |
          |      device drivers    memory managemant   |
          |               |            |               |
          |               hardware control             |
          +------------------- |  ---------------------+
                            hardware




kernel-wide design approaches
    monolithic kernels
        kernel space, shared memorym fast
        Linux, BSD, M$ 9x- ...

    microkernels
        user space, message passing, slow
        Mac OS X, GNU Mach

    Hybrid
        Monolithic + Micro
        M$ NT+

    other
        Nanokernels
        Exokernels


FreeBSD kernel
        monolithic -> modular
        cannot be dynamical loadable

    customized VS GENERIC
        fast boot time
        lower memory usage
        additional hardware support
        fine-tune system performance


finding system hardware
    dmesg
        cat /var/run/dmesg.boot
        pciconf -lv
    kldstate
    kldload
        /boot/kernel/*.ko
        xx_xxx_load="YES"
    kldunload


building FreeBSD source tree
    sysinstall
        configure -> disrtiburion -> src -> all


customized kernel comfiguration file
    sample files
    /usr/src/sys/<ARCH>/conf     # <ARCH> for i386 or amd64
        GENERIC, NOTES, LINT (generated by 'make LINT') <--- to find drivers
    /usr/src/sys/conf/NOTES      # for arch independent options


customized file
    cp GENERIC /usr/local/etc/KERNEL5566
    ln -s /usr/local/etc/KERNEL5566 /usr/src/sys/<ARCH>/conf


building a kernal
    cd /usr/src
    make buildkernel KERNCONF=KERNEL5566
    make installkernel KERNCONF=KERNEL5566
    make kernel = make buildkernel + make installkernel

    kernel locatinos
        /boot/kernel/kernel
        /boot/kernel -> /boot/kernel.old

    when somethings goes wrong
        config failed            # typo
        make failed              # fucking errors code 123
                                 # look over your configuration
                                 # or send mails for FreeBSD question mailing
list
        boot failed
            ok mode              # it means your kernel is not ok
                boot kernel.old
                unload kernel && load/boot/kernel.old && boot

            ps failed
                recompile and install a word

        sysctl command
            dynamically set or get kernel parameters


        /etc/sysctl.conf
        /boot/loader.conf

================================

disk
    interface
    geometry
    add new dicks
        install procedure
        filesystem check
        add a disk using 'sysintall'
    RAID
        GEOM


disk interface
    SCSI                         # expensive
    IDE / ATA
    SATA
    SAS
    USB


disk geometry
    secrot
        indivifual data block
    track
        circle
    cylinder
        circle on all platters
    posision
        CHS
        cylinder, head, sector


disk installation procedure
    connecting the disk
        IDE : master/slave
        SATA
        SCSI : ID, terminator
        power!                   # the most important

    creating device files
        auto created by 'devfs'

    formatting
        low-level
        manufacturer diagnostic utility

    partition and lable
        allow the disk to be treated as a group of independent data
            Ex. root, home, swap partition

        suggestion
            /var, /tmp => separate partition
        establishing logical volumes
        compine multiple partitions into a logical volume
            software RAID
                GEOM
                ZFS

        'newfs' command
            superblock contents  # before i-list
                inode table's size and location
                disk block map
                usage information
                other filesystem’s parameters

        'sync'

        mount
        Ex.
            mount /dev/ad1s1e /home2

        automount at boot time
            write it in /etc/fstab

       swap
            swapon, swapoff, swapctl
            swapinfo, pstat

        'fsck'
            system crash will cause
                inconsistency between memory image and disk contents
         fsck
            examine all local filesystem listed in /etc/fstab at boot time.
(fsck -p)
            automatically correct the following damages:
                unreferenced inodes
                inexplicably large link counts
                unused data blocks not recorded in block maps
                data blocks listed as free but used in file
                incorrect summary information in the superblock



RAID                             # redundant array of inexpensive disks
                                 # combine several physical hard drives into a
logical unit
    features
        fault tolerance
        higher throughput
        real-time recovery
    level
        0~6
        hierarchicak RAID (0 + 1)

    hardware RAID

    software RAID


level
    RAID 0
        500 + 500 = 1000
        stripped data intro several disks
        minimum numbers of drivers: 2
        advantage
            performance
        disadvantage
            no fault tolerance

    RAID 1
        500 + 500 = min (500, 500) = 500
        minimum numbers of drivers: 2

        advantage
            100% redundary of data
        disadvantage
            100% storage overage
            slow write performance

        Hardware and software
            GEOM, ZFS

    RAID 2
        Hamming Code ECC each bit data word

    RAID3 and RAID 4
        blocks by blocks
        bytes by bytes
        parallel transfer with Parity
        minimum number of drives: 3

        advantages:
            very high data transfer rate

        disadvantages:
            transaction rate equal to that of a single disk drive at best

    RAID 5 and RAID 6
        independent Disk with distributed parity blocks
        minimum number of drives: 3/4

        advantage:
            highest read data rate
            medium write data rate

        disadvantage:
            disk failure has a medium impact on throughput
            complex controller design
            when one disk failed, you have to rebuild the RAID array
            "write hole" problem

you will see

    0,           1,    5,        6
    performance, safe, average , more safer than 5



GEOM
    ELI
    JURNAL
    LABEL
    MIRROR
    SRIPE


major RAID control utilities
kernel modules
    /boot/kernel/geom_*


kernel support
    {glabel,gmirror,gstripe,g*} load/unload
    device GEOM_* in kernel config
    geom_*_enable=“YES” in /boot/loader.conf


LABLE
    for GEOM provider labelization
    kernel
        device GEOM_LABEL
        geom_label_load=“YES”
    'glable' command
        # glabel label -v usr da2
        # newfs /dev/label/usr
        # mount /dev/label/usr /usr
        # glabel stop usr
        # glabel clear da2


MIRROR  # for RAID 1
    kernel
        device GEOM_MIRROR
        geom_mirror_load=“YES”
    'gmirror' command
        # gmirror label -v -b round-robin data da0
        # newfs /dev/mirror/data
        # mount /dev/mirror/data /mnt
        # gmirror insert data da1
        # gmirror forget data                <---- this is so funny
        # gmirror insert data da1
        # gmirror stop data
        # gmirror clear da0


SRIPTE # for RAID0
    kernel
        device GEOM_STRIPE
        geom_stripe_load=“YES”
    'gstripe' command
        # gstripe label -v -s 131072 data da0 da1 da2 da3
        # newfs /dev/stripe/data
        # mount /dev/stripe/data /mnt
        # gstripe stop data
        # gstripe clear da0

SA class 5



samba

FTP                              # file transfer protocol

NFS                              # network file system
    mount
    nfsd / nfsiod
    based on RPC

CIFS                             # common internet file system
                                 # M$ 網路上的芳鄰
    SMB                          # server message block
    based on NetBIOS


netBIOS
    name service for registration and resolution
    session service for connection-oriented communication
    datagram (darkgerm?) disrtibution service for connection communication


SMB                              # port 137~139 445(TCP/IP)
    file and printer sharing service
    authentication


NetBIOS (API)
    interrupt file I/O to NetBIOS
    broadcast my name
    NETBEUI                      # with 'token ring'
    WINS
        NetBIOS Name server as a master
        don't need to broadcast frequently


SMB                              # server message block
    SMB -> CIFS -> SMB
    Win7
        SMB 2.1
        SMB 2.2


SAMBA

    a student use a packet to do network analysis of the DEC Pathworks server
software
    sharing files or printers like M$ does
    authenticate user identity like M$ does
    resolve NetBIOS like M$ dose

    install
        /usr/ports/net/samba35
        samba3.6 support SMB2    # for win7

    confuguration files
        /usr/local/etc/smb.conf.default => /usr/local/etc/smb.conf
        /usr/local/etc/lmhosts   # for WINS

    major execution files
        smbd /usr/local/sbin/snbd
            management of sharing directories, files, printers
        nmbd /usr/local/ssbin/nmbd
            resolve NetBIOS name and manage workgroup
        pdbedit /usr/local/bin/pdedit
            manage the samba user database
        smbpasswd /usr/local/bin/smbpasswd
        tdb

        pdbedit -a username      # add user
        pdbedit -x username      # delete user
        pdbedit -r -c username

    smb.conf
        sections
            [....]
            para1 = value1
        global section for global settings
        meta service


starting samba
    /usr/local/etc/rc.d/samba {start|stop}
    /etc/rc.conf
        samba_enable="YES"
        nmbd_enable="YES"


=======================================

ZFS
zetabyte filesystem
    storage pools
        contructed of files, partitions, or entire disks

    data integrity

    capacity
        128-bit file system

    copy on write
        modified data is in a new block

    snapshots, clones, rollbacks
        fast creation
        space efficiency
        clones are writeable snapshots

    dynamic striping

    compression
        lzjb or gzip

    variable block size
        data compression         # CPU is fast than hard diskI/O

    adaptive edianness
        big / little - endian

    encryption
        zfs pool ver30

    platforms
        solaris 10/11
        OpenSolaris
        FreeBSD 8.2-R (v15); 8.2-S, 9.0-, 10.0-C (v28)
        Mac X OS
        Linux

    self healing                 # using checcksum


using ZFS
    /etc/rc.conf
        zfs_enable="YES"
    /etc/rc.d/zfs start


zpool
    zpool create tank
        mirror
        raidz
    zpool add/attach/detach/online/offline
    zpool list/status
    zpool export/import
    zpool upgrade -v/-a
    zpool get/set


zfs
    zfs create
    zfs destroy
    zfs snapshots
        tank/fs0@today
        tank/fs0/./zfs/snapshots/today
    zfs clone
    zfs rollbacks
    zfs list
    zfs mount / unmount
    zfs upgrade -v/-a
    zfs send / receive
    zfs allow / unallow
    zfs hold / holds / release
    zfs diff
    zfs jail / unjail


Ten Ways To Improve ZFS Performance
    1: Add Enough RAM
    2: Add More RAM
    3: Boost Deduplication Performance With Even More RAM
    4: Use SSDs to Improve Read Performance
    5: Use SSDs to Improve Write Performance
    6: Use Mirroring
    7: Add More Disks
    8: Leave Enough Free Space
    9: Hire An Expert
    10: Be An Evil Tuner - But Know What You Do


============================

FTP
    file transfer protocol
    C/S architecture
    separated control/data connections
    Modes
        active  mode    client => server
        passive mode    client <= server

    RFC (reauest for comments)
        RFC 2640                 # UTF-8 support file name
        RFC 2324                 # Hyper text coffee pot control protocol

    security
        FTP transfer data via clear text
        so we need encryption

        two solutions
            FTP over SSH         # sftp
                commands   [O]
                data       [O]
            FTP over TLS         # better performance
                commands   [O]
                data       [X]


pure FTPd
    a FTP server
    support chroot
    anonymous
    virsual users and authentication
    FTP over TLS
    UTF-8
    /usr/ports/ftp/pure-ftpd


pure FTPd tools
    pure-ftpwho
    pure-pw


more tools                       # under /usr/ports/ftp
    pureadmin
    lftp
    wget
    mget
    filezilla

==============================

basic service and settings
    Ex. http, ftp, etc ...


service
    instarll
        ports
        package
        tarballs

    configuration
        configfile
        rc.conf

    startup
        rc.conf used for booting processes

    maintanance


configuration file
    under /usr/local/etc
    program.conf
    programrc
    copy sample files and edit it


RC script
    scripts for start / stop services


dependency!!!!


rc.conf     # after booting
    asdf_enable="YES"


usage
    start, stop, restart
    status
    reload


SA class 4


File system

using 'ls -l' command to get details
Ex.
-rw-r--r-- 1 xatierlike xatierlike 1631 2011-09-14 02:16 class1
    file type
    file access mode             # rwx for read, write, execute
    numbers of inodes
    file user owner
    filegroup owner
    file size
    file last modify time
    file name


file system achitecture
    pathname
    file tree
    mounting
    file type


inode and file
    link
    'ln' command


file access mode
    changing file owner
    freebsd bonus flags  # to protect your important files


file system architecture
                system call
    Application <=========> kernel <=> hardware

    process1, process2, process3....     [user mode]
  -----------------------------------------------------
    virtual file system                  [system mode]
     |
    device drivers ---> devices


purpose of file system
    represent and organize the system's storage
    namespace
    API
    security model
    implementation


system call via APIs
    OS will do the detail jobs


relationship of  API, system call, OS

                   +-- user appication ---
  user        APIs |                     ^
  mode             V                     |
------------------- system call interface ---------------------
  kernel           |                     |
  mode             +---> do some magic  -+





objects in the filesystems
    files and directories
    hardware device files (under /dev/... )
    processes information
    Interprocess communication (IPC)
    shared memory segments (SHM)

    we can uer filesystem interface to access such objects
    Ex. open, read, write, close, seek ... etc.


pathname
    where it is?
    absolute path => start from /
    relative path => start from your current directory

    contrains of pathname
        single componetn <= 255 char
        single absolute path <= 1024 char


file tree
    the data struct of files in your system
    / (root)
    some important directories under root
    /bin & /sbin      user utilities and system programs
    /dev              device
    /etc              system configurations and scripts
    /home             where you live
    /mnt              for system admins to  mount something
    /proc             images and running process
    /usr
        lib           standard libraries for porgrams
        libexec
        obj
        bin, sbin     local executalbe programs
        src           souce files
        include       libraries header files
        local         something loacl
        ports         fucking 'make install clean'

    /var              a lot of things
        db            database
            pkg       database for pkg and ports
            ports
        log           system log
        mail          your mailbox


    learn more:
        http://www.freebsd.org/doc/handbook/dirstructure.html


mointing file system
    'mount' command
    most are disk partitions
    network file servers (NFS)
    memory disk emulators  # man mdconfig
    kernel components


    for a new harddisk
        sysinstall
            configuration
                fdisk lable
                   fd or swap


    mount /dev/ad2sle /home2
    Note: you should mount it on a empty direction


    /etc/fstab
        auto mount at boot time

    'umount' command
     usage:
        unmount {node | devoce}
        Ex. unmount /dev/ad0s1e
        unmount -f                   # force unmount
        lsof / fstat


file types                       # the first character of 'ls -l'
    - regular file
    b block device
    c character device
    d directory
    l symbolic link
    s socket
    p named pipe


'file' command
    determine file type
    /usr/ports/sysutils/file


directory
    .  and ..
        current directory and your father directory
    mkdir / rmdir
        make directory
        remove directory

socket
    created by socket()
    local to a particular host
    be referenced through filesystem object rather than a network port

        process A      process B
           | write      ^
           V            | read
     +----------------------------+
     |      socket buffer         |
     |      [UNIX kernel]         |
     +----------------------------+



named pipe      # FIFO
    'mkfifo' command


link
    symbolic link
    ln -s src dest

inode
    a structure that records info of a file
    'ls -i' to see each file's inode number

    the inode structure
        mode
        owners
        timestamps
        size block
        count
        direct blocks
        single indirect
        double indirect
        triple indirect

filesystem
    boot blocks
    super block
    inode blocks
    date blocks


hardlink and symbolic link
    hardlink
        associate two or more filenames with same inode
        must in the same partition
        ln src dest

    symbolic link
        A file which points to another pathname
        ln -s src dest


file access mode
    rwx for read, write, and exectue   #value 421
    Ex.    rwxr-xr-x, 733
    user, group, other privileges

    'chmod' command
        chmod access-string file
        -R recursivily
    directory must be x then you can cd into it

class          operator        access type
--------------------------------------------
u(user)          +(add)                r
g(group)         -(remove)             w
o(other)         =(set exact)          x
a(all)


setuid, setgid, sticky bit
    the effective uid/gid will be set to the UID/GID of the file
    setuid
        passwd, chsh, crontab
    setgid
        top, fstat, write
    sticky on directory (/tmp)
        do not allow to delete or rename a file unless you are
            the owner of the file
            the owner of the directory
            root

umask
    shell built-in command
    inference the degault permissions given to the files newly created
    777 or 666 xor umask value

change file owner
    'chown' command
    'chgrp' command
    -R recursivily
    Ex.
        chown foo bar
        chown user:grp bar

FreeBSD bonus flags
    'chflags' command
    ls -ol
    'schg' flag to protect important files






screen 用法




       screen - screen manager with VT100/ANSI terminal emulation





Terminal 下:
    screen -ls          # 列出目前有的 screen
    screen -r pid       # 回復某個 screen (之前 detach 掉的)


Screen 裡的組合技:
    ctrl+a, c 的意思是『按下ctrl+a,之後再按c』
    ctrl+a  是 screen 組合鍵都要按的

    ctrl+a, c            # create a new screen
    ctrl+a, p            # previous screen
    ctrl+a, n            # next screen
    ctrl+a, C            # clear the screen.
    ctrl+a, d            # detach the screen
    ctrl+a, k            # kill the current screen
    ctrl+a, l            # Refresh screen
    ctrl+a, w            # show the list of screen
    ctrl+a, i            # info about the screen
    ctrl+a, \            # kill  all screens and return to your shell
    ctrl+a, [0~9]        # switch to screen [0~9]
    ctrl+a, "            # list all screens
    ctrl+a, A            # set title
    ctrl+a, ctrl+a       # recall to previous screen
    ctrl+a, ctrl+x       # lock the screen



SA class 3



user management:
    uid / gid                  # user id / group id
    uid == 0                   # I am a root!
    deamon                     # unprivileged software
    bin                        # system comnands
    sys                        # kernel and memory images
    nobody                     # a Korean song (?


Add a user:
    edit password and group files:
        vipw                   # use vi to edit it
        pw

    set initial password:
        passwd usermane        # set password for an user
        passwd                 # for root

    set quota
        edquota usermane

    create user's home
        mkdir /home/username

    set some startup files
        cp some file like '.tcshrc' for the user

    set file/dir owner to the user
        chown -R username:group /home/user

    the command 'useradd' is your friend!



/etc/passwd                    # data separated by ':'
    login name
    passwd (Encrypted)
    uid
    default gid
    GECOS info
    Home directory
    Login shell


Encrypted password:
    /etc/master.passwd         # for BSD
    /etc/shadow                # for Linux

Encrypted method:
    DES
        8 char => 13 char
    md5
        arbitary length => 34 char starts with $1$
    blf
        arbitary length => 60 chr starts with $2$


GECOS:                         # data separated by ','
    General Electric Comprehensive Operation System
    finger username
    chfn to change it
    it is useless


Login shell
    /bin/{sh, csh, tcsh, bash, zsh}
    chsh to change it


/etc/group
    group name
    encrypted password
    GID
    list of members, separated by “,”
    only members in wheel group can do 'su' command


/etc/master.passwd             # for freeBSD
    vipw to edit
    additional fields
        login class
            /etc/login.conf
        passwd change time
        account expiration time


/etc/login.conf
    cap_mkdb /etc/login.conf   => login.cong.db


add user in Linux:
    /etc/passwd
        pwconf transfer to /etc/shadow
        Login name
        Encrypted Passwd
        Date of last password change
        ...

    init password
        passwd username

    set quota
        edquota username

    make home
        mkdir /home/username

    start files
        system wide:
            /etc/{csh.cshrc, csh.login, csh.logout, profile}
        private (home)
            .cshtc .tcshrc .login .logout
            .profile (sh)
            .vimrc   (vim)
            .xinitrc (startx)

    change owner
        chown -R username:group /home/username

Remove accounts
    delete user
        vipw, pw userdel             # BSD
        edit /etc/passwd and pwconv  # Linux

    backup home and mail
        tar /home/username and /var/mail/username
        chmod 600 the tar-ed files
    Delete home and mailbox
        rm -rf /home/username /var/mailusername

disable login
     change user's login shell as /sbin/nologin
     put a '#' or '-' in front of the account
     put a '*' in the encrypted password field

the root (God)
    root is God, i.e. you can do anything!
    uid == 0

    becoming root
        change your uid to 0
        sshd:
            edit /etc/ssh/ssh_config
            PermitRootLogin yes      # don't do it!
    su
        su username
        change to target user

    sudo
        a limited su
        visudo to edit sudoers
        edit /usr/local/etc/sudoers

===============================

chinese word

    ascii
        8 bits for 256 char
        0x00 ~ 0x1F : control characters
        0x20 ~ 0x7F : printable characters
    Big5
    unicode
        utf8, utf16

    chinese environment:
        訊息
        顯示
        輸入
        列印
        處理

    locale
        LC_ALL
        LC_CTYPE
        LC_MESSAGES
        LC_TIME
        LC_NUMERIC
        LC_MONETARY
        LC_COLLATE
        LANG

        power: LC_ALL > LC_* > LANG

    tcsh shell
        setenv LC_TYPE zh_TW.UTF-8
    bash
        export LC_CTYPE=zh_TW.UTF-8

    font type
        bitmapped font
        truetype font (ttf)


===============================

Controlling Processes:
    'program' to 'process'
        program is dead and lie on disk    # EX. /usr/bin/grep
        when you execute it, it becomes a process
        process is alive, it resides in memory
        process lives in
            an address space in memory
            kernel data structures

    attribute of the process
        PID PPID               # Process ID and its father's PID
        UID EUID               # User ID and Effective user ID
        GID EGUD               # Group ID amd Effective group ID
        Niceness               # priority of the process

        fork()
            == 0 child
             > 0 parent

    a life of process
        fork
            child has the same program context
        exec
            child use exec to change the program context
        exit
            child use _exit to tell kernel that it is ready to die and this
death
            should be acknowledged by the child’s parent
        wait
            parent use wait to wait for child’s death
            If parent died before child, this orphan process will have init as
it’s new parent

    UID, GID, EUID, EGID
        the effective uid and gid can be used to enable ir restric the
additional permissions

    Signal -- what happen to the process
        signal can be sent
            as a means of communication
            to kill, intertupt, or suspend process
                Ex. Ctrl-c, Ctrl-z, bg, fg  (background / frontground)

    you can catch, ignore block the SIG

    Kill a pid
        kill [-signal] pid
            kill -9
            kill -15

        killall name

    Niceness
        high nice value => low priority (好人卡)
        inherent property: 當你爸是好人,你也是好人
        only root can set nice value

    Process States
        I  Idle
        R  Runnable
        S  Slepping
        T  Stopped
        Z  Zombie
        D  in Disk

    ps command
        ps aux
        ps auxww
        ps -j
        ps -o
        ps -L

    top / htop

    Runaway process
        kill it!
            kill -15
            kill -9
        renice a higher nice value   # 發好人卡給他


SA class 2




Kernel and Shell

Hardware => kernel => shell => you

shell: +-=> Fetch command => analyze => execute -+
       |                                                                         |
       +-----------------------------------------------------------------+

startup files

sh
    /etc/profile        login shell, system wide
    ~/.profile          login shell
    ENV                 always

csh
    /etc/csh.cshrc      always , system wide
    /etc/csh.login      login shell, system wide
    ~/.cshrc            always
    ~/.login            login shell
    ~/.logout           logout shell
    /etc/csh.logout     logout shell, system wide

tcsh
    ~/.tcshrc  login shell

bash
    /etc/profile
    ~/.bash_profile
    ~/.bash_login
    ~/.profile
    ~/.bashrc
    BASH_ENV

Shell special characters
Reduce typin as as possible, be lazy zzZ
    *      Match any string of characters
    ?      Match any single alohanumeric characters
    [...]  Match any single char within []
    [!...] Match any single char not in []
    ~      Home
    #      this is a comment
    ;      command separator
    &&     execute first one and execute second if first one success (exit
code: 0)
    ||     execute first one and execute second if first one fail (exit code:
!= 0)
    \      Excape char or command continueation indicator
    &      background execution


shell ENV variables:
    control shell behaviors

to dump them:
    "env" command

To get value:
    $variable_name   or ${varible_name}

Useful env variables
sh   / csh        what it is
HOME / HOME       home
MAIL / MAIL       mailbox
PATH / PATH       search path
PS1  / prompt     prompt string
PS2  / prompt2
     / prompt3
IFS  /            internal field separators
     / history    Number of history commands


variables and string quotes

assignment:
    sh:  var=value     csh:  set var=value

get variavle:
    $var or ${var}
    substitution stdout `cmd`
    'string' without substitution
    "string" with substitution

Assignment:

    local variables
        sh: my=test        csh: set my=test

    global variables
        sh: export my      csh: setenv my test


shell I/O:
    stdin  0
    stdout 1
    stderr 2
    user defined: 3~19

redirection:
    change the direction of shess I/O
    creat files
    append to files
    use existing files as input
    merge output streams
    use part of shell command as input

Usage:
    >     open the following file as stdin
    <     open the following file as stdout
    >>    append to the following file
    >&    merge stdout with stderr
    |     pipe stdout into stdin

PIPE:

             pipe   pipe
stdin => cmd1 ==> cmd2 => stdout
              \         \
               ->stderr  ->stderr


build-in shell commands:
    alias / cd / echo / eval / exec / exit
    jobs / kill / fg / bg / set / export
    hash / umask

Useful commands:
    passwd, chsh, chfn, chpass
    pid: ps, top
    directory: ls, mkdir/rmdir
    file: cp/mv/rm
    Email reader: mutt
    News reader: tin
    Connecting: ssh/telnet
    Manual: man, info
    Editor: vim, joe, ee, …etc.
    File Transmittion: ftp, ncftp, lftp, scp, wget, curl
    Compilers: gcc, g++, javac
    Scripting: perl, php, ruby, python
    login/exit/logout/screen

=================================

single user mood => read only
    read only
    mount -u /
    mount -a -t ufs
    swapon -a

how to shut dowm or reboot:
    Turning off the power     <--- don't do that
    shutdown -h               # halt
    shutdown -r               # reboot
    kill -TERM 1              # kill init

    time format (+m):
        hh:mm                 # for Linux
        yymmddhhmm            # for FreeBSD

    power off
        shutdown -p now

=================================
Installing Apps
    Package: (Pre-built)
        Linux: rpm, yum, dpkg
        FreeBSD: pkg_add, pkg_delete, pkg_info, pkg_version
    Source:
        Tarball
        tar zxvf source.tar.gz
        cd source
        ./configure [options]
        make
        make install

Three technologes:
    Packages     Pre-built!
    Ports        /usr/ports/.....
    Tarball      Fetch from internet

pkg_add                   # add a package
    pkg_dd pkg_name
    pkg_add -r pkg_name   # while you don't know the name
pkg_info                  # see some infomation, btw, use it with grep :)
pkg_delete                #delete a package
    pkg_delete pkg_name


How to use ports:
    to find where the application is
    $ whereis application_name
    goto its directory
    $ cd /usr/ports/.../...
    install it! Ports will fetch the tarball and compile the source code
    make && make install clean

portsnap
/etc/portsnap.conf
=> SERVERNAME=portsnap.tw.FreeBSD.org
sudo portsnap fetch extract update        # update your ports

note: use 'rehash' command after install an application  # for tcsh


=================================
X window
    X can be called X, X11, X window
    client-server model
    'Project Athena' @ MIT in 1984


Architecture:
    client: request display service
    server: provide display service
    communicated with X Protocol

Client:
    An application written in X libraries (e.g. Xlib)
    Request service
    Receive events from X server

Server:
    Runs locally and accepys multiple X clients

X protocol:
    local and network based computing look and feel the same

X11 implementation:
    XFree86
    Xorg

window manager:
    A special X Client provides certain look-and-feel window in front of you
    Background desktop theme
    control windows' behaviors
        size:     resize, minimize, maximize
        position: overlap, move

Examples:

     Gnome, KDE, Xfce ...

xdm
    X Display Manager

x11 forwarding


SA class 1


小整理一下上學期 SA 上課筆記

===========================================


SA 1st class (09/13)

資通安全學程網站
isc.cs.nctu.edu.tw

good habits for system admins:
read book and practice at least 6 hours every week
collect information on the internet

chinese resource:
vbird's site is old
try to read ENGLISH references

class websites (PDFs and HWs):
www.cs.nctu.edu.tw/~huanghs/course/sysadm2011

textbook:
<<UNIX and Linux system administration handbook>> 4e

scores:
mid 15%
final 20%
homeworks 60~70%
No delay work!!
4 exercises
1 team projects

background knowledge:
basic Unix command
TCP/IP Networking

We use:
FreeBSD 8.2 release    # 9.0 is comming soon

FreeBSD Type:
-----------+------------------------> current
           |
           +------------+-----------> stable
                        |
                        +-----------> release


Version number:  A.B.C-Type
A: major ver num
B: minor ver num
C: slight patch ver num
Type: prerelease, beta, rc, release, stable, current
release is for beginners

installation:
Slice is equal to the partition of common use
that is: partition => slics

Ex. ad0s1
ad / da
ad: IDE, SATA
da SCSI, usb stick

install FreeBSD step by step:
hardware
obtaining installion file
boot form CD (DVD)
FreeBSD installer: sysinstall
Partition Label Distribution Media Commit
Post installation configurations

Hardware:
CPU: 32/64 bit
RAM: Size
HD: Size amount SCSI or IDE
VGA: Brand ram size
Sound: Brand
Network Interface Card: Brand, IP, Netmask, getaway, Hostname, DNS
# 這裡感謝 kvchung 提供 IP 和 hostname

Last:
Beging experts!

Reference:
http://www.tw.freebsd.org/doc/zh_TW/books/handbook/install.html
http://netlab.cse.yzu.edu.tw/~statue/freebsd/docs/cfreebsd/
Extra:
ls 十大指令之首


Thursday, April 5, 2012

Dannvix: Presentation Best Practice

昨天看了 CrBoy 大大的 talk 投影片後

師大的    黑鬼    前輩 Dannvix 大大也慷慨解囊的將他之前做過的投影片拿出來與大家分享

如何準備演講與投影片





說到做簡報,便想到這幾年幫學弟妹修寒訓教學的經驗XD

想當初也是從完全不會到現在也逐漸培養出自己簡報風格 lol

Wednesday, April 4, 2012

Crboy: 那些老師沒教的事

小畢大大在成大 talk 的簡報釋出囉!

提到了資工系學生很多應該要學但是沒教的事

小弟獲益匪淺 <(_ _)>




沒有聽到現場超可惜的



小畢的 blog :  那些老師沒教的事

直接看簡報!