• If we have a limited connectivity to the world from current location, but still can connect to a shell account fully open to the world (or open to the other non-public network), than dynamic port forwarding available in ssh can save us. This feature (accessible by -D option) in fact makes ssh acting as SOCKS server. OK, but what can we do if our application doesn't support SOCKS proxy? It's important question, because vast majority of software is unaware of such protocol. In Linux we have a great tsocks (http://tsocks.sourceforge.net/), shell wrapper which transparently allow an application to use SOCKS proxy. In Windows there is FreeCap (http://www.freecap.ru/eng/), which does the same thing, but in a different way. Nice, but what if we have dozens of machines to set up. Teaching all users how to use any of mentioned application can be also really inconvenient. Making SOCKS proxy transparent will solve (almost?) all our problems. Is it feasible? YES, but you must have an access to superuser account on a gateway server (it can be also any other server, but gateway is used here for simplicity).

    I'm assuming that you already have SOCKS server bound to localhost on standard port 1080 (e.g. you started ssh with -D1080).

    1. Install libevent (http://www.monkey.org/~provos/libevent/). It can be already available in your distribution repository. This will be used for compiling in next step, so you must get development package (usually libevent-dev).
    2. Download transocks_ev (http://oss.tiggerswelt.net/transocks_ev/ - use svn or simply wget files) and build it using make.
    3. Run transocks_ev with following arguments: -p 12345 -H localhost -s 1080 -S localhost. -H tells where to bind transocks_ev, -p where to listen for incoming connections, -s and -S point SOCKS server.
    4. Change iptables configuration. This step requires superuser powers. Below you have example script (heavily based on tranSOCKS_ev's README) with some common alternatives:
      #!/bin/sh
       
      IPTABLES="/sbin/iptables"
       
      TRANSOCKS_PORT="12345"
      SOCKS_HOST="192.168.0.1"
      SOCKS_PORT="1080"

      # Create our own chain
      $IPTABLES -t nat -N TRANSOCKS 
      # Do not try to redirect local traffic
      $IPTABLES -t nat -I TRANSOCKS -o lo -j RETURN  
      # Do not redirect LAN traffic and some other reserved addresses.
      $IPTABLES -t nat -A TRANSOCKS -d 0.0.0.0/8 -j RETURN $IPTABLES -t nat -A TRANSOCKS -d 10.0.0.0/8 -j RETURN
      $IPTABLES -t nat -A TRANSOCKS -d 127.0.0.0/8 -j RETURN
      $IPTABLES -t nat -A TRANSOCKS -d 169.254.0.0/16 -j RETURN
      $IPTABLES -t nat -A TRANSOCKS -d 172.16.0.0/12 -j RETURN
      $IPTABLES -t nat -A TRANSOCKS -d 192.168.0.0/16 -j RETURN
      $IPTABLES -t nat -A TRANSOCKS -d 224.0.0.0/4 -j RETURN
      $IPTABLES -t nat -A TRANSOCKS -d 240.0.0.0/4 -j RETURN  
      # Do not redirect traffic for the SOCKS server (not needed if server is already excluded by above rules)
      $IPTABLES -t nat -I TRANSOCKS -p tcp -d $SOCKS_HOST --dport $SOCKS_PORT -j RETURN  
      ## Redirect only specified addresses.
      #$IPTABLES -t nat -A TRANSOCKS -m iprange ! --dst-range 123.45.6.78-123.45.6.90 -j RETURN 
      # Redirect all traffic that gets to the end of our chain
      $IPTABLES -t nat -A TRANSOCKS -p tcp -j REDIRECT --to-port $TRANSOCKS_PORT  
      # Filter (i.e. just branch into the TRANSOCKS-chain) all traffic that is routed over this host
      $IPTABLES -t nat -A PREROUTING -j TRANSOCKS  
      ## Filter all traffic from the own host (BE CAREFUL HERE IF THE SOCKS SERVER RUNS ON THIS MACHINE!)
      #$IPTABLES -t nat -A OUTPUT -j TRANSOCKS
    5. Now all hosts with your machine as a gateway use SOCKS proxy accordingly to iptables rules. Transparently!
    6. Open another beer bottle and enjoy. 8-)
  • This "vi" tutorial is intended for those who wish to master and advance their skills beyond the basic features of the basic editor. It covers buffers, "vi" command line instructions, interfacing with UNIX commands, and ctags. The vim editor is an enhanced version of vi. The improvements are clearly noticed in the handling of tags.

    The advantage of learning vi and learning it well is that one will find vi on all Unix based systems and it does not consume an inordinate amount of system resources. Vi works great over slow network ppp modem connections and on systems of limited resources. One can completely utilize vi without departing a single finger from the keyboard. (No hand to mouse and return to keyboard latency)

    NOTE: Microsoft PC Notepad users who do not wish to use "vi" should use "gedit" (GNOME edit) or "gnp" (GNOME Note Pad) on Linux. This is very similar in operation to the Microsoft Windows editor, "Notepad". (Other Unix systems GUI editors: "dtpad", which can be found in /usr/dt/bin/dtpad for AIX, vuepad on HP/UX, or xedit on all Unix systems.)


    Related YoLinux Tutorials:

    °Software development tools

    °Advanced VI

    °Emacs and C/C++

    °C++ Info, links

    °MS/Visual C++ Practices

    °C++ Memory corruption and leaks

    °C++ String Class

    °C++ STL vector, list

    °Posix Threads

    °Fork and Exec

    °GDK Threads

    °Clearcase Commands

    °YoLinux Tutorials Index


     


    Free Information Technology Magazine Subscriptions and Document Downloads


    Free Information Technology Software and Development Magazine Subscriptions and Document Downloads


    Vim Installation:

    Red Hat / CentOS / Fedora:

    • rpm -ivh vim-common-...rpm vim-minimal-...rpm vim-enhanced-...rpm vim-X11-...rpm
    • yum install vim-common vim-minimal vim-enhanced vim-X11
    Ubuntu / Debian:
    • apt-get install vim vim-common vim-gnome vim-gui-common vim-runtime
    Compiling Vim from source:
    • Download vim source from http://vim.org
    • tar xzf vim-7.0.tar.gz
    • cd vim70
    • ./configure --prefix=/opt --enable-cscope
    • make
    • make install
    Basic "vi" features

    One edits a file in vi by issuing the command: vi file-to-edit.txt

    The vi editor has three modes, command mode, insert mode and command line mode.

    1. Command mode: letters or sequence of letters interactively command vi. Commands are case sensitive. The ESC key can end a command.
    2. Insert mode: Text is inserted. The ESC key ends insert mode and returns you to command mode. One can enter insert mode with the "i" (insert), "a" (insert after), "A" (insert at end of line), "o" (open new line after current line) or "O" (Open line above current line) commands.
    3. Command line mode: One enters this mode by typing ":" which puts the command line entry at the foot of the screen.

    Partial list of interactive commands:

    Cursor movement:
    KeystrokesAction
    h/j/k/lMove cursor left/down/up/right
    spacebarMove cursor right one space
    -/+Move cursor down/up in first column
    ctrl-dScroll down one half of a page
    ctrl-uScroll up one half of a page
    ctrl-fScroll forward one page
    ctrl-bScroll back one page
    M (shift-h)Move cursor to middle of page
    HMove cursor to top of page
    LMove cursor to bottom of page
    W
    w
    5w
    Move cursor a word at a time
    Move cursor ahead 5 words
    B
    b
    5b
    Move cursor back a word at a time
    Move cursor back a word at a time
    Move cursor back 5 words
    e
    5e
    Move cursor to end of word
    Move cursor ahead to the end of the 5th word
    0 (zero)Move cursor to beginning of line
    $Move cursor to end of line
    )Move cursor to beginning of next sentence
    (Move cursor to beginning of current sentence
    GMove cursor to end of file
    %Move cursor to the matching bracket.
    Place cursor on {}[]() and type "%".
    '.Move cursor to previously modified line.
    'aMove cursor to line mark "a" generated by marking with keystroke "ma"
    'AMove cursor to line mark "a" (global between buffers) generated by marking with keystroke "mA"
    ]'Move cursor to next lower case mark.
    ['Move cursor to previous lower case mark.

    Editing commands:

    KeystrokesAction
    iInsert at cursor
    aAppend after cursor
    AAppend at end of line
    ESCTerminate insert mode
    uUndo last change
    UUndo all changes to entire line
    oOpen a new line
    dd
    3dd
    Delete line
    Delete 3 lines.
    DDelete contents of line after cursor
    CDelete contents of line after cursor and insert new text. Press esc key to end insertion.
    dw
    4dw
    Delete word
    Delete 4 words
    cwChange word
    xDelete character at cursor
    rReplace character
    ROverwrite characters from cursor onward
    sSubstitute one character under cursor continue to insert
    SSubstitute entire line and begin to insert at beginning of line
    ~Change case of individual character
    ctrl-a
    ctrl-x
    Increment number under the cursor.
    Decrement number under the cursor.
    /search_string{CR}Search for search_string
    ?search_string{CR}Search backwards (up in file) for search_string
    /\<search_string\>{CR}Search for search_word
    Ex: /\<s\>
    Search for variable "s" but ignore declaration "string" or words containing "s". This will find "string s;", "s = fn(x);", "x = fn(s);", etc
    nFind next occurrence of search_word
    NFind previous occurrence of search_word
    .repeat last command action.

    Terminate session:

    • Use command: ZZ
      Save changes and quit.
    • Use command line: ":wq"
      Save (write) changes and quit.
    • Use command line: ":w"
      Save (write) changes without quitting.
    • Use command line: ":q!"
      Ignore changes and quit. No changes from last write will be saved.
    • Use command line: ":qa"
      Quit all files opened.

    Advanced "vi" features

    Interactive Commands:

    • Marking a line:
      Any line can be "Book Marked" for a quick cursor return.
      • Type the letter "m" and any other letter to identify the line.
      • This "marked" line can be referenced by the keystroke sequence "'" and the identifying letter.
        Example: "mt" will mark a line by the identifier "t".
        "'t" will return the cursor to this line at any time.
        A block of text may be referred to by its marked lines. i.e.'t,'b
    • vi line buffers:
      To capture lines into the buffer:
      • Single line: "yy" - yanks a single line (defined by current cursor position) into the buffer
      • Multiple lines: "y't" - yanks from current cursor position to the line marked "t"
      • Multiple lines: "3yy" - yank 3 lines. Current line and two lines below it.
      Copy from buffer to editing session:
      • "p" - place contents of buffer after current line defined by current cursor position.
    • vim: Shift a block of code left or right:
      • Enter into visual mode by typing the letter "v" at the top (or bottom) of the block of text to be shifted.
      • Move the cursor to the bottom (or top) of the block of text using "j", "k" or the arrow keys.
        Tip: Select from the first collumn of the top line and the last character of the line on the bottom line.
        Zero ("0") will move the cursor to the first character of a line and "$" will move the cursor to the last character of the line.
      • Type >> to shift the block to the right.
        Type << to shift the block to the left.
      Note: The number of characters shifted is controlled by the "shift width" setting. i.e. 4: ":set sw=4"
      This can be placed in your $HOME/.vimrc file.

    Command Line:

    • command options:
      The vi command line interface is available by typing ":". Terminate with a carriage return.
      Example commands:
      • :help topic
        If the exact name is unknown, TAB completion will cycle through the various options given the first few letters. Ctrl-d will print the complete list of possibilites.
      • :set all - display all settings of your session.
      • :set ic - Change default to ignore case for text searches
        Default is changed from noignorecase to ignorecase. (ic is a short form otherwise type set ignorecase)
      • Common options to set:
        Full "set" CommandShort formDescription
        autoindent/noautoindentai/noai{CR} returns to indent of previous line
        autowrite/noautowriteaw/noawSee tags
        errorbells/noerrorbellseb/noebSilence error beep
        flash/noflashfl/noflScreen flashes upon error (for deaf people or when noerrorbells is set)
        tabstop=8tsTab key displays 8 spaces
        ignorecase/noignorecaseic/noicCase sensitive searches
        number/nonumbernu/nonuDisplay line numbers
        showmatch/noshowmatchno abbreviationsCursor shows matching ")" and "}"
        showmode/noshowmodeno abbreviationsEditor mode is displayed on bottom of screen
        taglengthtlDefault=0. Set significant characters
        closepunct='".,;)]} % key shows matching symbol.
        Also see showmatch
        linelimit=1048560 Maximum file size to edit
        wrapscan/nowrapscanws/nowsBreaks line if too long
        wrapmargin=0/nowrapmarginwm/nowmDefine right margin for line wrapping.
        list/nolist Display all Tabs/Ends of lines.
        bg=dark
        bg=light

        VIM: choose color scheme for "dark" or "light" console background.

    • Executing Unix commands in vi:
      Any UNIX command can be executed from the vi command line by typing an "!" before the UNIX command.
      Examples:
      • ":!pwd" - shows your current working directory.
      • ":r !date" - reads the results from the date command into a new line following the cursor.
      • ":r !ls -1" - Place after the cursor, the current directory listing displayed as a single column.
    • Line numbers:
      Lines may be referenced by their line numbers. The last line in the file can be referenced by the "$" sign.
      The entire file may be referenced by the block "1,$" or "%"
      The current line is referred to as "."
      A block of text may be referred to by its marked lines. i.e. 5,38 or 't,'b
    • Find/Replace:
      Example:
      • :%s/fff/rrrrr/ - For all lines in a file, find string "fff" and replace with string "rrrrr" for the first instance on a line.
      • :%s/fff/rrrrr/g - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line.
      • :%s/fff/rrrrr/gc - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line. Ask for confirmation
      • :%s/fff/rrrrr/gi - For all lines in a file, find string "fff" and replace with string "rrrrr" for each instance on a line. Case insensitive.
      • :'a,'bs/fff/rrrrr/gi - For all lines between line marked "a" (ma) and line marked "b" (mb), find string "fff" and replace with string "rrrrr" for each instance on a line. Case insensitive.
      • :%s/*$/ - For all lines in a file, delete blank spaces at end of line.
      • :%s/\(.*\):\(.*\)/\2:\1/g - For all lines in a file, move last field delimited by ":" to the first field. Swap fields if only two.
      For more info type:
      • :help substitute
      • :help pattern
      • :help gdefault
      • :help cmdline-ranges
    • Sorting:
      Example:
      • Mark a block of text at the top line and bottom line of the block of text. i.e. "mt" and "mb" on two separate lines. This text block is then referenced as "'t,'b.
      • :'t,'b !sort

    • Moving columns, manipulating fields and awk:
      :'t,. !awk '{print $3 " " $2 " " $1}' - This will reverse the order of the columns in the block of text. The block of text is defined here as from the line marked with the keystroke "bt" and the current line ("."). This text block is referenced as "'t,."
                    aaa bbb ccc              ccc bbb aaa
                    xxx yyy zzz   becomes->  zzz yyy xxx
                    111 222 333              333 222 111
      
    • Source Code Formatting: C++/Java
      • Use vim visual text selection to mark the lines to format (beautify):
        • eg. Whole file:
          • Go to first line in file: shift-v
          • Go to last line in file: shift-g
          • Select the key equals: =
        This will align all braces and indentations. For the equivalent in emacs see the YoLinux emacs tutorial.
    • Text Formatting:
      • Mark a block of text at the top line and bottom line of the block. i.e. "mt" and "mb" on two separate lines.
      • Example: ":'t,'b !nroff"
      • You can insert nroff commands i.e.:
        .ce 3Center the next three lines
        .fiFill text - left and right justify (default)
        .nfNo Fill
        .ls 2Double line spacing
        .spSingle line space
        .sv 1.0iVertical space at top of page space
        .nsTurn off spacing mode
        .rsRestore spacing mode
        .ll 6.0iLine length = 6 inches
        .in 1.0iIndent one inch
        .ti 1.0iTemporarily one time only indent one inch
        .pl 8.0iPage length = 8 inches
        .bpPage break
        Example:
        .fi
        .pl 2i
        .in 1.0i
        .ll 6.0i
        .ce
        Title to be centered
        .sp
        The following text bla bla bla bla bla bla bla bla bla bla 
        bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla 
        bla bla bla bla bla bla bla bla bla bla bla bla bla bla 
        bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla 
        bla bla bla bla bla
        

        Becomes:

                                 Title to be centered
        
                  The following text bla bla bla bla bla bla bla bla
                  bla  bla  bla  bla bla bla bla bla bla bla bla bla
                  bla bla bla bla bla bla bla bla bla  bla  bla  bla
                  bla  bla  bla  bla bla bla bla bla bla bla bla bla
                  bla bla bla bla bla bla bla bla bla  bla  bla  bla
                  bla bla bla bla
        
        
        
    • Spell Checking:
      • Mark a block of text by marking the top line and bottom line of the block. i.e. "mt" and "mb" on two separate lines.
      • :'t,'b !spell will cause the block to be replaced with misspelled words.
      • Press "u" to undo.
      • Proceed to correct words misspelled.
    • Macros:
      :map letter commands_strung_together
      :map - lists current key mappings
      Example - :map g n cwNEW_WORD{ctrl-v}{esc}i{ctrl-v}{CR}
      This example would find the next search occurrence, change the word and insert a line feed after the word. The macro is invoked by typing the letter "g".
      • Control/Escape/Carriage control characters must be prefixed with ctrl-V.
      • Choose a letter which is not used or important. (i.e. a poor choice would be "i" as this is used for insert)
    • Double spacing:
      • :%s/$/{ctrl-V}{CR}/g
        This command applies an extra carriage return at the end of all lines
    • Strip blanks at end of line:
      • :%s/{TAB}*$//
    • Strip DOS ctrl-M's:
      • :1,$ s/{ctrl-V}{ctrl-M}//

      Note: In order to enter a control character, one muust first enter ctrl-v. This is true throughout vi. For example, if searching for a control character (i.e. ctrl-m): /ctrl-v ctrl-M If generating a macro and you need to enter esc without exiting the vi command line the esc must be prefixed with a ctrl-v: ctrl-v esc.
    • Editing multiple files:
      • vi file1 file2 file3
      • :n Edit next file (file2)
      • :n Edit next file (file3)
      • :rew Rewind to the first file (file1)
    • Line folding:

      Many times one may encounter a file with folded lines or may wish to fold lines. The following image is of a file with folded lines where each "+" represents a set of lines not viewed but a marker line prefixed with a "+" is shown stating how many lines have been folded and out of view. Folding helps manage large files which are more easily managed when text lines are grouped into "folds".

      Example: vim /usr/share/vim/vim63/plugin/netrw.vim

      VIM folded lines

      Keystrokes:

      KeystrokeDescription
      zRUnfold all folded lines in file.
      zaOpen/close (toggle) a folded group of lines.
      zAOpen a closed fold or close an open fold recursively.
      zcClose a folded group of lines.
      zCClose all folded lines recursively.
      zdDelete a folded line.
      zDDelete all folded lines recursively.
      zEEliminate all folded lines in file.
      zFCreate "N" folded lines.
    • Hyper-Linking to include files:
      • Place cursor over the file name (i.e. #include "fileABC.h")
      • Enter the letter combination: gf
        (go to file)
      This will load file fileABC.h into vim. Use the following entry in your ~/.vimrc file to define file paths. Change path to something appropriate if necessary.
      "Recursively set the path of the project.
      set path=$PWD/**
      
    • Batch execution of vi from a command file:
      Command file to change HTML file to lower case and XHTML compiance:
      :1,$ s/<HTML>/<html>/g
      :1,$ s/<\/HTML>/<\/html>/g
      :1,$ s/<HEAD>/<head>/g
      :1,$ s/<\/HEAD>/<\/head>/g
      :1,$ s/<TITLE>/<title>/g
      :1,$ s/<\/TITLE>/<\/title>/g
      :1,$ s/<BODY/<body/g
      :1,$ s/<\/BODY/<\/body/g
      :1,$ s/<UL>/<ul>/g
      :1,$ s/<\/UL>/<\/ul>/g
      ...
      ..
      .
      :1,$ s/<A HREF/<a href/g
      :1,$ s/<A NAME/<a name/g
      :1,$ s/<\/A>/<\/a>/g
      :1,$ s/<P>/<p>/g
      :1,$ s/<B>/<b>/g
      :1,$ s/<\/B>/<\/b>/g
      :1,$ s/<I>/<i>/g
      :1,$ s/<\/I>/<\/i>/g
      :wq
             
      
      Execute: vi -e file-name.html < ViCommands-HtmlUpdate.txt

      [Potential Pitfall]: This must be performed while vim has none of the files open which are to be affected. If it does, vim will error due to conflicts with the vim swap file.


    Tagging:

    This functionality allows one to jump between files to locate subroutines.

    • ctags *.h *.c This creates a file names "tags".

    Edit the file using vi.

    • Unix command line: vi -t   subroutine_name This will find the correct file to edit.
      OR
    • Vi command line: :tag subroutine_name This will jump from your current file to the file containing the subroutine. (short form :ta subroutine_name )
      OR
    • By cursor position: ctrl-] Place cursor on the first character of the subroutine name and press ctrl-] This will jump to the file containing the subroutine.
      Note: The key combination ctrl-] is also the default telnet connection interrupt. To avoid this problem when using telnet block this telnet escape key by specifying NULL or a new escape key:
      • telnet -E file-name
      • telnet -e "" file-name

    In all cases you will be entered into the correct file and the cursor will be positioned at the subroutine desired.
    If it is not working properly look at the "tags" file created by ctags. Also the tag name (first column) may be abbreviated for convenience. One may shorten the significant characters using :set taglength=number

    Tag Notes:

    • A project may have a tags file which can be added and referred to by: :set tags=tags\ /ad/src/project1.tags
      A "\" must separate the file names.
    • :set autowrite will automatically save changes when jumping from file to file, otherwise you need to use the :w command.

    vim tagging notes: (These specific tag features not available in vi)

    Tag CommandDescription
    :tag start-of-tag-name_TABVim supports tag name completion. Start the typing the tag name and then type the TAB key and name completion will complete the tag name for you.
    :tag /search-stringJump to a tag name found by a search.
    ctrl-]The vim editor will jump into the tag to follow it to a new position in the file or to a new file.
    ctrl-tThe vim editor will allow the user to jump back a level.
    (or :pop)
    :tselect <function-name>When multiple entries exist in the tags file, such as a function declaration in a header file and a function definition (the function itself), the operator can choose by issuing this command. The user will be presented with all the references to the function and the user will be prompted to enter the number associated with the appropriate one.
    :tnextWhen multiple answers are available you can go to the next answer.
    :set ignorecase
    (or :set ic)
    The ignore case directive affects tagging.
    :tagsShow tag stack (history)
    :4popJump to a particular position in the tag stack (history).
    (jump to the 4th from bottom of tag stack (history).
    The command ":pop" will move by default "1" backwards in the stack (history).)
    or
    :4tag
    (jump to the 4th from top of tag stack)
    :tnextJump to next matching tag.
    (Also short form :tn and jump two :2tnext)
    :tpreviousJump to previous matching tag.
    (Also short form :tp and jump two :2tp)
    :tfirstJump to first matching tag.
    (Also short form :tf, :trewind, :tr)
    :tlastJump to last matching tag.
    (Also short form :tl)
    :set tags=./tags,./subdir/tags
    
    Using multiple tag files (one in each directory).
    Allows one to specify all tags files in directory tree: set tags=src/**/tags
    Use Makefile to generate tags files as well as compile in each directory.

    Links:


    The ctags utility:

    There are more than one version of ctags out there. The original Unix version, the GNU version and the version that comes with vim. This discussion is about the one that comes with vim. (default with Red Hat)

    For use with C++:

    • ctags version 5.5.4:
         ctags *.cpp ../inc/*.h
    • ctags version 5.0.1:
         ctags --lang=c++ --c-types=+Ccdefgmnpstuvx *.cpp ../inc/*.h

    To generate a tags file for all files in all subdirectories: ctags -R .

    The ctags program which is written by the VIM team is called " Exuberant Ctags" and supports the most features in VIM.

    Man page: ctags - Generate tag files for source code


    Defaults file:

    VIM: $HOME/.exrc

    • ~/.vimrc
    • ~/.gvimrc
    • ~/.vim/ (directory of vim config files.)

    VI: $HOME/.exrc

    Example:
             set autoindent
             set wrapmargin=0
             map g hjlhjlhjlhlhjl
             "
             " S = save current vi buffer contents and run spell on it,
             "     putting list of misspelled words at the end of the vi buffer.
             map S G:w!^M:r!spell %^M
             colorscheme desert
             "Specify that a dark terminal background is being used.
             set bg=dark
            
    

    Notes:

    • Look in /usr/share/vim/vim61/colors/ for available colorschemes.
      (I also like "colorscheme desert")
    • Alternate use of autoindent: set ai sw=3


    Using vim and cscope:

    Cscope was developed to cross reference C source code. It now can be used with C++ and Java and can interface with vim.

    Using Cscope to cross reference souce code will create a database and allow you to traverse the source to find calls to a function, occurances of a function, variable, macros, class or object and their respective declarations. Cscope offers more complete navigation than ctags as it has more complete cross referencing.

    Vim must be compiled with Cscope support. Red Hat Enterprise Linux 5 (or CentOS 5), includes vim 7.0 with cscope support. Earlier versions of Red Hat or Fedora RPM does not support Cscope and thus must be compiled.

    Compiling Vim from source:

    • Download vim source from http://www.vim.org/
    • tar xzf vim-7.0.tar.gz
    • cd vim70
    • ./configure --prefix=/opt --enable-cscope
    • make
    • make install

    Using Cscope with vim:

    The Cscope database (cscope.out) is generated the first time it is invoked. Subsequent use will update the database based on file changes.
    The database can be generated manually using the command i.e.: cscope -b *.cpp *.h or cscope -b -R .

    Invoke Cscope from within vim from the vim command line. Type the following: :cscope find search-type search-string The short form of the command is ":cs f" where the "search-type" is:

    Search TypeType short formDescription
    symbolsFind all references to a symbol
    globalgFind global definition
    callscFind calls of this function
    calleddFind functions that the specified function calls
    texttFind specified text string
    filefOpen file
    includeiFind files that "#include" the specified file

    Results of the Cscope query will be displayed at the bottom of the vim screen.

    • To jump to a result type the results number (+ enter)
    • Use tags commands to return after a jump to a result: ctrl-t
      To return to same spot as departure, use ctrl-o
    • To use "tags" navigation to search for words under the cursor (ctrl-\) instead of using the vim command line ":cscope" (and "ctrl-spaceBar" instead of ":scscope"), use the vim plugin, cscope_maps.vim [cache]
      When using this plugin, overlapping ctags navigation will not be available. This should not be a problem since cscope plugin navigation is the same but with superior indexing and cross referenceing.
      Place this plugin in your directory "$HOME/.vim/plugin"
      Plugin required for vim 5 and 6. This feature is compiled in with vim 7.0 on Red Hat Enterprise Linux 5 and CentOS 5 and newer Linux OS's. Attempts to use the plugin when not required will result in the following error:
      E568: duplicate cscope database not added
    • Cycle through results:
      • Next result: :tnext
      • Previous result: :tprevious
    • Create a split screen for Cscope results: :scscope find search-type search-string
      (Short form: :scs f search-type search-string)
    • Use command line argument ":cscope -R": Scan subdirectories recursively
    • Use Cscope ncurses based GUI without vim: cscope
      • ctrl-d: Exit Cscope GUI

    Cscope command line arguments:

    ArgumentDescription
    -RScan subdirectories recursively
    -bBuild the cross-reference only.
    -CIgnore letter case when searching.
    -fFileNameSpecify Cscope database file name instead of default "cscope.out".
    -Iinclude-directoriesLook in "include-directories" for any #include files whose names do not begin with "/".
    -iFilesScan specified files listed in "Files". File names are separated by linefeed. Cscope uses the default file name "cscope.files".
    -kKernel mode ignores /usr/include.
    Typical: cscope -b -q -k
    -qcreate inverted index database for quick search for large projects.
    -sDirectoryNameUse specified directory for source code. Ignored if specified by "-i".
    -uUnconditionally build a new cross-reference file..
    -vVerbose mode.
    file1 file2 ...List files to cross reference on the command line.

    Cscope environment variable:

    Environment VariableDescription
    CSCOPE_EDITOREditor to use: /usr/bin/vim
    EDITORDefault: /usr/bin/vim
    INCLUDEDIRSColon-separated list of directories to search for #include files.
    SOURCEDIRSColon-separated list of directories to search for additional source files.
    VPATHColon-separated list of directories to search. If not set, cscope searches only in the current directory.

    Manually Generating file cscope.files

    File: $HOME/bin/gen_cscope or /opt/bin/gen_cscope
    #!/bin/bash
    find ./ -name "*.[ch]pp" -print > cscope.files
    cscope -b -q -k
    
    Generates cscope.files of ".cpp" and ".hpp" source files for a C++ project.

    Note that this generates CScope files in the current working directory. The CScope files are only usefull if you begin the vim session in the same directory. Thus if you have a heirarchy of directories, perform this in the top directory and reference the files to be edited on the command line with the relative path from the same directory in which the CScope files were generated.


    Also see:


    Vim plugins:

    Vim default plugins:

    Vim comes with some default plugins which can be found in:

    • Red Hat / CentOS / Fedora:
      • RHEL4: /usr/share/vim/vim70/autoload/
      • Fedora 3:/usr/share/vim/vim63/plugin/
    • Ubuntu / Debian:
      • Ubuntu 6.06: /usr/share/vim/vim64/plugin/

    Additional custom plugins:

    User added plugins are added to the user's local directory: ~/.vim/plugin/ or ~/.vimrc/plugin/


    Default vim plugins:

    File Explorer / List Files: explorer.vim

    Help is available with the following command: :help file-explorer

    CommandDescription
    :ExploreList files in your current directory
    :Explore directory-nameList files in specified directory
    :VexploreSplit with a new vertical window and then list files in your current directory
    :SexploreSplit with a new horizontal window and then list files in your current directory

    The new window buffer created by ":Vexplore" and ":Sexplore" can be closed with ":bd" (buffer delete).


    Additional custom plugins:

    CScope: cscope_maps.vim

    See cscope and vim description and use in this tutorial above.

    Tabbed pages: minibufexpl.vim

    This plugin allows you to open multiple text files and accessed by their tabs displayed at the top of the frame.
    KeystrokeDescription
    :bnNew buffer
    :bdBuffer delete
    :b3Go to buffer number 3
    ctrl-w followed by "k"New buffer. Puts curson in upper tabbed portion of window. Navigate with arrow keys or "h"/"l".
    :qaQuit vim out of all buffers
    tabThe "tab" key jumps between tabbed buffers.

    Recommended ~/.vimrc file entry:

    "Hide abandon buffers in order to not lose undo history.
    set hid
    
    This vim directive will allow undo history to remain when switching buffers.

    The new window buffer tab created can be closed with ":bd" (buffer delete).

    Links:


    Alternate between the commensurate include and source file: a.vim

    Most usefull when used with the vim plugin "minibufexpl.vim"

    Usefull for C/C++ programmers to switch between the source ".cpp" and commensurate ".hpp" or ".h" file and vice versa.

    CommandDescription
    :Aswitches to the header file corresponding to the current file being edited (or vise versa)
    :ASsplits and switches
    :AVvertical splits and switches
    :ATnew tab and switches
    :ANcycles through matches
    :IHswitches to file under cursor
    :IHSsplits and switches
    :IHVvertical splits and switches
    :IHTnew tab and switches
    :IHNcycles through matches
    If you are editing fileX.c and you enter ":A" in vim, you will be switched to the file fileX.h

    Links:


    Vim tip:

    Using a mousewheel with vim in an xterm. Place in file $HOME/.Xdefaults

    XTerm*VT100.Translations: #override \n\ 
    : string("0x9b") string("[64~") \n\ 
    : string("0x9b") string("[65~")
    

    Links:

    vim booksBooks:
    ultimate guide to vi"The Ultimate Guide to VI and EX Text Editors"
    Hewlet Packard Corporation
    ISBN #0-8053-4460-8, Addison-Wesley Pub Co., Benjamin/Cummings Publishing Company
    Amazon.com
    Learn vi"Learning the vi Editor (6th edition)"
    by Linda Lamb, Arnold Robbins
    ISBN #1565924266, O'Reilly
    Amazon.com
    vi improved"Vi iMproved (VIM)
    by Steve Oualline
    ISBN #0735710015, Sams (1st edition)
    Amazon.com

     

  • Using Linux iptables or ipchains to set up an internet gateway / firewall / router for home or office

    Methods of connecting your network to the internet:

    • Use Linux ipchains / iptables and IP forwarding to configure Linux as a firewall and router. This is the method covered in this tutorial.
    • The Linux router project has produced a specialized version of Linux just to run ipchains / iptables and IP masquerading.
      See LinuxRouter.org.
    • Use SOCKS gateway proxy software running on Linux.
      For more information see the SOCKS5/e-Border home page.
    • Use a CISCO router - Configuration tutorial. (Note: PIX series are preferred for firewall use.)

    This tutorial will cover using a linux computer as a gateway between a private network and the internet. Any internet connection whether it be a dial-up PPP, DSL, cable modem or a T1 line can be used. In the case of most dial-up PPP connections and cable modem connections, only a single IP address is issued allowing only one computer to connect to the internet at a time. Using Linux and iptables / ipchains one can configure a gateway which will allow all computers on a private network to connect to the internet via the gateway and one external IP address, using a technology called "Network Address Translation" (NAT) or masquerading and private subnets. Iptables/ipchains can also be configured so that the Linux computer acts as a firewall, providing protection to the internal network.

     


    Related YoLinux Tutorials:

    °Linux Networking

    °Linux Sys Admin

    °Web site configuration

    °Internet Security

    °YoLinux Tutorials Index


     

    Firewall versions vs Linux versions:

    Note: References to ipfwadm and ipchains refer to older deprecated software.

     

    Firewall CommandLinux Kernel VersionRed Hat Version
    iptables2.4.x, 2.6.x7.1 - 9.0, Fedora 1,2,3
    ipchains2.2.x6.x, 7.0
    ipfwadm2.0.x5.x

    Note: Red Hat 7.1-9.0 and the default Linux 2.4 kernel may use ipchains or iptables but not both. Iptables is the preferred firewall as it supports "state" and can recognize if a network connection has already been "ESTABLISHED" or if the connection is related to the previous connection (required for ftp which makes multiple connections on different ports). Ipchains can not. Ipchain rules take precedence over iptables rules. During system boot, the kernel attempts to activate ipchains, then attempts to activate iptables. If ipchain rules have been activated, the kernel will not start iptables.

    Red Hat 7.1 will not support ipchains unless that option is configured (during install or later). If during install you select "Disable Firewall - no protection" then ipchains will not be available and you must rely upon iptables for a manual firewall configuration. (iptables only. ipchains will be unavailable)

    GUI configuration:

    • iptables: The GUI configuration tool /usr/bin/redhat-config-securitylevel can be used to choose a preconfigured firewall (High, Medium or no firewall) or it can be used to manually configure rules based on the network services your server will offer. The init script /etc/rc.d/init.d/iptables will use rules stored in /etc/sysconfig/iptables.
    • ipchains: The tool that does this is lokkit (or /usr/bin/gnome-lokkit), which uses ipchains to configure firewall options for High and Low security options. To support ipchains after install, run /usr/bin/gnome-lokkit and configure a firewall. It will configure ipchains to activate the firewall. Lokkit will generate the file /etc/sysconfig/ipchains. (Used by init script /etc/rc.d/init.d/ipchains which calls /sbin/ipchains-restore)

      To see if ipchains and the Lokkit configuration is invoked during system boot, use the command:

          chkconfig --list | grep ipchains

    The default Red Hat 7.1+ Linux 2.4 kernel is compiled to support both iptables and ipchains. Kernel support for ipchains is available during a kernel configuration and compilation. During make xconfig or make menuconfig turn on the feature: "IP: Netfilter Configuration" + "ipchains (2.2-style) support".

    Check your installation by using the command: rpm -q iptables ipchains
    These packages must be installed. The commands iptables and ipchains are the command interfaces to configure kernel firewall rules. The default Red Hat 7.1 kernel supports iptables and ipchains. (But not both at the same time.)

    [Potential Pitfall]: When performing an upgrade instead of a new install, the upgrade software will not install iptables as did not exist on the system previously. It will perform an upgrade to a newer version of ipchains. If you wish to use iptables, you must manually install the iptables RPM.
    i.e.: rpm -ivh iptables-XXX.i386.rpm

    [Potential Pitfall]: The Linux operating system kernel may load or not load what you had expected. Use the command lsmod to see if ip_tables or ip_chains were loaded.

    Switching a running system from ipchains to iptables: (Red Hat 7.1-9.0 - Linux kernel 2.4 specific)

    SequenceCommandDescription
    1chkconfig --del ipchainsRemove ipchains from system boot/initialization process
    2chkconfig --add iptablesAdd iptables to system boot/initialization process
    3ipchains -FFlush ipchains rules
    4service ipchains stopStop ipchains. Also: /etc/init.d/ipchains stop
    5rmmod ipchainsUnload ipchains kernel module. Iptables kernel module can not be loaded if the ipchains module is loaded
    6service iptables startLoad iptables kernel module. Also: /etc/init.d/iptables stop

     


    Network Address Translation (NAT):

    An individual on a computer on the private network may point their web browser to a site on the internet. This request is recognized to be beyond the local network so it is routed to the Linux gateway using the private network address. The request for the web page is sent to the web site using the external internet IP address of the gateway. The request is returned to the gateway which then translates the IP address to computer on the private network which made the request. This is often called IP masquerading. The software interface which enables one to configure the kernel for masquerading is iptables (Linux kernel 2.4) or ipchains (Linux kernel 2.2)

    The gateway computer will need two IP addresses and network connections, one to the private internal network and another to the external public internet.

    A note on private network IP addresses: A set of IP addresses has been reserved by IANA for private networks. They range from 192.168.0.1 to 192.168.254.254 for a typical small business or home network and are often referred to as CIDR private network addresses. Most private networks conform to this scheme.

     

    BlockRange CIDR NotationDefault Subnet MaskNumber of hosts
    24 bit block in class A10.0.0.010.255.255.25510.0.0.0/8255.0.0.016,777,216
    20 bit block in class B172.16.0.0172.31.255.255172.16.0.0/12255.240.0.01,048,576
    16 bit block in class C192.168.0.0192.168.255.255192.168.0.0/16255.255.0.065,536
    The actual number of hosts will be fewer that listed because addresses on each subnet will be reserved as a broadcast address, etc.

    This is detailed in RFC 1918 - Address Allocation for Private Internets. For a description of class A, B, and C networks see the YoLinux Networking Tutorial class description.

    The private networks may be subdivided into various subnets as desired. Examples:

    Range CIDR NotationDefault Subnet MaskNumber of hosts
    10.2.3.010.2.4.25510.2.3.0/23255.255.254.0512
    172.16.0.0172.17.255.255172.16.0.0/15255.254.0.0132608
    192.168.5.128192.168.5.255192.168.5.128/25255.255.255.128128

    CertGuide.com: Network Subnets

     


    Example 1: Linux connected via PPP

    This example uses a Linux computer connected to the internet using a dial-up line and modem (PPP). The Linux gateway is connected to the internal network using an ethernet card. The internal network consists of Windows PC's.

    The Linux box must be configured for the private internal network and PPP for the dial-up connection. See the PPP tutorial to configure the dial-up connection. Use the ifconfig command to configure the private network. i.e. (as root)

       /sbin/ifconfig eth1 192.168.10.101 netmask 255.255.255.0 broadcast 192.168.10.255

    This is often configured during install or can be configured using the Gnome tool neat (or the admin tool Linuxconf or netcfg for older Red Hat systems). System changes made with the ifconfig or route commands are NOT permanent and are lost upon system reboot. Permanent settings are held in configuration scripts executed during system boot. (i.e. /etc/sysconfig/...) See the YoLinux Networking tutorial for more information on assigning network addresses.

    Run one of the following scripts on the Linux gateway computer:

     

    iptables:

       iptables --flush                         - Flush all the rules in filter and nat tables
       iptables --table nat --flush
       iptables --delete-chain                  - Delete all chains that are not in default filter and nat table
       iptables --table nat --delete-chain
    
       # Set up IP FORWARDing and Masquerading
       iptables --table nat --append POSTROUTING --out-interface ppp0 -j MASQUERADE
       iptables --append FORWARD --in-interface eth0 -j ACCEPT         - Assuming one NIC to local LAN
    
       echo 1 > /proc/sys/net/ipv4/ip_forward    - Enables packet forwarding by kernel
                

     

    ipchains:

       #!/bin/sh
    ipchains -F forward - Flush all previous rules and settings ipchains -P forward DENY - Default set to deny packet forwarding ipchains -A forward -s 192.168.10.0/24 -j MASQ - Use IP address of gateway for private network ipchains -A forward -i ppp0 -j MASQ - Sets up external internet connection echo 1 > /proc/sys/net/ipv4/ip_forward - Enables packet forwarding by kernel

    A PPP connection as described by the YoLinux PPP tutorial will create the PPP network connection as the default route.

     


    Example 2: Linux connected via DSL, Cable, T1

    High speed connections to the internet result in an ethernet connection to the gateway. Thus the gateway is required to possess two ethernet Network Interface Cards (NICs), one for the connection to the private internal network and another to the public internet. The ethernet cards are named eth and are numbered uniquely from 0 upward.

    Use the ifconfig command to configure both network interfaces.

    /sbin/ifconfig eth0 XXX.XXX.XXX.XXX netmask 255.255.255.0 broadcast XXX.XXX.XXX.255   - Internet
    /sbin/ifconfig eth1 192.168.10.101 netmask 255.255.255.0 broadcast 192.168.10.255     - Private LAN
                
    Also see notes on adding a second NIC.

    This is often configured during install or can be configured using the Gnome tool neat (or the admin tool Linuxconf or netcfg for older Red Hat systems). System changes made with the ifconfig or route commands are NOT permanent and are lost upon system reboot. Permanent settings are held in configuration scripts executed during system boot. (i.e. /etc/sysconfig/...) See the YoLinux Networking tutorial for more information on assigning network addresses.

    Run the appropriate script on the linux computer where eth0 is connected to the internet and eth1 is connected to a private LAN:

     

    iptables:

       # Delete and flush. Default table is "filter". Others like "nat" must be explicitly stated.
    iptables --flush - Flush all the rules in filter and nat tables iptables --table nat --flush iptables --delete-chain - Delete all chains that are not in default filter and nat table iptables --table nat --delete-chain # Set up IP FORWARDing and Masquerading iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE iptables --append FORWARD --in-interface eth1 -j ACCEPT echo 1 > /proc/sys/net/ipv4/ip_forward - Enables packet forwarding by kernel

     

    ipchains:

       #!/bin/sh
    ipchains -F forward - Flush rules ipchains -P forward DENY - Default set to deny packet forwarding ipchains -A forward -s 192.168.10.0/24 -j MASQ - Use IP address of gateway for private network ipchains -A forward -i eth1 -j MASQ - Sets up external internet connection echo 1 > /proc/sys/net/ipv4/ip_forward

    Create a route for internal packets:

         route add  -net 192.168.10.0  netmask 255.255.255.0 gw XXX.XXX.XXX.XXX dev eth1
    Where XXX.XXX.XXX.XXX is the internet gateway defined by your ISP. For more information on routing see the YoLinux networking tutorial

    Note: While this configuration requires that the Linux gateway computer have two network cards, if you only have one PCI slot available you may use a card such as the Intel Pro 100 or Pro 1000 Dual Port which has two ethernet connections which reside on a single card. (This is what I use) Yolinux Hardware tutorial: More on Network interface cards

     

    icon
    Intel PCI Dual Pro 100 or Pro 1000 NIC card supports two physical ethernet connections (eth0, eth1) on one card.
    Compliant Standards: IEEE 802.3-LAN, IEEE 802.3U-LAN , Plug and Play
    Connectivity Technology: Cable - 10Base-T, 100Base-TX
    Data Link Protocol: Ethernet, Fast Ethernet
    Processor: 82550 - Intel

     

     

    Iptables options: (Linux kernel 2.4/2.6 firewall)

    General /sbin/iptables format to add rules:
    iptables [-t|--table table] -command [chain] [-i interface] [-p protocol] [-s address [port[:port]]] [-d address [port[:port]]] -j policy

    Six pre-defined "chain" rules are available:

    • INPUT
    • OUTPUT
    • INPUT
    • FORWARD
    • PREROUTING
    • POSTROUTING
    • User defined chains (just give it a new name instead of one of the pre-defined names)

     

    iptables options:

     

    --table
    -t
    Description
    filterDefault table. This is used if not specified
    natNetwork address translation
    mangleUsed for Quality Of Service (QOS) and preferential treatment
    rawEnables optimization. i.e. Ignore firewall state matching for port 80 for enhanced speed due to less processing. Requires kernel patch
    Command
    (Use one)
    Description
    -A
    --append
    Append rule to chain
    -D
    --delete
    Delete rule from chain
    -I
    --insert
    Insert rule at beginning or at specified sequence number in chain.
    -R
    --replace
    Replace rule
    -F
    --flush
    Flush all rules
    -Z
    --zero
    Zero byte counters in all chains
    -L
    --list
    List all rules.
    Add option --line-numbers for rule number.
    -N
    --new-chain
    Create new chain
    -X
    --delete-chain
    Delete user defined chain
    -P
    --policy
    Set default policy for a chain
    -E
    --rename-chain
    Rename a chain
    Command OptionDescription
    -s
    --source
    Source address of packet
    -d
    --destination
    Destination address of packet
    -i
    --in-interface
    Interface packet is arriving from
    -o
    --out-interface
    Interface packet is going to
    -p
    --protocol
    Protocol:
    °tcp
    --sport port[:port]
    --dport port[:port]
    --syn
    °udp
    °icmp
    °mac
    ...
    -j
    --jump
    Target to send packet to
    -f
    --fragment
    Fragment matching
    -c
    --set-counters
    Set packet/byte counter
    -m tcp
    --match tcp
    °--source-port port[:port]
    (port # or range #:#)
    °--destination-port port[:port]
    °--tcp-flags
    -m state
    --match state
    --state
    °ESTABLISHED
    °RELATED
    °NEW
    °INVALID
    (Push content, not expected to recieve this packet.)
    Defined PoliciesDescription
    ACCEPTLet packet through
    DROPDeny packet with no reply
    REJECTDeny packet and notify sender
    RETURNHandled by default targets
    MARKUsed for error response.
    Use with option --reject-with type
    MASQUERADEUsed with nat table and DHCP.
    LOGLog to file and specify message:
    °--log-level #
    °--log-prefix "prefix"
    °--log-tcp-sequence
    °--log-tcp-options
    °--log-ip-options
    ULOGLog to file and specify userpace logging messages
    SNATValid in PREROUTING chain. Used by nat.
    REDIRECTUsed with nat table. Output.
    DNATValid in POSTROUTING chain. Output.
    QUEUEPass packet to userspace.

    For the full info see the man page for iptables.

     


    Ipchains options: (Linux kernel 2.2 firewall)

    General /sbin/ipchains format to add rules:
    ipchains -A|I [chain] [-i interface] [-p protocol] [-y] [-s address [port[:port]]] [-d address [port[:port]]] -j policy [-l]

    ipchains options:

     

    CommandDescription
    -AAdd rule to chain
    -DDelete rule from chain
    -IInsert rule
    -RReplace rule
    -FFlush all rules
    -LList all rules
    -NCreate new chain
    -XDelete user defined chain
    -PSet default targe
    Command OptionDescription
    -sSource address of packet
    -dDestination address of packet
    -iInterface packet is arriving from
    -pProtocol
    -jTarget to send packet to
    -yFor -p tcp. Packet is SYN packet.
    --icmp-typeFor -p icmp.
    -lLog the packet to syslog.
    /var/log/messages
    Available in default Red Hat 6.0+ kernel
    System targets
    (policy)
    Description
    ACCEPTLet packet through
    DENYDeny packet
    REJECTDeny packet and notify sender
    MASQForward chain masquerade
    REDIRECTSend to different port
    RETURNHandled by default targets

    Four chain rule types are available:

    • IP input chain
    • IP output chain
    • IP forwarding chain
    • User defined chains (just give it a new name instead of the built-in names: input, output or forward)

    For the full info see the man page for ipchains. To add firewall rules read the links provided below.

     


    Configuring PCs on the office network:
    • All PC's on the private office network should set their "gateway" to be the local private network IP address of the Linux gateway computer.
    • The DNS should be set to that of the ISP on the internet.

     

    Windows '95 Configuration:

    • Select "Start" + Settings" + "Control Panel"
    • Select the "Network" icon
    • Select the tab "Configuration" and double click the component "TCP/IP" for the ethernet card. (NOT the TCP/IP -> Dial-Up Adapter)
    • Select the tabs:
      • "Gateway": Use the internal network IP address of the Linux box. (192.168.XXX.XXX)
      • "DNS Configuration": Use the IP addresses of the ISP Domain Name Servers. (Actual internet IP address)
      • "IP Address": The IP address (192.168.XXX.XXX - static) and netmask (typically 255.255.255.0 for a small local office network) of the PC can also be set here.

     

    Linux computers:

    • IP Address: Use ifconfig or netcfg commands to set the IP address and netmask.
      See Assigning an IP address portion of the Networking tutorial.
    • Gateway: The gateway is set with the route command. This can also be set by the GUI tool /usr/bin/netcfg or console tool /usr/sbin/netconfig. It is also stored by the system in the /etc/sysconfig/network file.
    • DNS: Configure file /etc/resolv.conf to set the DNS and default domain.
      See the Network configuration files portion of the Networking tutorial.
    • Simple firewall for the desktop Linux system:
      iptables -P INPUT   DROP
      iptables -P FORWARD DROP
      iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
      iptables -A INPUT -i lo -j ACCEPT
      iptables -A OUTPUT -o lo -j ACCEPT
      Allow network connections which have already been established (started by host) and related to your connection. FTP requires this as it may use various ports in support of the file transfer.)
      Allow network input/output from self (lo).

     


    Adding more security rules to your gateway:

     

    iptables:

    Deny a specific host: iptables -I INPUT -s XXX.XXX.XXX.XXX -j DROP

    Block ports by adding the following firewall rules:

    # Allow loopback access. This rule must come before the rules denying port access!!
    iptables -A INPUT -i lo -p all -j ACCEPT - Rule for your computer to be able to access itself via the loopback iptables -A OUTPUT -o lo -p all -j ACCEPT iptables -A INPUT -p tcp -s 0/0 -d 0/0 --dport 2049 -j DROP - Block NFS iptables -A INPUT -p udp -s 0/0 -d 0/0 --dport 2049 -j DROP - Block NFS iptables -A INPUT -p tcp -s 0/0 -d 0/0 --dport 6000:6009 -j DROP - Block X-Windows iptables -A INPUT -p tcp -s 0/0 -d 0/0 --dport 7100 -j DROP - Block X-Windows font server iptables -A INPUT -p tcp -s 0/0 -d 0/0 --dport 515 -j DROP - Block printer port iptables -A INPUT -p udp -s 0/0 -d 0/0 --dport 515 -j DROP - Block printer port iptables -A INPUT -p tcp -s 0/0 -d 0/0 --dport 111 -j DROP - Block Sun rpc/NFS iptables -A INPUT -p udp -s 0/0 -d 0/0 --dport 111 -j DROP - Block Sun rpc/NFS iptables -A INPUT -p all -s localhost -i eth0 -j DROP - Deny packets which claim to be from your loopback interface.
    These rules may be executed on their own to protect your system while attached to the internet or they may be appended to the end of the iptables gateway NAT scripts above.

    Debugging and logging:

    iptables -A INPUT -j LOG --log-prefix "INPUT_DROP: "
    iptables -A OUTPUT -j LOG --log-prefix "OUTPUT_DROP: "
    Add this to the end of your rules and you should be able to monitor dropped connections in /var/log/messages. I do NOT log in this method due to the outrageous volume of messages it generates. Use this for debugging or short term monitoring of the network.

     


    Another approach to firewalls is to drop everything and then grant access to each port you may need.

    iptables -F
    iptables -A INPUT -i lo -p all -j ACCEPT - Allow self access by loopback interface iptables -A OUTPUT -o lo -p all -j ACCEPT iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT - Accept established connections iptables -A INPUT -p tcp --tcp-option ! 2 -j REJECT --reject-with tcp-reset iptables -A INPUT -p tcp -i eth0 --dport 21 -j ACCEPT - Open ftp port iptables -A INPUT -p udp -i eth0 --dport 21 -j ACCEPT iptables -A INPUT -p tcp -i eth0 --dport 22 -j ACCEPT - Open secure shell port iptables -A INPUT -p udp -i eth0 --dport 22 -j ACCEPT iptables -A INPUT -p tcp -i eth0 --dport 80 -j ACCEPT - Open HTTP port iptables -A INPUT -p udp -i eth0 --dport 80 -j ACCEPT iptables -A INPUT -p tcp --syn -s 192.168.10.0/24 --destination-port 139 -j ACCEPT - Accept local Samba connection iptables -A INPUT -p tcp --syn -s trancas --destination-port 139 -j ACCEPT iptables -P INPUT DROP - Drop all other connection attempts. Only connections defined above are allowed.

     

    ipchains:

    This script configures firewall rules for a Linux computer with two ethernet ports. One port connects the computer to the internet with an external address of XXX.XXX.XXX.XXX. The other ethernet port connects the computer to an internal network of 192.168.10.0 to 192.168.10.255. This script is more complex but preferred to the previous scripts because of the extra security that the extra firewall rules offer. The script does work with a system running portsentry. For more on portsentry see the YoLinux Internet Security: portsentry Tutorial.

    Internet external network interface: eth0
    Internal private network interface: eth1
    Local loopback virtual interface: lo

    Gateway script for ipchains firewall and NAT:

       #!/bin/sh
    
       # Flush Rules
       ipchains -F forward 
       ipchains -F output 
       ipchains -F input 
    
       # Set default to deny all
       ipchains -P input   DENY
       ipchains -P output  DENY 
       ipchains -P forward DENY 
    
       # Add Rules
    
       # Accept packets from itself (localhost) (s)ource to itself (d)estination
       # Keeps system logging, X-Windows or any socket based service working.
       ipchains -A input  -j ACCEPT -p all -s localhost -d localhost -i lo
       ipchains -A output -j ACCEPT -p all -s localhost -d localhost -i lo
    
       # Deny and log (option -l) spoofed packets from external network (eth0) which mimic internal IP addresses
       ipchains -A input -j REJECT -p all -s 192.168.10.0/24 -i eth0 -l
    
       # Accept requests/responses from/to your own firewall machine
       ipchains -A input   -j ACCEPT -p all -d XXX.XXX.XXX.XXX -i eth0
    ipchains -A output -j ACCEPT -p all -s XXX.XXX.XXX.XXX -i eth0

    # Allow outgoing packets source (s) to destination (d)
    ipchains -A input -j ACCEPT -p all -s 192.168.10.0/24 -i eth1
    ipchains -A output -j ACCEPT -p all -s 192.168.10.0/24 -i eth1

    # Deny and log (option -l) outside packets from internet which claim to be from your loopback interface
    ipchains -A input -j REJECT -p all -s localhost -i eth0 -l

    ipchains -A forward -s 192.168.10.0/24 -j MASQ
    ipchains -A forward -i eth1 -j MASQ

    # Enable packet forwarding echo 1 > /proc/sys/net/ipv4/ip_forward

    Notes:

    • For this example it was assumed that your private network is from 192.168.10.0 to 192.168.10.255
    • The -d 0.0.0.0/0 refers to all or any destination address of packet. (destination in this case is irrelevant and the -d statement may be omitted))
    • localhost refers to your loopback interface on 127.0.0.1

     


    Red Hat 7.1 will configure firewall rules as an option during installation. Note that the firewall rules are generated for ipchains. The configuration tool /usr/bin/gnome-lokkit was used to perform this setup.

    Example of the security configuration: /etc/sysconfig/ipchains
    This is the configuration file for the script /etc/rc.d/init.d/ipchains (which calls /sbin/ipchains-restore) which may be invoked during system boot.

    # Firewall configuration written by lokkit
    # Manual customization of this file is not recommended.
    # Note: ifup-post will punch the current nameservers through the
    # firewall; such entries will *not* be listed here.
    :input ACCEPT
    :forward ACCEPT
    :output ACCEPT
    -A input -s 0/0 -d 0/0 80 -p tcp -y -j ACCEPT - Allow WWW http access to web server -A input -s 0/0 -d 0/0 22 -p tcp -y -j ACCEPT - Allow SSH (Secure Shell) access -A input -s 0/0 67:68 -d 0/0 67:68 -p udp -i eth0 -j ACCEPT - Allow DHCP/BOOTPC -A input -s 0/0 67:68 -d 0/0 67:68 -p udp -i eth1 -j ACCEPT -A input -s 0/0 -d 0/0 -i lo -j ACCEPT -A input -s 0/0 -d 0/0 -i eth1 -j ACCEPT - eth1 internal network access OK. External eth0 goes through firewall rules -A input -p tcp -s 0/0 -d 0/0 0:1023 -y -j REJECT - This shuts off telnet,FTP,bind...! Use for a workstation only -A input -p tcp -s 0/0 -d 0/0 2049 -y -j REJECT -A input -p udp -s 0/0 -d 0/0 0:1023 -j REJECT - Workstation only or explicitly ports as above with 80, 22 -A input -p udp -s 0/0 -d 0/0 2049 -j REJECT - Block NFS -A input -p tcp -s 0/0 -d 0/0 6000:6009 -y -j REJECT - Block remote X-Window connections -A input -p tcp -s 0/0 -d 0/0 7100 -y -j REJECT - Block remote font server connections
    Note: Once ipchains have been invoked for kernel 2.4 (RH 7.1), one may NOT use iptables. You may use one or the other but not both.

     


    Save/restore an tables/ipchains configuration:

    • IpTables: iptables-save man page
      /sbin/iptables-save > /etc/sysconfig/iptables.rules
      /sbin/iptables-restore < /etc/sysconfig/iptables.rules

       

    • IpChains: ipchains-save man page
      /sbin/ipchains-save > /etc/sysconfig/ipchains.rules
      /sbin/ipchains-restore < /etc/sysconfig/ipchains.rules

    The system init script looks for the file name /etc/sysconfig/ipchains instead of /etc/sysconfig/ipchains.rules. This will make the rules accessible to the init script which will invoke the rules upon system boot. See the YoLinux Init process tutorial for more information on init scripts and system boot procedures.

    Also see: how to turn off ICMP and look invisible to ping.

     


    proc file settings:

     

    • Turning on Linux kernel support for spoof and DOS (Denial Of Service) protection:

       

         echo 1 >/proc/sys/net/ipv4/tcp_syncookies
      Must first be compiled into kernel. (Included in Redhat default kernel) By default the Redhat install has this disabled (set to 0). This helps to prevent against the common 'syn flood attack'. A connecting computer (peer) may not receive reliable error messages from an over loaded server with syncookies enabled.

      For more on SYS cookies see: CERT Advisory CA-96.21

       

    • Turn on Source Address Verification: (Off by default on Red Hat install - set to 0)
         echo 1 >/proc/sys/net/ipv4/conf/eth0/rp_filter
      OR echo 1 >/proc/sys/net/ipv4/conf/all/rp_filter

      State the interface appropriate for your installation.
      The first example prevents spoofing attacks against your external networks only.

      IP spoofing is a technique where a host sends out packets which claim to be from another host. It is also used to hide the identity of the attacker.

    The TCP Man page - Linux Programmer's Manual and /usr/src/linux/proc.txt [link] (Kernel 2.4) cover /proc/sys/net/ipv4/* file descriptions.

    Also see:

     


    IP Forwading Notes:

    Choose one of the following to allow the Linux kernel to forward IP packets:

    1. Immediately allow the forwarding of packets. The configuration is not preserved on reboot but sets a flag in the kernel itself.
          echo 1 > /proc/sys/net/ipv4/ip_forward

       

    2. Another method is to alter the Linux kernel config file: /etc/sysctl.conf
      Set the following value:
          net.ipv4.ip_forward = 1
      This will configure the system to allow forwarding of packets upon system boot. It is stored in this configuration file and thus read and set upon system boot. If set to "0" then there will be no forwarding of packets.

       

    3. An alternate method is to alter the network script: /etc/sysconfig/network
           FORWARD_IPV4=true
      Change the default "false" to "true".

    All the above methods will result in a proc file value of "1" to allow TCP packet forwarding. Options 2 and 3 set boot configurations in a configuration file and will not take effect until system boot.
    Test the current setting of the kernel: cat /proc/sys/net/ipv4/ip_forward

    Note: The /proc directory is NOT on your hard drive but is present in the running kernel.

     


    CIDR Notation:

    The notation "/24" refers to the use of the first 24 bits of a 32 IP address. The is the equivalent of using the bitmask 255.255.255.0. To put it another way, it specifies a range of IP addresses: 0 to 255 for the last octet while the first three remain constant.

    Example: 192.168.103.0/24 refers to the IP address range 192.168.103.0 to 192.168.103.255

    The notation "/32" refers to a single IP address as it implies that all 32 bits of the IP address are significant.

     


    Configuration Tools:

    GUI tools and scripts exist to help you with the configuration of ipchains. See:

    • EasyFw - Tcl/Tk - RPM available from web site.
      RPM installs command: /usr/local/bin/easyfw
    • Firestarter - Configuration of firewall and real-time hit monitor for the Gnome desktop. Configures ipchains (kernel 2.2) and iptables (kernel 2.4)
    • Firewall Builder - iptables, ipfilter and OpenBSD PF. (GTK--)

    Included with Red Hat 7.x is the Gnome GUI tool gnome-lokkit. (ipchains)

    Tools for iptables configuration:

     


    Links and information:

    iptables:

    ipchains:

    Relevant networking links:

    Linux Router Project:

    Documents:

  • Changing the host name:

    This is a three step process:

    1. Issue the command: hostname new-host-name
    2. Change network configuration file: /etc/sysconfig/network
      Edit entry: HOSTNAME=new-host-name
    3. Restart systems which relied on the hostname (or reboot):
      • Restart network services: service network restart
        (or: /etc/init.d/network restart)
      • Restart desktop:
        • Bring down system to console mode: init 3
        • Bring up X-Windows: init 5
    One may also want to check the file /etc/hosts for an entry using the system name which allows the system to be self aware.

    The hostname may be changed at runtime using the command: sysctl -w kernel.hostname="superserver"

    Change the host name using GUI tool: /usr/sbin/system-config-network
    (Red Hat / Fedora / CentOS)

    Hostname entries are made in two places:

    system-config-network system-config-network
    Select the "DNS" tab.Select the "Devices" tab + "Edit" + the "General" tab.

     

    Network IP aliasing:

    Assign more than one IP address to one ethernet card:

        ifconfig eth0   XXX.XXX.XXX.XXX netmask 255.255.255.0 broadcast XXX.XXX.XXX.255
    ifconfig eth0:0 192.168.10.12 netmask 255.255.255.0 broadcast 192.168.10.255
    ifconfig eth0:1 192.168.10.14 netmask 255.255.255.0 broadcast 192.168.10.255

    route add -host XXX.XXX.XXX.XXX dev eth0
    route add -host 192.168.10.12 dev eth0
    route add -host 192.168.10.14 dev eth0

    In this example 0 and 1 are aliases in addition to the regular eth0. The result of the ifconfig command:

    eth0      Link encap:Ethernet  HWaddr 00:10:4C:25:7A:3F  
    inet addr:XXX.XXX.XXX.XXX Bcast:XXX.XXX.XXX.255 Mask:255.255.255.0
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:14218 errors:0 dropped:0 overruns:0 frame:0
    TX packets:1362 errors:0 dropped:0 overruns:0 carrier:0
    collisions:1 txqueuelen:100
    Interrupt:5 Base address:0xe400

    eth0:0 Link encap:Ethernet HWaddr 00:10:4C:25:7A:3F
    inet addr:192.168.10.12 Bcast:192.168.10.255 Mask:255.255.255.0
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    Interrupt:5 Base address:0xe400

    eth0:1 Link encap:Ethernet HWaddr 00:10:4C:25:7A:3F
    inet addr:192.168.10.14 Bcast:192.168.10.255 Mask:255.255.255.0
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    Interrupt:5 Base address:0xe400

    Config file: /etc/sysconfig/network-scripts/ifcfg-eth0:0

    DEVICE=eth0:0
    ONBOOT=yes
    BOOTPROTO=static
    BROADCAST=192.168.10.255
    IPADDR=192.168.10.12
    NETMASK=255.255.255.0
    NETWORK=192.168.10.0
    ONBOOT=yes

    Aliases can also be shut down independently. i.e.: ifdown eth0:0

    The option during kernel compile is: CONFIG_IP_ALIAS=y (Enabled by default in Redhat)

    Note: The Apache web server can be configured so that different IP addresses can be assigned to specific domains being hosted. See Apache configuration and "configuring an IP based virtual host" in the YoLinux Web site configuration tutorial.

    Network Classes:

    The concept of network classes is a little obsolete as subnets are now used to define smaller networks. These subnets may be part of a class A, B, C, etc network. For historical reference the network classes are defined as follows:

    • Class A: Defined by the first 8 bits with a range of 0 - 127.
      First number (8 bits) is defined by Internic i.e. 77.XXX.XXX.XXX
      One class A network can define 16,777,214 hosts.
      Range: 0.0.0.0 - 127.255.255.255
    • Class B: Defined by the first 8 bits with a range from 128 - 191
      First two numbers (16 bits) are defined by Internic i.e. 182.56.XXX.XXX
      One class B network can define 65,534 hosts.
      Range: 128.0.0.0 - 191.255.255.255
    • Class C: Defined by the first 8 bits with a range from 192 - 223
      First three numbers (24 bits) are defined by Internic i.e. 220.56.222.XXX
      One class B network can define 254 hosts.
      Range: 192.0.0.0 - 223.255.255.255
    • Class D: Defined by the first 8 bits with a range from 224 - 239
      This is reserved for multicast networks (RFC988)
      Range: 224.0.0.0 - 239.255.255.255
    • Class E: Defined by the first 8 bits with a range from 240 - 255
      This is reserved for experimental use.
      Range: 240.0.0.0 - 247.255.255.255

    Enable Forwarding:
    Forwarding allows the network packets on one network interface (i.e. eth0) to be forwarded to another network interface (i.e. eth1). This will allow the Linux computer to conect ("ethernet bridge") or route network traffic.

    The bridge configuration will merge two (or several) networks into one single network topology. IpTables firewall rules can be used to filter traffic.

    A router configuration can support multicast and basic IP routing using the "route" command. IP masquerading (NAT) can be used to connect private local area networks (LAN) to the internet or load balance servers.

    • Turn on IP forwarding to allow Linux computer to act as a gateway or router.
      echo 1 > /proc/sys/net/ipv4/ip_forward
      Default is 0. One can add firewall rules by using ipchains.

      Another method is to alter the Linux kernel config file: /etc/sysctl.conf Set the following value:

      net.ipv4.ip_forward = 1

      See file /etc/sysconfig/network for storing this configuration.

      FORWARD_IPV4=true
      Change the default "false" to "true".

    All methods will result in a proc file value of "1". Test: cat /proc/sys/net/ipv4/ip_forward

    The TCP Man page - Linux Programmer's Manual and /usr/src/linux/Documentation/proc.txt (Kernel 2.2 RH 7.0-) cover /proc/sys/net/ipv4/* file descriptions.

    Alos see: (YoLinux tutorials)

    Usefull Linux networking commands:

    • /etc/rc.d/init.d/network   start - command to start, restart or stop the network
    • netstat - Display connections, routing tables, stats etc
      • List externally connected processes: netstat -punta
      • List all connected processes: netstat -nap
      • Show network statistics: netstat -s
      • Kernel interface table info: netstat -a -i eth0
    • ping - send ICMP ECHO_REQUEST packets to network hosts. Use Cntl-C to stop ping.
    • traceroute - print the route packets take to network host
      • traceroute IP-address-of-server
      • traceroute domain-name-of-server
    • mtr - a network diagnostic tool introduced in Fedora - Like traceroute except it gives more network quality and network diagnostic info. Leave running to get real time stats. Reports best and worst round trip times in milliseconds.
      • mtr IP-address-of-server
      • mtr domain-name-of-server
    • whois - Lookup a domain name in the internic whois database.
    • finger - Display information on a system user. i.e. finger user@host Uses $HOME/.plan and $HOME/.project user files. Often used by game developers. See http://finger.planetquake.com/
    • iptables - IP firewall administration (Linux kernel 2.6/2.4) See YoLinux firewall/gateway configuration.
    • ipchains - IP firewall administration (Linux kernel 2.2) See YoLinux firewall/gateway configuration.
    • socklist - Display list of open sockets, type, port, process id and the name of the process. Kill with fuser or kill.
    • host - Give a host name and the command will return IP address. Unlike nslookup, the host command will use both /etc/hosts as well as DNS.
      Example: host domain-name-of-server
    • nslookup - Give a host name and the command will return IP address. Also see Testing your DNS (YoLinux Tutorial) Note that nslookup does not use the /etc/hosts file.

    inetd/xinetd: Network Socket Listener Daemons:

    The network listening daemons listen and respond to all network socket connections made on the TCP/IP ports assigned to it. The ports are defined by the file /etc/services. When a connection is made, the listener will attempt to invoke the assigned program and pipe the data to it. This simplified matters by allowing the assigned program to read from stdin instead of making its own sockets connection. The listener hadles the network socket connection. Two network listening and management daemons have been used in Red Hat Linux distributions:

    • inetd: Red Hat 6.x and older
    • xinetd: Red Hat 7.0-9.0, Fedora Core

     


    inetd:

    Configuration file: /etc/inetd.conf
    Entries in this file consist of a single line made up of the following fields:
            service socket-type protocol wait user server cmdline

     

    • service: The name assigned to the service. Matches the name given in the file /etc/services
    • socket-type:
      • stream: connection protocols (TCP)
      • dgram: datagram protocols (UDP)
      • raw
      • rdm
      • seqpacket
    • protocol: Transport protocol name which matches a name in the file /etc/protocols. i.e. udp, icmp, tcp, rpc/udp, rpc/tcp, ip, ipv6
    • wait: Applies only to datagram protocols (UDP).
      • wait[.max]: One server for the specified port at any time (RPC)
      • nowait[.max]: Continue to listen and launch new services if a new connection is made. (multi-threaded)
      Max refers to the maximum number of server instances spawned in 60 seconds. (default=40)
    • user[.group]: login id of the user the process is executed under. Often nobody, root or a special restricted id for that service.
    • server: Full path name of the server program to be executed.
    • cmdline: Command line to be passed to the server. This includes argument 0 (argv[0]), that is the command name. This field is empty for internal services. Example of internal TCP services: echo, discard, chargen (character generator), daytime (human readable time), and time (machine readable time). (see RFC)

    Sample File: /etc/inetd.conf

    #echo   stream  tcp     nowait  root    internal
    #echo dgram udp wait root internal

    ftp stream tcp nowait root /usr/sbin/tcpd in.ftpd -l -a
    #pop-3 stream tcp nowait root /usr/sbin/tcpd ipop3d
    #swat stream tcp nowait.400 root /usr/sbin/swat swat
    A line may be commented out by using a '#' as the first character in the line. This will turn the service off. The maximum length of a line is 1022 characters.

    The inet daemon must be restarted to pick up the changes made to the file:
    /etc/rc.d/init.d/inetd restart

    For more information see the man pages "inetd" and "inetd.conf".

     

     


    xinetd: Extended Internet Services Daemon:

    Xinetd has access control machanisms, logging capabilities, the ability to make services available based on time, and can place limits on the number of servers that can be started, redirect services to different ports and network interfaces (NIC) or even to a different server, chroot a service etc... and thus a worthy upgrade from inetd.

    Use the command chkconfig --list to view all system services and their state. It will also list all network services controlled by xinetd and their respective state under the title "xinetd based services". (Works for xinetd (RH7.0+) but not inetd)

    The xinetd network daemon uses PAM also called network wrappers which invoke the /etc/hosts.allow and /etc/hosts.deny files.

    Configuration file: /etc/xinetd.conf which in turn uses configuration files found in the directory /etc/xinetd.d/.

    To turn a network service on or off:

    • Edit the file /etc/xinetd.d/service-name
      Set the disable value:
      disable = yes
      or
      disable = no
      Restart the xinetd process using the signal:
      • SIGUSR1 (kill -SIGUSR1 process-id) - Soft reconfiguration does not terminate existing connections. (Important if you are connected remotely)
      • SIGUSR2 - Hard reconfiguration stops and restarts the xinetd process.
      (Note: Using the HUP signal will terminate the process.)
      OR
    • Use the chkconfig command: chkconfig service-name on
      (or off)
      This command will also restart the xinetd process to pick up the new configuration.

    The file contains entries of the form:

          service service-name
          {
             attribute  assignment-operator value value ...
             ...
          {
              
    Where:
    • attribute:
      • disable:
        • yes
        • no
      • type:
        • RPC
        • INTERNAL:
        • UNLISTED: Not found in /etc/rpc or /etc/services
      • id: By default the service id is the same as the service name.
      • socket_type:
        • stream: TCP
        • dgram: UDP
        • raw: Direct IP access
        • seqpacket: service that requires reliable sequential datagram transmission
      • flags: Combination of: REUSE, INTERCEPT, NORETRY, IDONLY, NAMEINARGS, NODELAY, DISABLE, KEEPALIVE, NOLIBWRAP.
        See the xinetd man page for details.
      • protocol: Transport protocol name which matches a name in the file /etc/protocols.
      • wait:
        • no: multi-threaded
        • yes: single-threaded - One server for the specified port at any time (RPC)
      • user: See file : /etc/passwd
      • group: See file : /etc/group
      • server: Program to execute and recieve data stream from socket. (Fully qualified name - full pathe name of program)
      • server_args: Unlike inetd, arg[0] or the name of the service is not passed.
      • only_from: IP address, factorized address, netmask range, hostname or network name from file /etc/networks.
      • no_access: Deny from ... (inverse of only_from)
      • access_times
      • port: See file /etc/services
      Also: log_type, log_on_success, log_on_failure (Log options: += PID,HOST,USERID,EXIT,DURATION,ATTEMPT and RECORD), rpc_version, rpc_number, env, passenv, redirect, bind, interface, banner, banner_success, banner_fail, per_source, cps, max_load, groups, enabled, include, includedir, rlimit_as, rlimit_cpu, rlimit_data, rlimit_rss, rlimit_stack.
      The best source of information is the man page and its many examples.
    • assignment-operator:
      • =
      • +=: add a value to the set of values
      • -=: delete a value from the set of values

    Then restart the daemon: /etc/rc.d/init.d/xinetd restart

    Example from man page: Limit telnet sessions to 8 Mbytes of memory and a total 20 CPU seconds for child processes.

    service telnet
    {
    socket_type = stream
    wait = no
    nice = 10
    user = root
    server = /usr/etc/in.telnetd
    rlimit_as = 8M
    rlimit_cpu = 20
    }

    [Pitfall] Red Hat 7.1 with updates as of 07/06/2001 required that I restart the xinetd services before FTP would work properly even though xinetd had started without failure during the boot sequence. I have no explanation as to why this occurs or how to fix it other than to restart xinetd: /etc/rc.d/init.d/xinetd restart.

    Man Pages:

    For more info see:

    PAM: Network Wrappers:

    Pluggable Authentication Modules for Linux (TCP Wrappers)

    This system allows or denies network access. One can reject or allow specific IP addresses or subnets to access your system.

    File: /etc/hosts.allow

       in.ftpd:208.188.34.105

    This specifically allows the given IP address to ftp to your system. One can also specify an entire domain. i.e. .name-of-domain.com
    Note the beginning ".".

    File: /etc/hosts.deny

       ALL:ALL

    This generally denies any access.

    See the pam man page.

    File: /etc/inetd.conf

    ftp     stream  tcp     nowait  root    /usr/sbin/tcpd  in.ftpd -l -a

    The inet daemon accepts the incoming network stream and assigns it to the PAM TCP wrapper, /usr/sbin/tcpd, which accepts or denies the network connection as defined by /etc/hosts.allow and /etc/hosts.deny and then passes it along to ftp. This is logged to /var/log/secure

     


    Advanced PAM: More specific access can be assigned and controlled by controlling the level of authentication required for access.

    Files reflect the inet service name. Rules and modules are stacked to achieve the level of security desired.

    See the files in /etc/pam.d/... (some systems use /etc/pam.conf)

    The format: service type control module-path module-arguments

    • auth - (type) Password is required for the user
      • nullok - Null or non-existatant password is acceptable
      • shadow - encrypted passwords kept in /etc/shadow
    • account - (type) Verifies password. Can track and force password changes.
    • password - (type) Controls password update
      • retry=3 - Sets the number of login attempts
      • minlen=8 - Set minimum length of password
    • session - (type) Controls monitoring

    Modules:

    • /lib/security/pam_pwdb.so - password database module
    • /lib/security/pam_shells.so -
    • /lib/security/pam_cracklib.so - checks is password is crackable
    • /lib/security/pam_listfile.so

    After re-configuration, restart the inet daemon: killall -HUP inetd

    For more info see:

    Network Monitoring Tools:

     

    • tcpdump - dump traffic on a network. See discussion below.
      Command line optionDescription
      -cExit after receiving count packets.
      -CSpecify size of output dump files.
      -iSpecify interface if multiple exist. Lowest used by default. i.e. eth0
      -w file-nameWrite the raw packets to file rather than parsing and printing them out.
      They can later be printed with the -r option.
      -nImprove speed by not performing DNS lookups. Report IP addresses.
      -tDon't print a timestamp on each dump line.

      Filter expressions:
      primitiveDescription
      host host-nameIf host has multiple IP's, all will be checked.
      net network-numberNetwork number.
      net network-number mask maskNetwork number and netmask specified.
      port port-numberPort number specified.
      tcpSniff TCP packets.
      udpSniff UDP packets.
      icmpSniff icmp packets.

      Examples:

      • tcpdump tcp port 80 and host server-1
      • tcpdump ip host server-1 and not server-2
    • iptraf - Interactive Colorful IP LAN Monitor
    • nmap - Network exploration tool and security scanner
      • List pingable nodes on network: nmap -sP 192.168.0.0/24
        Scans network for IP addresses 192.168.0.0 to 192.168.0.255 using ping.
    • Ethereal - Network protocol analyzer. Examine data from a live network.
      RPM's required:
      • ethereal-0.8.15-2.i386.rpm - Red Hat 7.1 Powertools CD RPM
      • ucd-snmp-4.2-12.i386.rpm - Red Hat 7.1 binary CD 1
      • ucd-snmp-utils-4.2-12.i386.rpm - Red Hat 7.1 binary CD 1
      • Also: gtk+, glib, glibc, XFree86-libs-4.0.3-5 (base install)
      There is an error in the ethereal package because it does not show the snmp libraries as a dependancies, but you can deduce this from the errors that you get if the ucd-snmp libraries are not installed.
    • EtherApe - Graphical network monitor for Unix modeled after etherman. This is a great network discovery program with cool graphics. (Red Hat Powertools CD 7.1)
    • Gkrellm - Network and system monitor. Good for monitoring your workstation. (Red Hat Powertools CD)
    • IPTraf - ncurses-based IP LAN monitor. (Red Hat Powertools CD)
    • Cheops - Network discovery, location, diagnosis and management. Cheops can identify all of the computers that are on your network, their IP address, their DNS name, the operating system they are running. Cheops can run a port scan on any system on your network. (Red Hat Powertools CD)
    • ntop - Shows network usage in a way similar to what top does for processes. Monitors how much data is being sent and received on your network. (Red Hat Powertools CD)
    • MRTG - Multi Router Traffic Grapher - Monitor network traffic load using SNMP and generate an HTML/GIF report. (See sample output)
    • dnsad - IP traffic capture. Export to Cisco Netflow for network analysis reporting.
    • scotty - Obtain status and configuration information about your network. Supports SNMP, ICMP, DNS, HTTP, SUN RPC, NTP, & UDP. (Red Hat Powertools CD)
    • Big Brother - Monitoring ans services availablility.
    • OpenNMS.org - Network Management using SNMP.
    • Nagios - host, service and network monitoring
    • Angel network monitor

    Using tcpdump to monitor the network:

     

    [root]# ifconfig eth0 promisc          - Put nic into promiscuous mode to sniff traffic.
    [root]# tcpdump -n host not XXX.XXX.XXX.XXX | more    - Sniff net but ignore IP which is your remote session.
    [root]# ifconfig eth0 -promisc         - Pull nic out of promiscuous mode.
    
    Network Intrusion and Hacker Detection Systems:

    SNORT: Monitor the network, performing real-time traffic analysis and packet logging on IP networks for the detection of an attack or probe.

     


    ARP: Address Resolution Protocol

    Ethernet hosts use the Address Resolution Protocol (ARP) to convert a 32-bit internet IP addresses into a 48-bit Ethernet MAC address used by network hardware. (See: RFC 826) ARP broadcasts are sent to all hosts on the subnet by the data transmitting host to see who replies. The broadcast is ignored by all except the intended receiver which recognizes the IP address as its own. The MAC addresses are remembered (APR cache) for future network communications. Computers on the subnet typically keep a cache of ARP responses. ARP broadcasts are passed on by hubs and switches but are blocked by routers.

    Reverse ARP (See: RFC 903) is a bootstrap protocol which allows a client to broadcast requesting a server to reply with its IP address.

     

    • arp (8) man page - manipulate the system ARP cache
    • Shows other systems on your network (including IP address conflicts): arp -a
    • Show ARP table Linux style: arp -e
    • arpwatch (8) man page - keep track of ethernet/ip address pairings
    • arpsnmp (8) man page - keep track of ethernet/ip address pairings. Reads information generated by snmpwalk
    • arping (8) man page - send ARP REQUEST to a neighbor host
      Print ARP reply (similar to arp -a): arping 192.168.10.99
    • List ARP table: cat /proc/net/arp
    • ip (8) man page - show / manipulate routing, devices, policy routing and tunnels
      View ARP table: ip neighbor

    ARP is something that simply works. No Linux system configuration is necessary. It's all part of the ethernet and IP protocol. The aforementioned information is just part of the Linux culture of full visibility into what is going on.

     


    Configuring Linux For Network Multicast:

    Regular network exchanges of data are peer to peer unicast transactions. An HTTP request to a web server (TCP/IP), email SNMP (TCP/IP), DNS (UDP), FTP (TCP/IP), ... are all peer to peer unicast transactions. If one wants to transmit a video, audio or data stream to multiple nodes with one transmission stream instead of multiple individual peer to peer connections, one for each node, one may use multicasting to reduce network load. Note that multicast and a network broadcast are different. Multicast messages are only "heard" by the nodes on the network that have "joined the multicast group" which are those that are interested in the information.

    The Linux kernel is Level-2 Multicast-Compliant. It meets all requirements to send, receive and act as a router for multicast datagrams. For a process to receive multicast datagrams it has to request the kernel to join the multicast group and bind the port receiving the datagrams. When a process is no longer interested in the multicast group, a request is made to the kernel to leave the group. It is the kernel/host which joins the multicast group and not the process. Kernel configuration requires "CONFIG_IP_MULTICAST=y". In order for the Linux kernel to support multicast routing, set the following in the kernel config:

    • CONFIG_IP_MULTICAST=y
    • CONFIG_IP_ROUTER=y
    • CONFIG_IP_MROUTE=y
    • CONFIG_NET_IPIP=y

    The default Red Hat / Fedora kernels are compiled to support multicast.

    See the YoLinux tutorial on optimization and rebuilding the Linux kernal.

    Note that on multihomed systems (more than one IP address/network card), only one device can be configured to handle multicast.

    Class D networks with a range of IP addresses from 224.0.0.0 to 239.255.255.255 (See Network Classes above) have typically been reserved for multicast.

    Usefull commands:

    CommandDescription
    cat /proc/net/igmpList multicast group to which the host is subscribed. Use "Internet Group Management Protocol".
    (See /usr/src/linux/net/core/igmp.c)
    cat /proc/net/dev_mcastList multicast interfaces.
    (See /usr/src/linux/net/core/dev_mcast.c)
    ping 224.0.0.1All hosts configured for multicast will respond with their IP addresses
    ping 224.0.0.2All routers configured for multicast will respond
    ping 224.0.0.3All PIM routers configured for multicast will respond
    ping 224.0.0.4All DVMRP routers configured for multicast will respond
    ping 224.0.0.5All OSPF routers configured for multicast will respond

    Multicast transmissions are achieved through proper routing, router configuration (if communicating through subnets) and programatically with the use of the following "C" function library calls:

    Function CallDescription
    setsockopt()Pass information to the Kernel.
    getsockopt()Retrieve information broadcast using multicast.
    For more on multicast programming see: Multicast Howto.

    The multicast application will specify the multicast loopback interface, TTL (network time to live), network interface and the multicast group to add or drop.

    Add route to support multicast:
    • route add 224.0.0.0 netmask 240.0.0.0 dev eth0
    Note that if adding a route to forward packets through a router, that the router MUST be configured to forward multicast packets. Many routers do not support forwarding of multicast packets or have a default configuration which does not. The internet by default does not forward multicast packets.

     


    Living in a MS/Windows World:

     

    • SMB4k: My favorite MS/Windows file share browser.

       

    • In Nautilus use the URL "smb:" to view MS/Windows servers. [tutorial]

       

    • LinNeighborhood: Linux workstation gui tool.

      Make your life simple and use the GUI/File Manager LinNeighborhood. It uses smbmount, samba and smbclient to give you access to MS/Windows servers and printers.

    See the YoLinux tutorial on integrating Linux into a Microsoft network.

     


    Network Definitions:

     

    • IPv4: Most of the Internet servers and personal computers use Internet Protocol version 4 (IPv4). This uses 32 bits to assign a network address as defined by the four octets of an IP address up to 255.255.255.255. Which is the representation of four 8 bit numbers thus totaling 32 bits.
    • IPv6: Internet Protocol version 6 (IPv6) uses a 128 bit address and thus billions and billions of potential addresses. The protocol has also been upgraded to include new quality of service features and security. Currently Linux supports IPv6 but IPv4 is used when connecting your computer to the internet.
    • TCP/IP: (Transmission Control Protocol/Internet Protocol) uses a client - server model for communications. The protocol defines the data packets transmitted (packet header, data section), data integrity verification (error detection bytes), connection and acknowledgement protocol, and re-transmission.
    • TCP/IP time to live (TTL): This is a counting mechanism to determine how long a packet is valid before it reaches its destination. Each time a TCP/IP packet passes through a router it will decrement its TTL count. When the count reaches zero the packet is dropped by the router. This ensures that errant routing and looping aimless packets will not flood the network.
    • MAC Address: (media access control) is the network card address used for communication between other network devices on the subnet. This info is not routable. The ARP table maps TCP/IP address (global internet) to the local hardware on the local network. Use the command /sbin/ifconfig to view both the IP address and the MAC address. The MAC address uniquely identifies each node of a network and is used by the Ethernet protocol.
    • Full Duplex: Allows the simultaneous sending and receiving of packets. Most modern modems support full duplex.
    • Half Duplex: Allows the sending and receiving of packets in one direction at a time only.
    • OSI 7 Layer Model: The ISO (International Standards Organization) has defined the OSI (Open Systems Interconnection) model for current networking protocols.
      OSI LayerDescriptionLinux Networking Use
      7Application Layer.
      The top layer for communications applications like email and the web.
      telnet, web browser, sendmail
      6Presentation Layer.
      Syntax and format of data transfer.
      SMTP, http
      5Session Layer.
      4Transport Layer.
      Connection, acknowledgement and data packet transmission.
      TCP
      UDP
      3Network Layer.IP
      ARP
      2Data Link Layer.
      Error control, timing
      Ethernet
      1Physical Layer.
      Electrical characteristics of signal and NIC
      Ethernet
    • Network Hub: Hardware to connect network devices together. The devices will all be on the same network and/or subnet. All network traffic is shared and can be sniffed by any other node connected to the same hub.
    • Network Switch: Like a hub but creates a private link between any two connected nodes when a network connection is established. This reduces the amount of network collisions and thus improves speed. Broadcast messages are still sent to all nodes.
  • 【原创】在fc9 安装vmware tools 没有 kernel-devel的解决方案

    vmware 6 上面安装 fc 9,然后安装vmware tools 的时候,没有C header files。

    What is the location of the directory of C header files that match your running
    kernel? [/usr/src/linux/include]

    解决方法:

    这个问题,需要安装与系统内核配套的开发包。

    查看内核: uname -r

    内核头文件C header files下载地址:

    http://rpmfind.net/linux/rpm2html/search.php?query=kernel-devel

    注意:
    安装vmware tools 的时候,如果提示没有权限,那么需要用chmod 777 文件名 来添加权限,比如 提示vmware-install.pl没有权限,那么用下面的命令

    chmod 777 vmware-install.pl

    下面是我的fc9的安装演示,我的内核版本是2.6.25-14.fc9.i686,所以wget的时候选择kernel-devel-2.6.25-14.fc9.i686.rpm

    你需要核对你的内核版本,在上面的网址中选择正确的内核。

    重要:

    内核安装完毕后,需要用这个命令确定内核 C header 的安装目录

    ls -d /usr/src/kernels/$(uname -r)*/include
    引用:
    [root@localhost ~]# uname -r
    2.6.25-14.fc9.i686
    [root@localhost ~]# rpm -q kernel-devel
    package kernel-devel is not installed
    [root@localhost ~]# cd /home
    [root@localhost home]# wget ftp://rpmfind.net/linux/fedora/releases/9/Everything/i386/os/Packages/kernel-devel-2.6.25-14.fc9.i686.rpm
    [root@localhost home]# rpm -i kernel-devel-2.6.25-14.fc9.i686.rpm
    [root@localhost home]# rpm -q kernel-devel
    kernel-devel-2.6.25-14.fc9.i686
      

     Fedora 9出来了,对我这个经常追求新软件的人来说,说不得要试一下了。于是花了几个小时的时间下载了一个,并在vmware下装了它。F9出来的时候,很多人一直说它用了多少新技术,有多少了不起的进步。装上去看了一下,觉得主要是界面方面改进了不少。其他还是差不多。
       很快发现了一些东西,vmware tools不能用了,每次都要按control+alt去让鼠标回到windows下来,更糟糕的是共享文件好麻烦。所有一定要装上vmware tools!上google找了一些文档,终于装上了,归结如下,以备后用!
       step 1.打开菜单“VM -> Install VMware Tools”,然后有光盘自动弹出,把里面的源代码拷贝出来。我的文件是vmwareTools-6.0.2-59824.tar.gz ,我把它拷贝到/opt里。(我习惯在这里安装应用程序)
       step 2.下载最新的open-vm-tools,现在可以下载到最新版本是open-vm-tools-2008.06.03-96374.tar.gz
      step 3.解压缩源代码。tar zvxf vmwareTools-6.0.2-59824.tar.gz
    tar xvzf open-vm-tools-96374.tar.gz
       step 4.编译open-vm-tools
    cd open-vm-tools-2008.06.03-96374/
    ./configure && make
    cd modules/linux/
    step 5.拷贝到vmware源代码里
    for i in *; do mv ${i} ${i}-only; tar -cf ${i}.tar ${i}-only; done
    cd ../../..
    mv -f open-vm-tools-2008.06.03-96374/modules/linux/*.tar vmware-tools-distrib/lib/modules/source/
    step 6.安装vmwaretools
    cd vmware-tools-distrib/
    sudo ./vmware-install.pl
    这里我出现一个小问题,提示找不到kernel的header,从网上下载当前内核开发包kernel-devel-2.6.25-14.fc9.i686.rpm,接着rpm -ivh kernel-devel-2.6.25-14.fc9.i686.rpm。重新执行step 6,一路回车后安装成功了。
      装好后还有一个问题,当你向共享文件夹写文件时总提示没有权限,root用户都提示没有权限。看了一下日志,是selinux在做怪,配置SElinux太麻烦了,不如关了它。vi /etc/sysconfig/selinux找到SElinux=enforcing这一行把它改为SElinux=disabled.重启后一切就ok了!!

  • 1.用livecd(强烈推荐)
    2.用安裝cd
    3.使用grub4dos
    4.使用grub軟盤

    1,使用livecd(强烈推荐)
    使用任何你喜歡的linux livecd(比如,ubuntu 6.06的desktop cd)
    在终端下输入:
    sudo su  //切换到root
    grub  //进入grub,可能要等一会

    grub>
    接着输入:
    root (hdx,y) //x和y的解释如下,并且root后要有空格
    setup (hdx) //setup后要有空格

    hd表示硬盘,格式是(hd硬盘号,分区号) 从零开始计算。所以(按照日常的习惯,从1开始数)
    (hd0,0)表示第一个硬盘的第一个分区,
    (hd0,1)表示第一个硬盘的第2个分区,
    (hd1,4)表示第2个硬盘的第5个分区。
    (注意,linux系统里是用hda1表示第一个硬盘的第一个分区,不要把它和grub中的表示混起来。) root (hdx,y)这里的(hdx,y) 是/boot 目录所在的分区(通常情况下,也就是你装ubuntu系统的分区,除非你安装的时候把/boot分出去了。)
    如果你不知道你把ubuntu装在第几个分区,可以在输入root (hd0, 时按Tab键来补全。(假设你把ubuntu装在第一块硬盘上)按了tab后,你将看到一些有关各个分区的信息。通常你可以通过分区的大小和格式看出你把ubuntu系统装在哪里了。
    setup (hdx) 通常情况下,是setup (hd0)。(多半你把ubuntu装在第一块硬盘上。) 要注意的是,不要输入setup (hd0,0)。我曾经犯过这个错误。(如果你没把命令抄下来,凭记忆操作的话,可能会犯这种错误。)
    最後,输入quit退出grub,重啟系統。好了,总结一下用到的命令(建议你把下面的代码抄在纸上。如果你对(hdx,y)表示的含义还感觉模糊,最好把上面几段解释也抄下来。)
    代码:

    sudo su
    grub
    root (hdx,y)
    setup(hdx)
    quit

    很简单吧?关键只要理解grub中硬盘分区的表示法就行了。

    2,使用ubuntu安裝cd恢复
    ubuntu desktop-cd可能用不起来。你可能需要7.10的alternative cd。

    1. 用 Ubuntu 安装 CD 开机
    2. 在 "boot:" 提示号出现时, 键入 "rescue" 当作开机参数
    boot: rescue
    3. 顺着屏幕上的指示跟着作
    4,例如 假设 /boot 磁碟分区位在 /dev/hda
    代码:

    #grub-install /dev/hda

    下面是另外一种方法。firehare 写道:
    1. 启动系统到 Ubuntu 安装CD
    2. 沿着屏幕上的命令直到 (千万不要超过这一步)
    [!!] Fdisk disks
    3. 按 'Ctrl + Alt + F2'
    4. 按 'Enter' 进入终端
    5.
    ~ # mkdir /ubuntu
    ~ # fdisk -l /dev/discs/disc0/disc
    ~ # mount <你的Ubuntu根设备所在位置> /ubuntu/
    ~ # chroot /ubuntu/sh-2.05b#

    6. 假设 /dev/hda1 是 /boot 分区的地址
    7. sh-2.05b# grub
    grub> root (hd0,0)
    grub> setup (hd0)
    grub> quit

    1. 用 Ubuntu 安装 CD 开机
    2. 在 "boot:" 提示号出现时, 键入 "rescue" 当作开机参数
    boot: rescue
    3. 顺着屏幕上的指示跟着作
    4,例如 假设 /boot 磁碟分区位在 /dev/hda
    代码:
    #grub-install /dev/hda

    3,使用 grub for dos
    在沒有ubuntu安裝盤或livecd的情況下,你可以使用grub4dos重新安裝grub。
    你甚至可以用grub4dos代替grub來引導系統。

    3.1使用grub4dos重新安裝grub
    下載http://www.ubuntu.org.cn/download/installformharddisk/grldr
    oneleaf 写道:将 grldr 复制到 C:\,编辑C:\BOOT.INI,加入一行:
    C:\GRLDR="GRUB"
    再手工输入启动命令
    例如:root (hd0,0)
    kernel /vmlinuz-2.6.10-5-686 root=/dev/hdb5 ro quiet splash
    initrd /initrd.img-2.6.10-5-686
    savedefault
    boot
    进入后,重新安装grub就好了。
    重新安裝grub:
    例如 假设 /boot 磁碟分区位在 /dev/hda
    代码:

    # grub-install /dev/hda

    3.2用grub4dos代替grub來引導系統
    yonsan 写道:
    (凭记忆写的,如有不完善请指正)
    如果你的系统现在正在使用grub引导方式,请在操作之前查看一下/boot/grub/menu.lst的内容,
    建议将/boot/grub/menu.lst拷贝一份以备用(将它拷到fat32分区中存放就可以)!进入window环境下
    1) 下载grub020p.zip并解压到C盘根目录下,打开C盘查看一下是否有以下文件

    C:\boot (文件夹)
    C:\ChangeLog.txt
    C:\compile
    C:\COPYING
    C:\grldr
    C:\grub4lin
    C:\grub-0.95-patch1-startups
    C:\grub-0.95-patch2-findroot
    C:\grub-0.95-patch3-ntfs
    C:\grub-0.95-patch4-emulation
    C:\grub-0.95-patch5-splash
    C:\grub-0.95-patch6-scdrom
    C:\grub-0.95-patch7-bioscdrom
    C:\grub.exe
    C:\grub.pif
    C:\README.txt
    C:\robin.xpm.gz
    C:\scratchpad.txt

    2) 修改C:\boot\grub\menu.lst ,用你刚才从linux系统中拷贝的menu.lst覆盖C:\boot\grub\menu.lst

    3) 进入grub命令行方式 (出现grub引导菜单时按c键)
    > root (hd0,0)
    > setup (hd0)

    4) 重启计算机

    4.使用grub軟盤很簡單,只要用grub軟盤啟動机器就行了。
    如何制作grub軟盤?
    如果你沒做過grub軟盤,想在用安裝cd恢复的時候順便做一個,那就試試下面這個:
    youngong 写道:
    用安装CD启动电脑,输入rescue回车
    启动后执行"grub- install /dev/hda3"重新安装grub到ubuntu分区上
    再用"grub-install /dev/fd0"制作一张启动软盘
    (如果你打算将grub安装在MBR上可就更简单了,只需要grub-install /dev/hda)。
    再用刚才制作的软盘重启电脑,就可以进入ubuntu linux了。
    为了还原我原来的NT Loader启动linux的方式,再提取hda3分区的引导记录
    即“dd if=/dev/hda3 of=/linux.lnx bs=512 count=1",
    并将生成的linux.lnx文件复制到C区根目录下,
    修改boot.ini加入“c:\linux.lnx=Ubuntu linux 5.04",
    就可以在硬盘引导时选择启动ubuntu了。
    其实整个过程中制作引导软盘只起了个过渡作用,但同时也方便以后维护系统。
    zhan 写道:
    今天重装了windows系统,将原来的xp装为2003
    装完后用ubuntu的安装盘grub-install /dev/hda 将linux恢复了
    但是启动时只有一个winxp的选项,进入时说不能识别文件系统,不能启动
    然后出现一个GRUB 就停住了,不过linux系统是还可以用.
    各位大侠有没有什么好办法,我不想再重装了!!
    启动win时的显示见下:
    Booting 'microsoft windows xp professional'
    root (hd0,0)
    Filesystem type unkown ,partition type 0x7
    savedefault
    makeactive
    chainloader+1
    GRUB
    到这里就不动了,按键基本都没用,不过,ctrl+alt+delete能重启
    yonsan 写道:
    用以下方式引导windows
    代码:

    # Windows
    title Windows
    rootnoverify (hd0,0)
    chainloader +1

    -------------------------------------------------------------------------------------------------------

    重装Windows后 无法进入ubuntu 的修复方法
    如果你的电脑是Win和Ubuntu双系统的,可能会遇到这样的问题。
    就是重装Win之后将无法进入Ubuntu了。一般情况下遇到这样的问题,我们有两种方法解决!

    最简单的方法:
    1.利用另外的一个LiveCD盘进入后把所有的盘都挂载。
    2.拷贝原Ubuntu下的/boot/grub到Win的C盘。
    3.修改Win的C盘里的boot.ini文件。它可能隐藏和只读 需要自己改下属性!
    4.在这个文件最后加入一句C:\grldr=ubuntu
    5.重启选择Ubuntu。

    第二种方法:
    注意此种方法只能在重装WIN之前到Ubuntu下操作!!!
    首先确定你的grub正常,并能启动linux
    然后启动到Ubuntu如果你的是IDE硬盘
    请运行:
    sudo dd if=/dev/hda of=/media/linux.lnx bs=512 count=1

    如果你硬盘的被识别为sda ,请运行
    sudo dd if=/dev/sda of=/media/linux.lnx bs=512 count=1

    然后你可以到/media找到linux.lnx这个文件
    将它拷贝到你的win根目录,一般是C:\然后重启Win,修改根目录下的boot.ini 文件。
    在这个文件最后增加:
    C:\linux.lnx=”linux
    OK,重启,选择Ubuntu吧。
    注意:你需要将这个文件备份,可以备份到网络硬盘或者U盘内。
    这样你重装Win之后,只需要将这个文件拷贝到Win的根目录,修改boot.ini 就可以了!

    总结:相比较而言,第一种方法更简单一点,但是我觉得第二种方法更一劳永逸。
    当然,你可以选择利用重装grub来恢复对Ubuntu的引导。但是我不觉得那对于新手会简单!
    感谢提供这两种方法的sun391和enjoyforfun
    ------------------以上内容转自某个网页------------------------------------
    补充: 用GhostXP的安装盘安装Windows 可能不存在这个问题(至少本人用深度白金珍藏版5.7.1是这样的)

    -------------------------------------------------------------------------------------------------------

    当我们的脆弱的Windows定期瘫痪,无法修复只能重新安装的尴尬时刻,我们发现“霸道”的Windows 在安装时丝毫没有顾及在硬盘的MBR上还存在操作系统的引导程序(grub),直接删除,只写入Windows的引导信息。

    不管微软这样是不是有意而为,这都看出Windows的陋习和微软的强盗行径。我们怎么办,放弃Windows?但是我们还要我们心爱的游戏,反正Windows已经是我硬盘上的一个因为游戏还存在的附属系统,我们忍了。

    发扬Linux人的DIY精神,我们自己动手找回丢失的Linux引导程序。

    1,使用Ubuntu live关盘引导进入 Ubuntu live 模式

    2,在Ubuntu中运行终端,执行下列命令:

    $sudo grub

    其实,grub不仅只在我们引导时候出现在我们眼前,我们平时也可以直接运行grub命令进入模拟grub引导程序。

    3,之后,我们在grub 命令行模式下接着执行

    root (hdx,y)

    注意:其中x为硬盘号,数字 “ 0 ”指我们机器上的第一块硬盘,grub的排列顺序是从 “ 0 ”开始的。同理,如果你的系统在第二个硬盘上则是1,依次类推。另外,其中的“ y ”表示前面所指硬盘的 /boot 所在分区号,如果实在不知道,后面信息怎么填,你可以在输入逗号后按Tab键,这样可列出硬盘的分区信息。

    4,安装 grub ,执行命令:

    setup (hdx)

    setup (hdx)就是把GRUB写到"x"硬盘的MBR上。如果成功会有一个successful......

    5,安成安装后,退出 grub 。

    quit

    6,重启机器,重新引导Linux。

    $sudo reboot

    备注:其实,当我们安装完毕grub之后,还需要检查 grub 的配置文件信息是否正确,方法是在 Ubuntu live 模式下利用 mount 命令加载原来ubuntu 的分区,在原 /boot 目录下的 grub/menu1.st 文件中的信息。

  • 普通 APT 用法

    apt-get install <package>
    下载 <package> 以及所有倚赖的包裹,同时进行包裹的安装或升级。如果某个包裹被设置了 hold (停止标志,就会被搁在一边(即不会被升级)。更多 hold 细节请看下面。

    apt-get remove [--purge] <package>

    移除 <package> 以及任何倚赖这个包裹的其它包裹。
    --purge 指明这个包裹应该被完全清除 (purged) ,更多信息请看 dpkg -P。

    apt-get update

    升级来自 Debian 镜像的包裹列表,如果你想安装当天的任何软件,至少每天运行一次,而且每次修改了
    /etc/apt/sources.list 后,必须执行。

    apt-get upgrade [-u]

    升级所以已经安装的包裹为最新可用版本。不会安装新的或移除老的包裹。如果一个包改变了倚赖关系而需要安装一个新的包裹,那么它将不会被升级,而是标志为 holdapt-get update 不会升级被标志为 hold 的 包裹 (这个也就是 hold 的意思)。请看下文如何手动设置包裹为 hold。我建议同时使用 '-u' 选项,因为这样你就能看到哪些包裹将会被升级。

    apt-get dist-upgrade [-u]

    apt-get upgrade 类似,除了 dist-upgrade 会 安装和移除包裹来满足倚赖关系。因此具有一定的危险性。

    apt-cache search <pattern>
    搜索满足 <pattern> 的包裹和描述。

    apt-cache show <package>

    显示 <package> 的完整的描述。

    apt-cache showpkg <package>
    显示 <package> 许多细节,以及和其它包裹的关系。

    dselect
    console-apt
    aptitude
    gnome-apt

    APT 的几个图形前端(其中一些在使用前得先安装)。这里 dselect 无疑是最强大的,也是最古老,最难驾驭。

    普通 Dpkg 用法

    dpkg -i <package.deb>
    安装一个 Debian 包裹文件,如你手动下载的文件。

    dpkg -c <package.deb>

    列出 <package.deb> 的内容。

    dpkg -I <package.deb>

    从 <package.deb> 中提取包裹信息。

    dpkg -r <package>

    移除一个已安装的包裹。

    dpkg -P <package>

    完全清除一个已安装的包裹。和 remove 不同的是,remove 只是删掉数据和可执行文件,purge 另外还删除所有的配制文件。

    dpkg -L <package>

    列出 <package> 安装的所有文件清单。同时请看 dpkg -c 来检查一个 .deb 文件的内容。

    dpkg -s <package>

    显示已安装包裹的信息。同时请看 apt-cache 显示 Debian 存档中的包裹信息,以及 dpkg -I 来显示从一个 .deb 文件中提取的包裹信息。

    dpkg-reconfigure <package>

    重新配制一个已经安装的包裹,如果它使用的是 debconf (debconf 为包裹安装提供了一个统一的配制界面)。你能够重新配制 debconf 它本身,如你想改变它的前端或提问的优先权。例如,重新配制 debconf,使用一个 dialog 前端,简单运行:

    dpkg-reconfigure --frontend=dialog debconf (如果你安装时选错了,这里可以改回来哟:)

    echo "<package> hold" | dpkg --set-selections
    设置 <package> 的状态为 hlod (命令行方式)

    dpkg --get-selections "<package>"

    取的 <package> 的当前状态 (命令行方式)

    支持通配符,如:
    Debian:~# dpkg --get-selections *wine*
    libwine                                         hold
    libwine-alsa                                    hold
    libwine-arts                                    hold
    libwine-dev                                     hold
    libwine-nas                                     hold
    libwine-print                                   hold
    libwine-twain                                   hold
    wine                                            hold
    wine+                                           hold
    wine-doc                                        hold
    wine-utils                                      hold

    例如:
    大家现在用的都是 gaim-0.58 + QQ-plugin,为了防止 gaim 被升级,我们可以采用如下方法:

    方法一:
    Debian:~# echo "gaim hold" | dpkg --set-selections
    然后用下面命令检查一下:
    Debian:~# dpkg --get-selections "gaim"
    gaim                                            hold
    现在的状态标志是 hold,就不能被升级了。

    如果想恢复怎么办呢?
    Debian:~# echo "gaim install" | dpkg --set-selections
    Debian:~# dpkg --get-selections "gaim"
    gaim                                            install
    这时状态标志又被重置为 install,可以继续升级了。

    同志们会问,哪个这些状态标志都写在哪个文件中呢?
    在 /var/lib/dpkg/status 里你也可以通过修改这个文件实现 hold。

    有时你会发现有的软件状态标志是 purge,不要奇怪。
    如:事先已经安装了 amsn,然后把它卸了。
    apt-get remove --purge amsn
    那么状态标志就从 install 变成 purge。

    方法二:
    在/etc/apt 下手动建一个 preferences 文件
    内容:
    Package: gaim
    Pin: version 0.58*
    保存
    更详细内容请看:
    http://linuxsir.com/bbs/showthread.php?s=&threadid=22601

    dpkg -S <file>
    在包裹数据库中查找 <file>,并告诉你哪个包裹包含了这个文件。(注:查找的是事先已经安装的包裹)

    从源码建立 deb packages

    apt-get source [-b] <package>
    下载一个源码的包并解开。
    你必须在你的 /etc/apt/sources.list 文件里写入一条 deb-src 的记录才能完成这项工作。
    如果你输入了一个 -b 参数,并且是以 root 的身份,deb 包会被自动的创建。

    apt-get build-dep <package>
    自动下载并安装通过源码创建 <package> 时需要的包。
    只有apt 0.5以上版本才支持这个功能。
    现在woody和以上版本包含了这个功能。
    如果你使有一个旧版本的apt,查找依赖性最简单的方法是查看源码包中 debian/control 这个文件,
    注意这个路径是相对的,是包内的路径。

    普通的用法,结合 apt-get source -b,例子 (as root):

    apt-get build-dep <package>
    apt-get source -b <package>

    会下载源码包,建立依赖性,然后尝试编译源码。

    dpkg-source -x <package.dsc>
    如果你手工下载了一个程序的源码包,其中包含了几个类似 .orig.tar.gz ,.dsc ,
    以及 .diff.gz 之类的文件,
    那么你就可以对 .dsc 文件使用这个命令来 unpack 源码包。

    dpkg-buildpackage
    从 Debian 源码树建立一个 deb 包。你必须在 source tree 的主目录才能生效。例如:

    dpkg-buildpackage -rfakeroot -uc -b

    这里 '-rfakeroot' 指定命令使用 fakeroot 程序来模仿 root 权限 [来实现所有者(ownership)目的],
    '-uc' 表示 "Don't cryptographically sign the changelog",'-b' 代表只建立二进制包。

    debuild
    一个快速打包脚本类似 dpkg-buildpackage,能自动的识别是否使用 fakeroot,
    同时为你运行 lintiangpg

    修正倚赖关系

    dpkg --configure --pending
    如果 dpkg 在 apt-get install upgrade dist-uptradeing 的时候出错退出,
    尝试使用此命令来配置已经 unpack 的包。
    然后再用 apt-get install,upgrade,或者 dist-upgrade -f,
    然后再用 apt-get install,upgrade,或者 dist-upgrade。

    可能会重复多次,这样通常可以解决大多数的依赖性问题。
    (同时,如果提示由于某种原因需要某个特定的包裹,你可以常识安装或卸载这个包)

    apt-get install -f
    apt-get upgrade -f
    apt-get dist-upgrade -f
    尝试修正上述过程中出现依赖性关系
    注意 apt-get install -f 不需要 <package> 作为参数。
  • vimrc文件在debian系统里是/etc/vim/vimrc文件,而在其他系统里是本用户home目录下的.vimrc文件. 

    1 基本设置

    • set nocp
      该命令指定让 VIM 工作在不兼容模式下。 在 VIM 之前, 出现过一个非常流行的编辑器叫
      vi。 VIM 许多操作与 vi 很相似, 但也有许多操作与 vi 是不一样的。 如果使用“:set
      cp”命令打开了兼容模式开关的话, VIM 将尽可能地模仿 vi 的操作模式。


      例如:VIM 里允许在 Insert 模式下使用方向键移动光标, 而 vi 里在
      Insert 模式下是不能移动光标的, 必须使用 ESC 退回到 Normal 模式下才行。


      再举一个例子, vi 里使用 u 命令可以撤消一次先前的操作, 再次按下 u
      时, 将撤消“撤消”这个动作本身, 也就是我们常说的“重复”(redo)。
      而 VIM 里可以使用 u 命令撤消多步操作, “重复”使用的快捷键是 Ctrl
      + R。


      使用兼容模式后, VIM 将放弃这些新的功能, 尽量模仿 vi 的各种操作方式。
      只有在不兼容模式下, 才能更好地发挥 VIM 自身的特点。
    • set ru    

      该命令打开 VIM 的状态栏标尺。 默认情况下, VIM 的状态栏标尺在屏幕底部,
      它能即时显示当前光标所在位置在文件中的行号、列号, 以及对应的整个文件的百分比。
      打开标尺可以给文件的编辑工作带来一定方便。
         
    • set hls
      搜索时高亮显示被找到的文本。
    • set is
      搜索时在未完全输入完毕要检索的文本时就开始检索。
    • syntax on
      打开关键字色。
    • set backspace=indent,eol,start
      设想这样一个情况: 当前光标前面有若干字母, 按下 i 键进入了 Insert
      模式, 然后输入了 3 个字母, 再按 5 下删除(Backspace)。 默认情况下,
      VIM 仅能删除新输入的 3 个字母, 然后喇叭“嘟嘟”响两声。 如果“set
      backspace=start”, 则可以在删除了新输入的 3 个字母之后, 继续向前删除原有的两个字符。


      再 设想一个情况: 有若干行文字, 把光标移到中间某一行的行首, 按 i 键进入 Insert 模式, 然后按一下 Backspace。 默认情况下, 喇叭会“嘟”一声,然后没有任何动静。 如果“set backspace=eol”, 则可以删除前一行行末的回车,也就是说将两行拼接起来。


      当设置了自动缩进后, 如果前一行缩进了一定距离, 按下回车后, 下一行也会保持相同的缩进。
      默认情况下, 不能在 Insert 模式下直接按 Backspace 删除行首的缩进。
      如果“set backspace=indent”, 则可以开启这一项功能。


      上述三项功能, 可以选择其中一种或几种, 用逗号分隔各个选项。
    • set whichwrap=b,s,<,>,[,]
      默认情况下, 在 VIM 中当光标移到一行最左边的时候, 继续按左键,光标不能回到上一行的最右边。 同样地, 光标到了一行最右边的时候, 不能通过继续按右跳到下一行的最左边。
      但 是, 通过设置 whichwrap 可以对一部分按键开启这项功能。 如果想对某一个或几个按键开启到头后自动折向下一行的功能,可以把需要开启的键的代号写到 whichwrap 的参数列表中, 各个键之间使用逗号分隔。以下是 whichwrap 支持的按键名称列表:

       

      • b
        在 Normal 或 Visual 模式下按删除(Backspace)键。
      • s
        在 Normal 或 Visual 模式下按空格键。
      • h
        在 Normal 或 Visual 模式下按 h 键。
      • l
        在 Normal 或 Visual 模式下按 l 键。
      • <
        在 Normal 或 Visual 模式下按左方向键。
      • >
        在 Normal 或 Visual 模式下按右方向键。
      • ~
        在 Normal 模式下按 ~ 键(翻转当前字母大小写)。
      • [
        在 Insert 或 Replace 模式下按左方向键。
      • ]
        在 Insert 或 Replace 模式下按右方向键。
    • set encoding=cp936
      设置当前字符编码为简体中文。 
     
     

    2 文本编辑设置

       

    • set sw=4
      自动缩进的时候, 缩进尺寸为 4 个空格。
    • set ts=4
      Tab 宽度为 4 个字符。
    • set et
      编辑时将所有 Tab 替换为空格。


      该选项只在编辑时将 Tab 替换为空格, 如果打开一个已经存在的文件, 并不会将已有的
      Tab 替换为空格。 如果希望进行这样的替换的话, 可以使用这条命令“:retab”。

    3 断行设置

       

    • set lbr
      不在单词中间断行。 设置了这个选项后, 如果一行文字非常长, 无法在一行内显示完的话,
      它会在单词与单词间的空白处断开, 尽量不会把一个单词分成两截放在两个不同的行里。
    • set fo+=mB
      打开断行模块对亚洲语言支持。 m 表示允许在两个汉字之间断行, 即使汉字之间没有出现空格。
      B 表示将两行合并为一行的时候, 汉字与汉字之间不要补空格。 该命令支持的更多的选项请参看用户手册。

    4 C/C++ 编码设置

    • set sm
      显示括号配对情况。 打开这个选项后, 当输入后括号 (包括小括号、中括号、大括号)
      的时候, 光标会跳回前括号片刻, 然后跳回来, 以此显示括号的配对情况。
    • set cin
      打开 C/C++ 风格的自动缩进。 打开了自动缩进后, 在编码的时候可以使用“V”命令选中一段文本后,按“=”将这段文本重新调整缩进格式, 在一定程度上起到代码美化的作用。


      另外, 打开了自动缩进后, 在使用 TERM 下的 vim 的时, 粘贴代码时常常会出现版式混乱的现象。那是因为 TERM 并不知道现在正在粘贴代码, 它直接“粘贴”动作向 vim
      解释为键入, 因此 vim 便按照设置的自动缩进格式为的代码调整了缩进。
      不幸的是, 粘贴进去的代码中本身已经包含了缩进, 因此便出现了版式混乱的情况。
      在 gvim 中就不会出现这个问题, 因为它能够知道现在正在粘贴。


      知道了这个症状的来由, 解决方案也就显而易见了: 在粘贴的时候把所有自动缩进都关闭,
      粘贴完毕之后再打开。 一个个手工关闭自动缩进未免过于繁琐, vim 为提供了一个很好用的命令,只要输入“:set paste”, 就可以关闭所有自动缩进。 粘贴完毕后再输入“:set
      nopaste”就可以重新打开原有的自动缩进设置了。
    • set cino=:0g0t0(sus
      设定 C/C++ 风格自动缩进的选项, 这里简要介绍一下这段代码里用到的选项的含义,
      cino 支持的选项还很多, 更多选项请看用户手册。
      // :0
      //
      // switch 语句之下的 case 语句缩进 0 个空格,也就是说不缩进,与 switch 块平
      // 齐,使用这样风格:
      switch (x)
      {
      case 1:
          a = b;
          break;
      default:
      }

       

      // g0
      //
      // class、struct 等之下的访问权限控制语句,如 public、protected、private 等,
      // 相对 class、struct 等所在的块缩进 0 个空格,与 class 等块平齐,使用这样的
      // 风格:
      class foo
      {
      public:
          int a;
      private:
          int b;
      };

      // t0
      //
      // 如果函数返回值与函数名不在同一行,则返回值缩进 0 个空格,也就是说不缩进,如
      // 下所示:

      // set cino=t4
          int
      func1()
      {
      }

      // set cino=t0
      int
      func()
      {
      }

      // (sus
      //
      // 当一对括号跨越多行时,其后的行缩进前面 sw 指定的距离,效果如下:
      int a = (1 + 2 + 3
          + 4 + 5 + 6
          + 7 + 8) * 9;

     

    • set ai
      打开普通文件类型的自动缩进。 该自动缩进不如 cindent 智能, 但它可以为你编辑非
      C/C++ 文件提供一定帮助。
    5 其它设置

       

    • set selectmode=
      不使用 selectmode。
    • set mousemodel=popup
      当右键单击窗口的时候, 弹出快捷菜单。
    • set keymodel=
      不使用“Shift + 方向键”选择文本, “Shift + 方向键”代表向指定方向跳一个单词。
      如果你喜欢这项功能的话, 可以使用“set keymodel=startsel,stopsel”打开它。
    • set selection=inclusive
      指定在选择文本时, 光标所在位置也属于被选中的范围。 如果指定 selection=exclusive
      的话, 可能会出现某些文本无法被选中的情况。
    • colo torte
      选择 torte 配色方案。 VIM 里内置了许多关键字上色的配色方案, 另外你还可以到网上下载更多配色方案,或是自己编写。 点击“编辑”→“调色板”, 就能列出所有支持的配色方案。
      你可以把“调色板”子菜单剪下来, 然后慢慢选择, 挑出一个最喜欢的配色方案来。
    6 图形界面设置
    • set nowrap
      指定不折行。 如果一行太长, 超过屏幕宽度, 则向右边延伸到屏幕外面。
      如果使用图形界面的话, 指定不折行视觉效果会好得多。
    • set guioptions+=b
      添加水平滚动条。 如果你指定了不折行, 那为窗口添加一个水平滚动条就非常有必要了。
    • set guifont=Courier\ 9
      设置图形界面下的字体。 你可以点“编辑”→“选择字体”, 然后在对话框中选出你喜欢的字体与字号,选择完毕后, 先按几下 ESC 确认处在 Normal 模式下, 然后输入这条命令:“:set
      guifont?” 回车后 gvim 屏幕最下方会显示出你当前所用的字体的名称与字号。
      将获得的结果写到配置文件里面就可以了, 需要注意一点, 如果字体名称里面含有空格的话,
      在抄的时候需要在所有空格前面加一个斜杠。
    7 条件选择
    同一个配色方案, 在 gvim 下和字符界面的 vim 下效果大相径庭,在 gvim 下使用 torte 配色方案, 在 vim 下使用 ron 配色方案。 因此我们有必要针对gvim 和 vim 进行不同的设置。
    另外, 前面我们在 gvim 下不使用折行, 开启水平滚动条, 但在 vim 下,是没有滚动条可用的, 因此还是有必要为 vim 保留自动折行。
    条件选择设置的格式如下:
  • After seeing the how to mount a fat32 partition I thought I'd show you how to mount a share.

    First off you need to make sure the share it setup correctly on your Windows system, I'll only focus on sharing with WinXP.

    Its not hard on WinXP. First off right-click on the folder you wish to share and select "Sharing and Security".

    Select "Share this folder".

    You can now set the Share name, you can also fiddle with the maximum number of users allowed at one time (the default is normally good enough).

    If you want to heighten the security in this share you can click on "Permissions" and remove the default "Everyone" group (select and click Remove). After this you can click Add. Type the username that will be used to allow access (this has to be a valid user on your WinXP machine). Click Ok, and Ok again. The folder icon should alter and a hand will be holding the folder. This indicates a network share.

    Ok so you need to know these things:
    The hostname of the WinXP PC (eg winpc). Right click on "My Computer" click on "Computer Name". Look at the "Full Computer Name".

    The sharename of the folder (eg shared) Do you remember what you called it tongue.gif.

    A user/pass for the winxp system. This is only required if you altered the permissions (i.e. if its not sharing to Everyone).

    Phew 50% of the way there.

    Ok so onto the Linux system, its relatively simple:

    Make the directory you want to mount the share to.
    CODE
    mkdir /mnt/share


    Next either...

    Mount the share with user/pass:
    CODE
    smbmount //winpc/shared /mnt/share -o username=user,password=pass,rw


    Or mount the share without a user/pass (this is true if Everyone is still set)
    CODE
    smbmount //winpc/shared /mnt/share -o rw


    Hopefully thats it. Now you can use the share. You cannot create symbolic links or chmod the system (this is restriction on the WinXP side).

    If you wish to allow users on the linux side access to the share then you will need to alter the options. Adding in uid= or gid= to allow access to users or groups respectively by mounting the drive with there permissions. Here's an example:

    CODE
    smbmount //winpc/shared /mnt/share -o rw,uid=znx


    This will mount the drive as if user znx had done it. Thus he will have rw access to the shared.

    Hands up who I managed to confuse wink.gif
    znx
    Decided to append some more to this:

    Make a file /root/.creds (you will be root!)
    CODE
    username = znx
    password = mypassword


    Make sure the file is closed permissions...
    CODE
    chmod 0600 /root/.creds


    Now edit /etc/fstab and add a line for the share:
    CODE
    //winpc/shared  /mnt/share  smbfs  credentials=/root/.creds,rw,uid=znx  0  0


    Now the share can be mounted just by doing:
    CODE
    mount /mnt/share


    Simple enough happy.gif
    znx
    A problem was encountered using the smbmount command saying something like:

    CODE
    Usage: mount.smbfs service mountpoint [-n] [-o options,...]" followed by the list of options and "This command is designed to be run from within /bin/mount by giving the option '-t smbfs'.


    You can overcome this using the mount command:

    CODE
    mount -t smbfs -o username=USER,password=PASS //server/share /mnt/share


    Replacing USER/PASS as before.
    znx
    Expanding again smile.gif

    If you wish to open access to other users you can use the "umask" option with mount. You will need to understand the octal modes for file permissions a little to use this fully.

    For instance:
    umask 022 relates to 755 rwxr-xr-x (755 + 022 = 777).

    If you are confused by this you can use umask=000 .. this will give read/write/execute permissions to ALL users.

    Now to show umask in both the command line:

    CODE
    mount -t smbfs -o username=USER,password=PASS,umask=022 //server/share /mnt/share


    And in fstab:

    CODE
    //winpc/shared  /mnt/share  smbfs  credentials=/root/.creds,rw,umask=022  0  0


    Using umask allows you to adjust the permissions of the mounted share.

    Summing up you can therefore control user (uid=), group (gid=) and permissions (umask=) on the mounted share.
    Shadowcat
    bah edit the original post lazybones tongue.gif


    Which post .. ? [znx]
    Andy72
    Thanks a lot for this guide!!

    I followed your first example, the one without user/password and got it works superb :-)

    But, How do I save this setting, dont want mount it manually evereytime I restart the computer...

    I Have tried to edit the fstab but get error, can someone help a real Noob with a coode that NOT supose to have a password or username.... (i have a xbox and other stuff conected to the network and want not to setupp password, yes I m lazy...)

    BR /Andreas

    _________
    Edit:
    This line works good in fstab:
    //servername/sharename /media/sharename smbfs rw 0 0

    But after restart I need to type sudo mount -a

    So again, why does my Kubuntu not automatically do this during restart...
    znx
    QUOTE (Andy72 @ Jul 10 2006, 02:40 PM) *
    Thanks a lot for this guide!! I followed your first example, the one without user/password and got it works superb :-)


    Yay!

    QUOTE (Andy72 @ Jul 10 2006, 02:40 PM) *
    So again, why does my Kubuntu not automatically do this during restart...


    You are there, any normal system would auto mount that with no issues.

    Interestingly enough I know why this is. There is a bug with kubuntu (and ubuntu) that means it will hang if samba is auto mounted from fstab. I believe it has to do with the kernel module not being installed early enough.

    So to work around this, do the following:

    /etc/fstab add the "noauto" option to ensure that its not going to be auto mounted.
    CODE
    //servername/sharename /media/sharename smbfs rw,noauto 0 0


    The open up /etc/rc.local (make one if its not there) and add:
    CODE
    mount /media/sharename


    By the time that rc.local is run the kernel module will be there and all should be well (proof of this is your ability to mount -a after its all booted).

    happy.gif
    Andy72
    Hi, think I'm need some more help! :-(

    Fixed the noauto and the fstab and restarted the computer, but the disk are not mounted (and it.s now not possible to use the mount -a command because the noautu).

    As before when I click on the icon for the share folder in desktop I get the messege that only root can mount it... (I have even added more rights to the useracount besides admin also root, disks...)

    Is there a way to verify that the rc.local has been started? It works fine if I type sudo /etc/rc.local (and password) in the terminal...
    znx
    QUOTE (Andy72 @ Jul 11 2006, 05:21 PM) *
    Hi, think I'm need some more help! :-(


    Ah .. my fault I think, do this:
    CODE
    chmod +x /etc/rc.local


    Adding executable permissions to it.

    If it runs the script .. you should see (as the last thing) something like:
    CODE
    * Running local boot scripts


    Or similar.
    Andy72
    Thank you for your patience with me, but I’m sorry to say that it still not working. It´s exactly the same as before, and I not sure that I can see something like running any boot scripts during the boot up (its sweep away very fast in the end, and can not break/pasue)…

    If you have any more idea I’m happy too hear them otherwise it’s ok, I now it’s not easy to serve computers from distance… :\

    I have done some progress with Linux anyway, I can now log into linux from my windows pc, so its works auto from that direction (that way I need password, maybe I find a solution to shut it off)!
    samssf
    You people need to stop posting answers to questions unless you know your advice will work. I've lost about 30 hours in the last 4 days because of this.

    I too have the same problem.

    I installed Ubuntu 6.06 dapper drake as dual boot. Followed instructions and installed it correctly. Everything is great... except whenever I click on a drive in "Computer" I get a message that says "Only root can mount /dev/sdc1". And yes, I have tried everything I can think of. My fstab looks fine. I've tried sudo and sudo su to root.

    Helpful suggestions please. Obivously lots of people have had this issue if I received the error on a clean install.
    anyweb
    QUOTE
    samssf Posted Today, 01:17 AM
    You people need to stop posting answers to questions unless you know your advice will work. I've lost about 30 hours in the last 4 days because of this.
    if we don't post howto's then how will people learn ?

    QUOTE
    I installed Ubuntu 6.06 dapper drake as dual boot. Followed instructions and installed it correctly. Everything is great... except whenever I click on a drive in "Computer" I get a message that says "Only root can mount /dev/sdc1".


    ok lets be clear here, are you trying to mount ANOTHER computers (windows xp) 'share' or are you trying to mount your dual boot NTFS drive ? To be clear, THIS POST is about how to mount ANOTHER computers share from within linux, it is not about how to mount an NTFS drive/partition within linux.

    if that's the case then you need to read the 'how to mount an NTFS drive in 5 minutes or less... post'

    if this is not the case then please give us details of what you have tried and what your exact error is,

    the more details the better, oh and welcome to the forums,

    cheers
    anyweb
    znx
    QUOTE (samssf @ Sep 20 2006, 02:17 AM) *
    /dev/sdc1


    That is a local drive, what this howto is for is remote windows share. Check out the link that anyweb provided.

    It should be made clear to all, this tutorial requires two separate machines, one a linux system the other a windows system, I'm sorry if there was any confusion with regards to this.
    dustman
    i tried all the methods stated in this thread, but all i get is this
    CODE
    dustman@dustman-laptop:~$ smbmount //smb://ionut/ /home/dustman/Muzica/jean/ -o ro
    11060: Connection to smb: failed
    SMB connection failed


    where "//smb://ionut" is the network path of the share folder i want to mount, and "/home/dustman/Muzica/jean/ " is the path i want to mount the share folder

    With the second method i get:
    CODE
    dustman@dustman-laptop:~$ sudo mount -t smbfs -o guest //smb://ionut /home/dustman/Muzica/jean/
    11318: Connection to smb: failed
    SMB connection failed


    basicly the same stuff as the first method. What am I doing wrong? :|


    P.S. the network has only two users...my laptop and "ionut" computer...so there are no username and password set. In windows it works like a dream, but in ubuntu is doesn't sad.gif
    znx
    Remove the //smb: from the front of your lines. It sees the smb: as the name of the PC its trying to connect to!

    CODE
    $ smbmount //IPADDRESS/ionut /home/dustman/Muzica/jean/ -o ro


    Or

    CODE
    $ sudo mount -t smbfs -o guest //IPADDRESS/ionut /home/dustman/Muzica/jean/


    There we go smile.gif
    dustman
    QUOTE (znx @ Nov 21 2007, 03:37 PM) *
    Remove the //smb: from the front of your lines. It sees the smb: as the name of the PC its trying to connect to!

    CODE
    $ smbmount //IPADDRESS/ionut /home/dustman/Muzica/jean/ -o ro


    Or

    CODE
    $ sudo mount -t smbfs -o guest //IPADDRESS/ionut /home/dustman/Muzica/jean/


    There we go smile.gif


    yes, yes....it's working biggrin.gif i figured it out.... thank you for answering smile.gif


    Cheers!


    Radu
    This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
    Invision Power Board © 2001-2008 Invision Power Services, Inc.
  • BusyBox 简化嵌入式 Linux 系统

    为小环境准备的一个小工具包

    developerWorks
    文档选项
    将此页作为电子邮件发送

    将此页作为电子邮件发送


    级别: 初级

    M. Tim Jones (mtj@mtjones.com), 咨询工程师, Emulex

    2006 年 9 月 11 日

    BusyBox 是很多标准 Linux® 工具的一个单个可执行实现。BusyBox 包含了一些简单的工具,例如 cat 和 echo,还包含了一些更大、更复杂的工具,例如 grep、find、mount 以及 telnet(不过它的选项比传统的版本要少);有些人将 BusyBox 称为 Linux 工具里的瑞士军刀。本文将探索 BusyBox 的目标,它是如何工作的,以及为什么它对于内存有限的环境来说是如此重要。

    BusyBox 的诞生

    BusyBox 最初是由 Bruce Perens 在 1996 年为 Debian GNU/Linux 安装盘编写的。其目标是在一张软盘上创建一个可引导的 GNU/Linux 系统,这可以用作安装盘和急救盘。一张软盘可以保存大约 1.4-1.7MB 的内容,因此这里没有多少空间留给 Linux 内核以及相关的用户应用程序使用。

    BusyBox 许可证
    BusyBox 是按照 GNU General Public License(GPL)许可证发行的。这意味着如果我们在一个项目中使用 BusyBox,就必须遵守这个许可证。我们可以在 BusyBox Web 站点(请参看本文后面 参考资料 一节的内容)上看到这个许可证的内容。BusyBox 团队似乎正忙于监视违反这个许可证的情况。实际上,他们维护了一个 “Hall of Shame” 页面来说明违反者的情况。

    BusyBox 揭露了这样一个事实:很多标准 Linux 工具都可以共享很多共同的元素。例如,很多基于文件的工具(比如 grepfind)都需要在目录中搜索文件的代码。当这些工具被合并到一个可执行程序中时,它们就可以共享这些相同的元素,这样可以产生更小的可执行程序。实际上,BusyBox 可以将大约 3.5MB 的工具包装成大约 200KB 大小。这就为可引导的磁盘和使用 Linux 的嵌入式设备提供了更多功能。我们可以对 2.4 和 2.6 版本的 Linux 内核使用 BusyBox。

    BusyBox 是如何工作的?

    为了让一个可执行程序看起来就像是很多可执行程序一样,BusyBox 为传递给 C 的 main 函数的参数开发了一个很少使用的特性。回想一下 C 语言的 main 函数的定义如下:

    POSIX 环境
    尽管 BusyBox 的目标 是提供一个相当完整的 POSIX(可移植操作系统接口)环境,这是一个期望,而不是一种需求。这些工具虽然并不完整,但是它们提供了我们期望的主要功能。

    清单 1. C 的 main 函数
    int main( int argc, char *argv[] )
    

    在这个定义中,argc 是传递进来的参数的个数(参数数量),而 argv 是一个字符串数组,代表从命令行传递进来的参数(参数向量)。argv 的索引 0 是从命令行调用的程序名。

    清单 2 给出的这个简单 C 程序展示了 BusyBox 的调用。它只简单地打印 argv 向量的内容。


    清单 2. BusyBox 使用 argv[0] 来确定调用哪个应用程序
    // test.c
    #include <stdio.h>
    
    int main( int argc, char *argv[] )
    {
      int i;
    
      for (i = 0 ; i < argc ; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
      }
    
      return 0;
    }
    

    调用这个程序会显示所调用的第一个参数是该程序的名字。我们可以对这个可执行程序重新进行命名,此时再调用就会得到该程序的新名字。另外,我们可以创建一个到可执行程序的符号链接,在执行这个符号链接时,就可以看到这个符号链接的名字。


    清单 3. 在使用新命令更新 BusyBox 之后的命令测试
    $ gcc -Wall -o test test.c
    $ ./test arg1 arg2
    argv[0] = ./test
    argv[1] = arg1
    argv[2] = arg2
    
    $ mv test newtest
    $ ./newtest arg1
    argv[0] = ./newtest
    argv[1] = arg1
    
    $ ln -s newtest linktest
    $ ./linktest arg
    argv[0] = ./linktest
    argv[1] = arg
    

    BusyBox 使用了符号链接以便使一个可执行程序看起来像很多程序一样。对于 BusyBox 中包含的每个工具来说,都会这样创建一个符号链接,这样就可以使用这些符号链接来调用 BusyBox 了。BusyBox 然后可以通过 argv[0] 来调用内部工具。





    回页首


    配置并编译 BusyBox

    我们可以从 BusyBox 的 Web 站点上下载最新版本的 BusyBox(请参看 参考资料 一节的内容)。与大部分开放源码程序一样,它是以一个压缩的 tarball 形式发布的,我们可以使用清单 4 给出的命令将其转换成源代码树。(如果我们下载的版本不是 1.1.1,那就请在这个命令中使用适当的版本号以及特定于这个版本号的命令。)


    清单 4. 展开 BusyBox
    $ tar xvfz busybox-1.1.1.tar.gz
    $
    

    结果会生成一个目录,名为 busybox-1.1.1,其中包含了 BusyBox 的源代码。要编译默认的配置(其中包含了几乎所有的内容,并禁用了调试功能),请使用 defconfig make 目标:

    BusyBox 源代码树
    BusyBox 的源代码树组织得很好。这些工具都基于它们的用途进行了分类,并存储在单独的子目录中。例如,网络工具和守护进程(如 httpdifconfig 等)都在 ./networking 目录中;标准的模块工具(包括 insmodrmmodlsmod)都在 ./modutils 目录中;编辑器(例如 vi 和流编辑器,如 awksed)都在 ./editors 目录中。makefile 配置、编译和安装所使用的各个文档都在这个目录树的根目录中。

    清单 5. 编译默认的 BusyBox 配置
    $ cd busybox-1.1.1
    $ make defconfig
    $ make
    $
    

    结果是一个相当大的 BusyBox 映像,不过这只是开始使用它的最简单的方法。我们可以直接调用这个新映像,这会产生一个简单的 Help 页面,里面包括当前配置的命令。要对这个映像进行测试,我们也可以对一个命令调用 BusyBox 来执行,如清单 6 所示。


    清单 6. 展示 BusyBox 命令的执行和 BusyBox 中的 ash shell
    $ ./busybox pwd
    /usr/local/src/busybox-1.1.1
    $ ./busybox ash
    /usr/local/src/busybox-1.1.1 $ pwd
    /usr/local/src/busybox-1.1.1
    /usr/local/src/busybox-1.1.1 $ exit
    $
    

    在这个例子中,我们调用了 pwd(打印工作目录)命令,使用 BusyBox 进入了 ash shell,并在 ash 中调用了 pwd





    回页首


    手工配置

    如果您正在构建一个具有特殊需求的嵌入式设备,那就可以手工使用 menuconfig make 目标来配置 BusyBox 的内容。如果您熟悉 Linux 内核的编译过程,就会注意到 menuconfig 与配置 Linux 内核的内容所使用的目标相同。实际上,它们都采用了相同的基于 ncurses 的应用程序。

    使用手工配置,我们可以指定在最终的 BusyBox 映像中包含的命令。我们也可以对 BusyBox 环境进行配置,例如包括对 NSA(美国国家安全代理)的安全增强 Linux(SELinux),指定要使用的编译器(用来在嵌入式环境中进行交叉编译)以及 BusyBox 应该静态编译还是动态编译。图 1 给出了 menuconfig 的主界面。在这里我们应该可以看到可以为 BusyBox 配置的不同类型的应用程序(applet)。


    图 1. 使用 menuconfig 配置 BusyBox
    使用 menuconfig 配置 BusyBox
    多体系结构支持
    可以简单地为 BusyBox 指定交叉编译器意味着我们可以为很多体系结构编译 BusyBox。要为您的目标体系结构编译 BusyBox,我们需要一个交叉编译器和一个已经为特定目标体系结构编译好的 C 库(uClibc 或 glibc)。

    要手工配置 BusyBox,请使用下面的命令:


    清单 7. 手工配置 BusyBox
    $ make menuconfig
    $ make
    $
    

    这为我们提供了可以调用的 BusyBox 的二进制文件。下一个步骤是围绕 BusyBox 构建一个环境,包括将标准 Linux 命令重定向到 BusyBox 二进制文件的符号链接。我们可以使用下面的命令简单地完成这个过程:


    清单 8. 构建 BusyBox 环境
    $ make install
    $
    

    默认情况下,这会创建一个新的本地子目录 _install,其中包含了基本的 Linux 环境。在这个根目录中,您会找到一个链接到 BusyBox 的 linuxrc 程序。这个 linuxrc 程序在构建安装盘或急救盘(允许提前进行模块化的引导)时非常有用。同样是在这个根目录中,还有一个包含操作系统二进制文件的 /sbin 子目录。还有一个包含用户二进制文件的 /bin 目录。在构建软盘发行版或嵌入式初始 RAM 磁盘时,我们可以将这个 _install 目录迁移到目标环境中。我们还可以使用 make 程序的 PREFIX 选项将安装目录重定向到其他位置。例如,下面的代码就使用 /tmp/newtarget 根目录来安装这些符号链接,而不是使用 ./_install 目录:


    清单 9. 将符号链接安装到另外一个目录中
    $ make PREFIX=/tmp/newtarget install
    $
    

    使用 install make 目标创建的符号链接都来自于 busybox.links 文件。这个文件是在编译 BusyBox 时创建的,它包含了已经配置的命令清单。在执行 install 时,就会检查 busybox.links 文件确定要创建的符号链接。

    到 BusyBox 的命令行链接也可以使用 BusyBox 在运行时动态创建。CONFIG_FEATURE_INSTALLER 选项就可以启用这个特性,在运行时可以这样执行:


    清单 10. 在运行时创建命令链接
    $ ./busybox --install -s
    $
    

    -s 选项强制创建这些符号链接(否则就创建硬链接)。这个选项要求系统中存在 /proc 文件系统。





    回页首


    BusyBox 编译选项

    BusyBox 包括了几个编译选项,可以帮助为我们编译和调试正确的 BusyBox。


    表 1. 为 BusyBox 提供的几个 make 选项
    make 目标说明
    help显示 make 选项的完整列表
    defconfig启用默认的(通用)配置
    allnoconfig禁用所有的应用程序(空配置)
    allyesconfig启用所有的应用程序(完整配置)
    allbareconfig启用所有的应用程序,但是不包括子特性
    config基于文本的配置工具
    menuconfigN-curses(基于菜单的)配置工具
    all编译 BusyBox 二进制文件和文档(./docs)
    busybox编译 BusyBox 二进制文件
    clean清除源代码树
    distclean彻底清除源代码树
    sizes显示所启用的应用程序的文本/数据大小

    在定义配置时,我们只需要输入 make 就可以真正编译 BusyBox 二进制文件。例如,要为所有的应用程序编译 BusyBox,我们可以执行下面的命令:


    清单 11. 编译 BusyBox 二进制程序
    $ make allyesconfig
    $ make
    $
    





    回页首


    压缩 BusyBox

    如果您非常关心对 BusyBox 映像的压缩,就需要记住两件事情:

    1. 永远不要编译为静态二进制文件(这会将所有需要的库都包含到映像文件中)。相反,如果我们是编译为一个共享映像,那么它会使用其他应用程序使用的库(例如 /lib/libc.so.X)。
    2. 使用 uClibc 进行编译,这是一个对大小进行过优化的 C 库,它是为嵌入式系统开发的;而不要使用标准的 glibc (GNU C 库)来编译。




    回页首


    BusyBox 命令中支持的选项

    BusyBox 中的命令并不支持所有可用选项,不过这些命令都包含了常用的选项。如果我们需要知道一个命令可以支持哪些选项,可以使用 --help 选项来调用这个命令,如清单 12 所示。


    清单 12. 使用 --help 选项调用命令
    $ ./busybox wc --help
    BusyBox v1.1.1 (2006.04.09-15:27+0000) multi-call binary
    
    Usage: wc [OPTION]... [FILE]...
    
    Print line, word, and byte counts for each FILE, and a total line if
    more than one FILE is specified. With no FILE, read standard input.
    
    Options:
    	-c	print the byte counts
    	-l	print the newline counts
    	-L	print the length of the longest line
    	-w	print the word counts
    
    $
    

    这些特定的数据只有在启用了 CONFIG_FEATURE_VERBOSE_USAGE 选项时才可以使用。如果没有这个选项,我们就无法获得这些详细数据,但是这样可以节省大约 13 KB 的空间。





    回页首


    向 BusyBox 中添加新命令

    向 BusyBox 添加一个新命令非常简单,这是因为它具有良好定义的体系结构。第一个步骤是为新命令的源代码选择一个位置。我们要根据命令的类型(网络,shell 等)来选择位置,并与其他命令保持一致。这一点非常重要,因为这个新命令最终会在 menuconfig 的配置菜单中出现(在下面的例子中,是 Miscellaneous Utilities 菜单)。

    对于这个例子来说,我将这个新命令称为 newcmd,并将它放到了 ./miscutils 目录中。这个新命令的源代码如清单 13 所示。


    清单 13. 集成到 BusyBox 中的新命令的源代码
    #include "busybox.h"
    
    int newcmd_main( int argc, char *argv[] )
    {
      int i;
    
      printf("newcmd called:\n");
    
      for (i = 0 ; i < argc ; i++) {
    
        printf("arg[%d] = %s\n", i, argv[i]);
    
      }
    
      return 0;
    }
    

    接下来,我们要将这个新命令的源代码添加到所选子目录中的 Makefile.in 中。在本例中,我更新了 ./miscutils/Makefile.in 文件。请按照字母顺序来添加新命令,以便维持与现有命令的一致性:


    清单 14. 将命令添加到 Makefile.in 中
    MISCUTILS-$(CONFIG_MT)          += mt.o
    MISCUTILS-$(CONFIG_NEWCMD)   += newcmd.o
    MISCUTILS-$(CONFIG_RUNLEVEL)    += runlevel.o
    

    接下来再次更新 ./miscutils 目录中的配置文件,以便让新命令在配置过程中是可见的。这个文件名为 Config.in,新命令是按照字母顺序添加的:


    清单 15. 将命令添加到 Config.in 中
    config CONFIG_NEWCMD
    	bool "newcmd"
    	default n
    	help
    	  newcmd is a new test command.
    

    这个结构定义了一个新配置项(通过 config 关键字)以及一个配置选项(CONFIG_NEWCMD)。新命令可以启用,也可以禁用,因此我们对配置的菜单属性使用了 bool (Boolean)值。这个命令默认是禁用的(n 表示 No),我们可以最后放上一个简短的 Help 描述。在源代码树的 ./scripts/config/Kconfig-language.txt 文件中,我们可以看到配置语法的完整文法。

    接下来需要更新 ./include/applets.h 文件,使其包含这个新命令。将下面这行内容添加到这个文件中,记住要按照字母顺序。维护这个次序非常重要,否则我们的命令就会找不到。


    清单 16. 将命令添加到 applets.h 中
    USE_NEWCMD(APPLET(newcmd, newcmd_main, _BB_DIR_USER_BIN, _BB_SUID_NEVER))
    

    这定义了命令名(newcmd),它在 Busybox 源代码中的函数名(newcmd_main),应该在哪里会为这个新命令创建链接(在这种情况中,它在 /usr/bin 目录中),最后这个命令是否有权设置用户 id(在本例中是 no)。

    倒数第二个步骤是向 ./include/usage.h 文件中添加详细的帮助信息。正如您可以从这个文件的例子中看到的一样,使用信息可能非常详细。在本例中,我只添加了一点信息,这样就可以编译这个新命令了:


    清单 17. 向 usage.h 添加帮助信息
    #define newcmd_trivial_usage	"None"
    #define newcmd_full_usage	"None"
    

    最后一个步骤是启用新命令(通过 make menuconfig,然后在 Miscellaneous Utilities 菜单中启用这个选项)然后使用 make 来编译 BusyBox。

    使用新的 BusyBox,我们可以对这个新命令进行测试,如清单 18 所示。


    清单 18. 测试新命令
    $ ./busybox newcmd arg1
    newcmd called:
    arg[0] = newcmd
    arg[1] = arg1
    $ ./busybox newcmd --help
    BusyBox v1.1.1 (2006.04.12-13:47+0000) multi-call binary
    
    Usage: newcmd None
    
    None
    

    就是这样!BusyBox 开发人员开发了一个优秀但非常容易扩展的工具。





    回页首


    结束语

    BusyBox 是为构建内存有限的嵌入式系统和基于软盘系统的一个优秀工具。BusyBox 通过将很多必需的工具放入一个可执行程序,并让它们可以共享代码中相同的部分,从而对它们的大小进行了很大程度的缩减,BusyBox 对于嵌入式系统来说是一个非常有用的工具,因此值得我们花一些时间进行探索。



    参考资料

    学习
    • 您可以参阅本文在 developerWorks 全球站点上的 英文原文

    • uClibcglibc 一个精简内存需求的替代品。尽管它需要的资源比 glibc 少,但是将应用程序移植到 uClibc 上通常只需要重新编译即可。

    • Open Group 站点上的 POSIX FAQ 可以帮助我们学习更多有关 POSIX 的知识。这个规范的第 3 部分详细介绍了 shell 和工具的相关内容。

    • LinuxTiny 是用来减少 2.6 版本的 Linux 内核对内存和磁盘需求的一系列补丁,它只有 2MB 大小的 RAM。如果您对精简 2.6 版本的 Linux 内核感兴趣,请尝试一下 Matt Mackall 所开发的这个工具。

    • developerWorks Linux 专区 可以找到为 Linux 开发人员准备的更多资源。

    • 随时关注 developerWorks 技术事件和网络广播

    获得产品和技术
    • 下载 BusyBox 的最新版本。我们可以找到最新的新闻、勘误以及使用并改进 BusyBox 的教程。

    • 订购免费的 SEK for Linux,这有两张 DVD,包括最新的 IBM for Linux 的试用软件,包括 DB2®、Lotus®、Rational®、Tivoli® 和 WebSphere®。

    • 在您的下一个开发项目中采用 IBM 试用软件,这可以从 developerWorks 上直接下载。


    讨论


    关于作者

    M. Tim Jones

    Tim Jones 是一名嵌入式软件工程师,他是 GNU/Linux Application ProgrammingAI Application Programming 以及 BSD Sockets Programming from a Multilanguage Perspective 等书的作者。他的工程背景非常广泛,从同步宇宙飞船的内核开发到嵌入式架构设计,再到网络协议的