Wednesday, May 30, 2012

Tmux 用法


tmux 是噗浪上 @mosky 大大之前推薦的 terminal multiplexer

其實這玩意跟 screen 很像,不過最大差別應該在於 license 不同 (BSD vs GPL),有人不爽用XDDD

他最強大的功能在於 split pane




screen 的概念是一個 screen 底下有多個 window

tmux 則是可以用有多個 window,window 底下又可以有多個 pane, pane 又可以隨時展開成 window









精美圖片來源: http://josephjiang.com/entry.php?id=373 




tmux 還有一個特色功能就是 title 可以設成中文 (貌似是 UTF8)

不過應該沒人會無聊設 title 時還切換輸入法打中文,好像是有點雞肋的功能XDD




漫畫


src: http://pragprog.com/book/bhtmux/tmux




一般 Debian based Linux 可以用 apt-get install tmux 直接安裝








Ctrl-B (前導鍵, 類似 screen 的 Ctrl-A)

不過如果在像是 vim 或是 less 等基於 vi UI 的 pager

Ctrl-B 是 PageUp ,反而操作不便(要多按兩下)

screen 綁的 Ctrl - A 在 vim 裏面是比較不會用到的數字物件遞增的功能,較不會影響我對 vim 的使用

當然 config 寫一寫這些 key binding 都可以改的XDDD






以下常用功能介紹


基於 window
Ctrl-B c          create 創建新 window
Ctrl-B &          關閉目前的 window
Ctrl-B n/p        next/previous 切換到下一個 / 上一個 window
Ctrl-B [N]        切換到 [N] 號 window
Ctrl-B d          detach 目前的 session / shell 下 tmux attach 可以恢復 session
Ctrl-B ?          大絕招,顯示所有 key binding
Ctrl-B ~          tmux message log
Ctrl-B l          兩個 window 間往返
Ctrl-B w          window list
Ctrl-B ,          rename window title

基於 pane
Ctrl-B "          水平 split
Ctrl-B %          垂直 split
Ctrl-B x          關掉目前 pane
Ctrl-B !          把目前的 pane 搬到新的 window 下
Ctrl-B Ctrl       [上下左右] 調整 pane 大小
Ctrl-B Alt        [上下左右] 調整 pane 大小 (一次調五格)
Ctrl-B space      切切看其他 pane 排列方式
Ctrl-B q          顯示 pane 編號 (持續一秒)
Ctrl-B t          在目前的 pane 顯示時間
Ctrl-B o          切換到下一個 pane
Ctrl-B [上下左右]   切換到該方向的 pane
Ctrl-B { 或 }      向前/後移動 pane
Ctrl-B Alt/Ctrl o 逆時針 / 順時針旋轉 pane


不過其實他的 man page 已經很完整了

           C-b         Send the prefix key (C-b) through to the application.
           C-o         Rotate the panes in the current window forwards.
           C-z         Suspend the tmux client.
           !           Break the current pane out of the window.
           "           Split the current pane into two, top and bottom.
           #           List all paste buffers.
           $           Rename the current session.
           %           Split the current pane into two, left and right.
           &           Kill the current window.
           '           Prompt for a window index to select.
           ,           Rename the current window.
           -           Delete the most recently copied buffer of text.
           .           Prompt for an index to move the current window.
           0 to 9      Select windows 0 to 9.
           :           Enter the tmux command prompt.
           ;           Move to the previously active pane.
           =           Choose which buffer to paste interactively from a list.
           ?           List all key bindings.
           D           Choose a client to detach.
           [           Enter copy mode to copy text or view the history.
           ]           Paste the most recently copied buffer of text.
           c           Create a new window.
           d           Detach the current client.
           f           Prompt to search for text in open windows.
           i           Display some information about the current window.
           l           Move to the previously selected window.
           n           Change to the next window.
           o           Select the next pane in the current window.
           p           Change to the previous window.
           q           Briefly display pane indexes.
           r           Force redraw of the attached client.
           s           Select a new session for the attached client interactively.
           L           Switch the attached client back to the last session.
           t           Show the time.
           w           Choose the current window interactively.
           x           Kill the current pane.
           {           Swap the current pane with the previous pane.
           }           Swap the current pane with the next pane.
           ~           Show previous messages from tmux, if any.
           Page Up     Enter copy mode and scroll one page up.
           Up, Down
           Left, Right
                       Change to the pane above, below, to the left, or to the right of the current pane.
           M-1 to M-5  Arrange panes in one of the five preset layouts: even-horizontal, even-vertical, main-horizontal, main-ver‐
                       tical, or tiled.
           M-n         Move to the next window with a bell or activity marker.
           M-o         Rotate the panes in the current window backwards.
           M-p         Move to the previous window with a bell or activity marker.
           C-Up, C-Down
           C-Left, C-Right
                       Resize the current pane in steps of one cell.
           M-Up, M-Down
           M-Left, M-Right
                       Resize the current pane in steps of five cells.

     Key bindings may be changed with the bind-key and unbind-key commands.

Tuesday, May 29, 2012

How to add arguments to links in gnome-shell menu




就算在自己的 notebook 上用 chrome


我還是喜歡 default 打開 --incognito  (無痕) 模式


因為之前習慣用 cario dock 直接改 google-chrome 按鈕設定的 exec 真正的指令就好


現在換上 12.04 時為了節省麻煩,我想辦法讓自己改掉依賴 cario dock 的習慣


直接使用  gnome-shell 的 application menu 就好


不過悲劇出現了XD


替 gnome-shell menu 的 applications 加參數要自己 hack


google 到這篇 stackoverflow


How to add arguments to links in gnome-shell menu


sudo vim /usr/share/applications/google-chrome.desktop

找到這行

Exec=/opt/google/chrome/google-chrome %U

加上 incognito 參數

Exec=/opt/google/chrome/google-chrome %U --incognito

:wq


done!

#########################################################

後來發現寫在 /usr/share/applications 裏面似乎會因為更新而跑掉

cp 一份到 ~/.local/share/applications 比較保險(?)




Saturday, May 19, 2012

Alice in UNIX Land



原文出處 http://www.pma.caltech.edu/Publications/alice.in.unix.land.html


Alice in UNIX Land

Alice was reading the message on her monitor and beginning to suspect that everything was not as it should be. "Program too big to fit in memory," it read.
"Curiouser and curiouser," she said, "All I did was load fourteen TSRs before starting my word processor. With four megabytes, I wish I could use more than 640K."
"At that moment, a small white consultant ( a very white consultant) ran across the room. "Oh my coat and necktie," he said, "I'm going to be late for my appointment. And at one fifty an hour, too." Before Alice could say anything, he leaped into her monitor and disappeared behind her operating system.
Alice thought that she had never seen anyone leap into a monitor before; and certainly not go clean through the operating system. But then, she had been told that DOS was very shallow. Without hesitating a moment, she leaped in after him.
She found herself in a shiny corridor. Not knowing what else to do, she began walking. Turning a corner, she found herself facing two fat little men, each with an arm round the other's neck. One had "POS" embroidered on his collar, and the "NEG".
"I know," said Alice, "you two are a transistor."
"Yes," said Positive.
"Can you help me? asked Alice.
"No," said Negative.
"I'm looking for a white consultant." Alice pointed in the direction she had been walking. "Did he go this way?" she asked.
"No," said Negative.
She pointed the other way.
"Yes," said Positive.
Soon Alice came upon a large brown table. The Consultant was there, as was an apparently Mad Hacker, and several creatures that Alice did not recognize. In one corner sat a Dormouse fast asleep. Over the table was a large sign that read "UNIX Conference."
Everyone except the Dormouse was holding a paper cup, from which they were sampling what appeared to be custard. "Wrong flavor," they all declared as they passed the cup the cup to the creature on their right and graciously took the one being offered on their left. Alice watched them repeat this ritual three or four times before she approached and sat down.
Immediately, a large toad leaped into her lap and looked at her as if it wanted to be loved. "Grep," it exclaimed.
"Don't mind him," explained the Mad Hacker. "He's just looking for some string."
"Nroff?" asked the Frog.
The Mad Hacker handed Alice a cup of custard-like substance and a spoon. "Here," he said, "what do you think of this?"
"It looks lovely," said Alice, "very sweet." She tried a spoonful. "Yuck!" she cried. "It's awful. What is it?"
"Oh just another graphic interface for UNIX," answered the Hacker.
Alice pointed to the sleeping Dormouse. "Who's he?" she asked.
"That's OS Too," explained the Hacker. "We've pretty much given up on waking him.
Just then, a large, Blue Elephant sitting next to the Dormouse stood up. "Ladies and gentlemen," he trumpeted pompously, "as the largest creature here, I feel impelled to state that we must take an Open Look at..."
A young Job Sparrow on the other side of the table stood up angrily. The Elephant noticed and changed his speech accordingly. "...what our NextStep will be.
"Half the creatures bowed in respect while the other half snickered quietly to themselves. Just then, OS Too fell over in his sleep, crashing into the Elephant and taking him down with him. No one seemed a bit surprised.
"What we need," declared a Sun Bear as he lapped up custard with his long tongue," is a flavor that goes down like the Macintosh.
"Suddenly, the White Consultant began jumping up and down as his face got red. "No, no, no! he screamed. "No one pays one fifty an hour to Macintosh consultants!"
"Awk," said the Frog.
"Users," explained the Sun Bear, "want an easy interface that they will not have to learn."
"Users?" cried the Consultant in disbelief. "Users?! You mean secretaries, accountants, architects. Manual laborers!"
"Well," responded the Sun Bear, "we've got to do something to make them want to switch to UNIX."
"Do you think," said a Woodpecker who had been busy making a hole in the table, "that there might be a problem with the name `UNIX?' I mean, it does sort of suggest being less than a man."
"Maybe we should try another name, " suggested the Job Sparrow, "like Brut, or Rambo."
"Penix," suggested a Penguin.
"Mount," said the Frog, "spawn."
Alice slapped him. "Nice?" he asked.
"But then again," suggested the Woodpecker, "what about the shrinkwrap issue?"
Suddenly, everyone leaped up and started dashing about, waving their hands in the air and screaming. Just as suddenly, they all sat down again.
"Now that that's settled," said the Woodpecker, "let's go back to tasting flavors."
Everyone at the table sampled a new cup of custard. "Wrong flavor," they all declared as they passed the cup to the creature on their right and took the one being offered on their left.
Totally confused, Alice got up and left. After she had been walking away, she heard a familiar voice behind her.
"Rem," is said, "edlin."
Alice turned and saw the Frog. She smiled. "Those are queer sounding words," she said, "but at least I know what they mean."
"Chkdsk," said the Frog.


By Lincoln Spector TEXAS COMPUTER CURRENTS SEPTEMBER 1989

Monday, May 14, 2012

Larry Wall's Quotes

from brainyquote.com


Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi.
Larry Wall


For me, writing is a love-hate relationship.
Larry Wall


Hubris itself will not let you be an artist.
Larry Wall


I am not a sort of person who wants to run a company.
Larry Wall


I still drive my 1977 Honda Accord. The paint is almost all worn off. It's still running.
Larry Wall


I take time to watch anime. I don't know whether I'm allowed to, but I do it anyway.
Larry Wall



I talked about becoming stupid, but I've always been stupid. Fortunately I've been just smart enough to realize that I'm stupid.
Larry Wall


I think computer science, by and large, is still stuck in the Modern age.
Larry Wall


I think operating systems work best if they're free and open. Particular applications are more likely to be proprietary.
Larry Wall


I think software patents are a bad idea. Many patents are given for trivial inventions.
Larry Wall


I think the way IBM has embraced the open source philosophy has been quite astonishing, but gratifying. I hope they'll do very well with it.
Larry Wall


I want people to use Perl. I want to be a positive ingredient of the world and make my American history. So, whatever it takes to give away my software and get it used, that's great.
Larry Wall



I'm just paid to do whatever I want to do. Some of the time it's development, and some of the time it's just goofing off.
Larry Wall


I'm never satisfied because I've been always interested in too many things and I always want to do everything at once.
Larry Wall


If any ideology is so serious that you can't have fun while you're doing it, it's probably too serious.
Larry Wall


If you're a large corporation, you can afford to pay the money to register patents, but if you're an individual like me, you can't.
Larry Wall


Many days I don't write any code at all, and some days I spend all day writing code.
Larry Wall


One of the very basic ideas of Post-Modernism is rejection of arbitrary power structures. Different people are sensitive to different kinds of power structures.
Larry Wall


Perl was designed to work more like a natural language. It's a little more complicated but there are more shortcuts, and once you learned the language, it's more expressive.
Larry Wall


Post-Modernism was a reaction against Modernism. It came quite early to music and literature, and a little later to architecture. And I think it's still coming to computer science.
Larry Wall

Programmers can be lazy.
Larry Wall


Real programmers can write assembly code in any language.
Larry Wall


Some of modern engineering is necessary to good art. But I think of myself is a cultural artist.
Larry Wall


Somebody out there is going to do something that's far more surprising than anything that I would do. I was surprised by the whole web thing in the first place.
Larry Wall


The Harvard Law states: Under controlled conditions of light, temperature, humidity, and nutrition, the organism will do as it damn well pleases.
Larry Wall


The problems that I really like to solve are our cultural problems.
Larry Wall



The three chief virtues of a programmer are: Laziness, Impatience and Hubris.
Larry Wall


The world has become a larger place. The universe has been expanding, and Perl's been expanding along with the universe.
Larry Wall


There is no schedule. We are all volunteers, so we get it done when we get it done. Perl 5 still works fine, and we plan to take the right amount of time on Perl 6.
Larry Wall


To be a good artist, you have to serve the work of art and allow it to be what it is supposed to be.
Larry Wall


We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise.
Larry Wall


We are so Post-Modern that we don't realize how Post-Modern we are anymore.
Larry Wall



When I announced the development of Perl 6, I said it was going to be a community design. I designed Perl, myself. It's limited by my own brain power. So I wanted Perl 6 to be a community design.
Larry Wall


Younger hackers are hard to classify. They're probably just as diverse as the old hackers are. We're all over the map.
Larry Wall

Larry Wall's video


來聽聽神的訪問
















Thursday, May 10, 2012

vim split



寫 CPP 常常會把把檔案分成  main.cpp / foo.cpp / foo.h  的模式

用 vim 的 split 功能做到非常方便的同時編輯功能 ( awesome wm 控表示:






首先,打開 main.cpp

    vim main.cpp 

然後我要同時看一下 foo.h 標頭檔的內容

    :vs[plit] foo.h             # vsplit 水平分割 

此時,vim 會在左方打開 foo.h 的內容

    :sp[lit] foo.cpp            # split 垂直分割 

vim 會在 foo.h 的上方打開 foo.cpp 的內容

移動游標的方法是 ^w + [jkhl]        # 跟 vim 裏面的游標上下左右一樣
                   下上左右

    ^wp (往返)或是 ^ww (循環)可以來回切換視窗

    ^wr 或是 ^wR 可以把左右(或上下) 視窗對調



    開啟空 split window
    :new (^wn)
    :vnew



    快速移動游標

    ^wt (or ^w^t 也可)    # Move cursor to top-left window.                                 
                                                                                
    ^wb (or ^w^b)        # Move cursor to bottom-right window.


    ^w[JKHL]             # Move the current window to be at the very bottom/top/left/right window





    調整 split 切出來的視窗大小


    ^w>   ^w<     # 邊界往右往左移 
    ^w+   ^w-     # 邊界上下移動  
    ^w_   ^w|     # 放大視窗至底部/最右邊 
    ^w=           # 復原到原本的一半大小 


  也可以用 resize 來完成


    :res[ize] +/-N)
    :vertical res[ize] [N]


  or
    :set mouse=a  # 用滑鼠調整




    在某個特定 window 執行 command 的方法
    :abo[veleft] {cmd}
    :bel[owright] {cmd}
    :to[pleft] {cmd}
    :bo[tright] {cmd}




Ref:

  :help windows.txt

    https://www.linux.com/learn/tutorials/442415-vim-tips-using-viewports

    http://www.openfoundry.org/tw/tech-column/2383-vim--buffers-and-windows

Wednesday, May 9, 2012

Perldoc in Vim

昨天上 NA 時用 vim 寫筆記

寫到一半不小心按到 CapsLock 鍵,然後我按下 k 時竟然彈出了神奇的 man !!!

:help K 看一下,竟然有有趣的東西XDD

K                       Run a program to lookup the keyword under the           
                        cursor.  The name of the program is given with the      
                        'keywordprg' (kp) option (default is "man").  The       
                        keyword is formed of letters, numbers and the           
                        characters in 'iskeyword'.  The keyword under or        
                        right of the cursor is used.  The same can be done      
                        with the command >                                      
                                :!{program} {keyword}                           
<                       There is an example of a program to use in the tools    
                        directory of Vim.  It is called 'ref' and does a        
                        simple spelling check.                                  
                        Special cases:                                          
                        - If 'keywordprg' is empty, the ":help" command is      
                          used.  It's a good idea to include more characters    
                          in 'iskeyword' then, to be able to find more help.    
                        - When 'keywordprg' is equal to "man", a count before   
                          "K" is inserted after the "man" command and before    
                          the keyword.  For example, using "2K" while the       
                          cursor is on "mkdir", results in: >                   
                                !man 2 mkdir                                    
<                       - When 'keywordprg' is equal to "man -s", a count       
                          before "K" is inserted after the "-s".  If there is   
                          no count, the "-s" is removed.                        
                        {not in Vi}


K 會對著現在游標的 word 去找 man ,這個功能寫 Shell script  應該很好用XDD

然後這個功能給我了一個啟發,喜歡寫 Perl 的我,何不把這功能跟 perldoc 結合起來呢?

於是我在我的 vimrc 底下寫了這個

au FileType perl nmap K :!perldoc -f <cword><CR>


用 autocmd 來幫我完成從 perldoc 找到現在的 cword 去匹配裏面的說明

原本很開心的以為這是我自己原創的 hack

後來 google 了一下  perlmonks.org  上早就有人問過了XD

perlbuzz.com 的文章跟我幾乎一模一樣 XDDD

他還去找了非內建函式的 perldoc

於是我把我的版本修改成這樣 (多一個 <CR> 讓離開 less 時不用多按一下 Enter)

au FileType perl nmap K :!perldoc <cword> <bar><bar> perldoc -f <cword><CR><CR>


不過其實很多 vim plugins 就已經有類似的功能了

http://vim.sourceforge.net/scripts/script.php?script_id=1913
http://vim.sourceforge.net/scripts/script.php?script_id=1217
http://www.vim.org/scripts/script.php?script_id=209

Monday, May 7, 2012

workstation beginer's guide



本文轉自我 BS2 個板,把圖片和 link 換一換XD


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



本篇文章為板主半夜睡不著覺夢遊不小心打出來的文章

不保證其正確性,但很開心能與大家分享 

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

前言:大一同學應該都能漸漸體會到,愈來愈多 老師/助教 會要求同學要在系上工作站

環境上完成作業,有鑑於大多同學對工作站 Unix-like system 很陌生,而我個人對各個

助教在解釋工作站時覺得有些小細節會有小遺漏,無法帶給同學比較完整、宏觀的教學

於是乎我來夢遊一篇教學 XD


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

Reference.

    由於我的能力以及本教學涵蓋範圍有限,希望同學有空時可以參考以下資源

    《UNIX PowerTools, 3nd Edition

    《Bash Guide for Beginners》 [PDF, 2e ]

    《Learning the bash Shell, 3rd Edition

    《Classic Shell Scripting

    《Essential System Administration, 3rd Edition

    《交大資工系 SA/NA 課程》 sysadm2011  netadm2012

    《FreeBSD Handbook

    《工三的系計中專業的助教ㄉㄉ們

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

大綱

    主要提這三個面向的簡單概覽 (意思就是你別想從這份教學中學到太多 :P )

        about UNIX workstation 

        shell command 

        the vim editor











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

Ch 1.  Unix 

    1.1 history 

    1.2 difference between Unix-like systems 

    1.3 why Unix 













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

    1.1 history 

        UNIX 是米國 AT&T 公司在 1969 年於 Bell lab 發展出來的分時多人多工

        並具有強大可攜性的作業系統


        最早的 UNIX 是由兩位大師 Kenneth Thompson 和 Dennis M. Ritchie

        共同開發的,一開始是用組合語言邊寫,後來 DMR 發明並改用 C 來重

        寫 UNIX 整個系統,此為現代 Unix-like OS 的濫觴

        更多小故事可以參考 DMR 大師發表的這篇論文

        《The Evolution of the Unix Time-sharing System》 




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

    1.2 difference between Unix-like systems

        UNIX 系統後來因為一些商業問題而有了爭議,UC Berkeley 從 UNIX 為基礎

        發展出  Berkeley Software Distribution (BSD) 


        BSD 系統的成功後來又發展了 FreeBSD、NetBSD、OpenBSD、Darwin 等
                                                            (Mac OS X的祖先)


        BSD 後來又因為一些疑似手滑別人家的 code 而遭到了質疑,部份砍掉重練(?)

        後跟乖乖一樣重新改版換包裝,各位觀眾!全新的 FreeBSD 4.4-Lite!


        目前 FreeBSD 最新 stable 版本為 9.0 和 8.3

        系上 BSD 工作站使用的是  FreeBSD 8.2-RELEASE-p3

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

        Linux 是另一個受人喜愛的作業系統 ,由 Geek 之王,Linus Torvalds 開發

         

# Mr, Linux, King of Geeks, Dad of 3 



        Linus 大學修 OS 時,玩了一個叫作 MINIX 的 UNIX 教學版本,因為它是教育

        軟體,不准在上面玩其他有趣的事情,所以 Linus 就決定刻了一個自己的 OS

        Kernel,並且丟到了 FTP 上面引起各大牛人們圍觀,大家東改西改,加上了很

        多有用的 tools 和 patch ,Linus 決定,將新的作業系統以 GPL 授權發行 



        知名的 Linux distributions 很多, Ubuntu, Debian, Fedora, OpenSuSE ...

        Linux 是好用的 server 和 desktop 系統,大家可以嘗試看看(私心)

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

        團子  UNIX 大家族



            各個 UNIX-like 很多,可以參考幾張經每個 UNIX 家族樹


# from wiki 

               


Linux 家族樹
# 光是 Linux 出來的分支就有這麼多 

             





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

    1.3 why UNIX 

            為什麼我們要用 Unix 呢?老實說,這是信仰問題XD 各位可以去翻翻

            《The UNIX- HATERS Handbook》 - Simson Garfinkel 
           

            這本還有 DMR 大師為其寫序的大作,Unix sucks :P



            此外,可以比較知名 hacker esr (Eric Steven Raymond) 的大作

            《The Art of Unix Programming》 
           


            兩本相較之後,你就會明白,why Unix 這個問題


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

 
    Some Unix Philosophy                

        UNIX is not just an operating system, but a way of life.

        Unix Is Fun to Hack

        Write programs that do one thing and do it well.
        Write programs to work together.
        Write programs to handle text streams, because that is a universal
                                                                interface.
        Small is beautiful.
        Make each program do one thing well.
        Build a prototype as soon as possible.
        Choose portability over efficiency.
        Store data in flat text files.
        Use software leverage to your advantage.
        Use shell scripts to increase leverage and portability.
        Avoid captive user interfaces.
        Make every program a filter.

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

Ch 2.  Shell commands 

    2.1 what's shell 

    2.2 powerful shells 

    2.3 basic shell commands (and builtins) 

    2.4 more useful commands 











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

    2.1 what's shell 

        shell 是一層讓 user 和 system kernel 溝通的那層"殼"

        Command-line shells 替 OS 提供一層 command-line interface (CLI)



        也許很多人會很不習慣用指令的方式來操控電腦,大家已經習慣滑鼠點點點

        的用法,但是,身為資工系學生,能夠在麻瓜面前啪啪啪打指令是基本的XD

        熟悉了 shell 的操控方式,很多時候工作會比圖形介面下來的簡單且輕鬆很多


        並且,shell 的一步步是可以重現的(寫成 script) 讓重複的工作可以輕鬆重用

        # vgod 大神的 Sikuli 基本上就是想做到 GUI 的 scriptting XD 


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

    2.2 powerful shells 

        各家工作站上面提供的 shell 各有所不同

        常見的 shell 有  bash, tcsh, zsh, Bourne shell (sh) 


        bash (Bourne-Again shell) 是 Linux 上的標準 shell

        tcsh 是 BSD 上常見的 shell

        zsh (The last shell you'll ever need!) 地表上最強的 shell

        Bourne shell 最原始的 shell ,是各家 shell 的祖先



        各個 shell 基本上都完整支援 Bourne shell ,大同小異卻但各有各的超能力


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

    2.3 basic shell commands (and builtins) 

        builtins shell commands 是 shell 為你提供的最基本的內建功能

        我們可以透過 man builtins 指令 (man for manual) 來看到各個指令提供的

        功能。

        man 是最強大也是你必須要會的指令

            man — format and display the on-line manual pages 

            在工作站上有任何問題就是問男人,他會告訴你一切有關這個指令的魔法

            man man 

                男人阿!請告訴我 man 指令的用法吧!

        註:每個 shell 提供的 builtins 略有不同

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

    cd (change directory)

        cd 用來改變目前所在資料夾位置

            cd dir   # change to dir 

            cd       # go home ( cd 後面什麼都沒接) 

            cd ..    # 跑到上一層 

            cd -     # 時空跳轉,回到剛剛到過的資料夾 

    pwd (print working directory)

        pwd 用來知道我現在人在那邊

    echo (毫無反應,只是個 echo)

        echo Hello world!    # 印出 Hello world! 

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

    bg (background)

        bg 用來把工作 (process) 丟到背景執行



    fg (foreground)

        fg 把丟到背景的 process 拿回來



    kill (kill a process)

        kill 送出特定 Signal 給指定的 pid

            kill -9 5566 # 送 9 號 signal (去死吧!) 給 pid 為 5566 的 process 



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

    logout (logout)

        從你目前的 shell 登出

        a geeky way : press Ctrl-D 

            按下 Ctrl-D 會送一個 EOF 給你的 shell 代表告訴 shell 我要登出









    簡單的 builtins 到這邊,接下來是一些常用指令教學 :D



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

    ls ( list directory contents )

        ls           # 列出目前這裡有什麼 

        ls -a        # list all 

        ls -l        # list in long format 


    mkdir (make directories)

         mkdir dir   # make the directory 'dir' 

    rm (remove directory entries)

        rm -r dir    # recursively remove everything in dir 

        rm -f file   # force remove it 

        rm -rf /     # make your computer faster !!!! 
==============================================================================

    cp (copy files)

        cp file1 file2  # copy file1 to file2 

        cp -r dir       # recursively copy everything in dir 

    mv (move files)

        mv file1 ../    # move file1 to the father directory 

        mv file1 file2  # rename the file 

        mv file{1,2}    # do the same thing 

    cat (concatenate files and print on the standard output)

        cat file1       # print file1 out 

    tac (reverse cat)

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

    more (a simple pager for viewing a file)

        more file1     # let's see what's in file1 

    less (less is more than more)

        less file1     # similar to 'more file1' 


    both more and less are based on vi-style command keys 


    head (output the first part of files, default 10 lines)

        head file1     # print first 10 lines of file11 

    tail (output the last part of files, default 10 lines)

        tail file1     # print last 10 lines of file1 

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

        2.4 more useful commands 

            這部份要提的是資工系學生必會的幾個好用指令

            screen          # 一個 ssh 連線,多個 user session 

            irssi           # a IRC client for UNIX 

            gcc             # GNU's compiler collection 











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

    screen  (screen manager with VT100/ANSI terminal emulation)

        當你今天要在工作站同時做很多事情時,我們不必開多個 ssh 連線過去 

        screen 可以幫我們在本機端模擬出 login sessoin 讓我們能同時使用很多個

        shell 分別做不同的工作


        screen 最強大的功能是可以把現在的 screen detach 起來,下次從別處 ssh

        到工作站時可以把 screen 拿回來,繼續剛剛為完成的工作


        這個功能在編譯或是跑大型程式時很好用,掛 BBS 和 IRC 也很方便

        screen 功能強大,請參考 #177VUE1 #17DP0JL [P_xatier @bs2.to] 兩篇文章



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

    irssi (a modular IRC client for UNIX)

        Internet Relay Chat (IRC) 是網路上真正高手雲集之處

        如果你想多認識世界各地的大神們,上 IRC 找準沒錯!


        irssi 是 UNIX 機器上的 IRC client

        irssi IRC 的操作方法繁多無法一一列舉,請參考這兩篇優質教學

Lzy's 用 screen + irssi 上 irc 之鄉民版教學 (含Q&A)

erepublik IRC的推廣文!   (這篇漫畫超好笑XD)


    系上在 Freenode 上面也有 IRC channel,/j #nctuNASA ILoveCSCC  # 後面是密碼
                                          /j #nctucsie     # 這邊都沒人 
                                          /j #nctucs       # 系計中ㄉㄉ專用

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

    gcc / g++   (GNU project C and C++ compiler)

        在工作站上面寫 C code 常常會用到的標準 complier

            gcc test.c           # default complie to 'a.out' 

            gcc test.c -o test   # set the output file named 'test' 

            gcc -c test.c        # only compile (output .o files) 


        常見的 gcc flags

        -std=c99    -std=c++0x     -ansi     # using different standard 

        -Wall -Wextra -pedantic              # warning options 

        -O2 -O3 -Os -Ofast                   # optimization options 

        -lm                                  # link to the math lib 
==============================================================================

    screen, irssi, gcc 的功能強大到遠遠不只你想像的那樣,這邊給出幾個 ref 參考


       GNU Screen manual

        Irssi documentation and tutorials

        GCC online documentation



        screen 和 irssi 教學很短,一下子就唸完了

        gcc 的 manual 超精美XD 當作床邊故事來看吧 :P






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

Ch 3.  the vim editor

    3.1 vi, vim, and emacs 

    3.2 vim starters 

    3.3 master 













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

    3.1  vi, vim, and emacs 

        遠在古老 UNIX 時代,各個巫師都喜歡自己刻一個自己順手的 editor ,有個叫

        Bill Joy 的 hacker 發展了自己的 editor: vi 


        vi 的使用就像開車一樣,切換排檔的概念,不同 mode 底下能完成不同的事 

        常見的有 command mode 和 insert mode,分別能輸入指令和直接輸入文字


        vi 已成為 UNIX 底下比備的標準編輯器,幾乎所有的 UNIX 都可以找到 vi

        或是其衍生產品

        MJ12Net : The vi editor

       

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

    vim, Vi IMproved 是 Bram Moolenaar 所開發的,當年他買了一台機器,可惜上面

    沒有他愛用的 vi ,於是,他就自己在這台機器上面把 vi 給刻了出來(抖) 


    vim 承襲了 vi 的特性,並加入了許多強大的功能,並具有 vim script 的高度拓

    展性,使得 vim 在 UNIX 界受到眾多 hackers 的喜愛


    vim script 讓大家可以自由的替 vim 開發 plugins ,完成更強大的功能

    更多請參考 vim.org



    功能強大的代表就是 vim 不是很好學的,請參考 編輯器學習曲線圖比較XD

   

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

    emacs 則是是作業系統(誤)     為    [Escape Meta Alt Control Shift] 的縮寫

        在 UMIX 瀏覽器大戰中,vim 和 emacs 是敵對的文化,分別有兩派人馬支持著

        emacs 是由 GNU 創辦人, 糟老頭 RMS (Richard M. Stallman) 在 MIT 開發的


        emacs 最為人所知的是他的強大巨集拓展,以 Lisp 語言為基礎,emacs 提供了

        強大的工作環境,你能在上面做任何你想做的事,包括泡咖啡和上噗浪(?)
        http://en.wikipedia.org/wiki/Emacs#Extensibility

        emacs 特性是依賴組合鍵,平常可以任意輸入文字,加上特殊按鍵組合可以打開

        各種神奇功能 (PS. Emacs 的快捷鍵會引發腕管綜合症(誤)) 

        有這麼一句話『emacs 是強大的作業系統,只是上面缺乏了一個好的編輯器』 

        關於編輯器之神(vim) 和神的編輯器(emacs) 的戰爭,請參考
                                      wiki: Editor war
==============================================================================

    3.2 vim starters

        剛剛提到, vim 要上手非常不容易,我也不打算在這裡介紹 vim 的使用(毆)

        提供以下資源,看完的(並實際動手練習)可以學會簡單的 vim 操作 (依序閱讀)

            yannesposito: Learn Vim Progressively

            vgod: 淺談模式”mode”與文字編輯的技術與學習

           鳥哥的 Linux 私房菜: vim 程式編輯器

            大家來學VIM(一個歷久彌新的編輯器)

        cheat sheets (懶的看前面落落長文章的話)

            vgod: 給程式設計師的Vim入門圖解說明
            bullium.com : Vim Commands Cheat Sheet
            VIM QUICK REFERENCE CARD
            http://jrmiii.com/attachments/Vim.pdf 
==============================================================================

    3.3 master

        對於有時間的人,可以去翻翻去看官方的精美 vim 教學

            vim book

            vimcdoc

            Vim Tips Wiki 



        對於沒時間的人,可以玩玩看 vim 的簡單教學 (強烈建議去玩看看!!)

            在工作站上打 vimtutor 指令,花個 20 分鐘,親身體驗 vim 的有趣世界



        學習 vim 是一趟無法回頭的旅程(?) 一旦陷進去可能就會愛上這個 editor XD

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


    本夢遊教學到這邊結束

        希望這份教學對同學們有幫助 :D

            所有不懂的東西歡迎來問我

                無論是站內信或是直接找我都可以



    最後,送你們一張很棒的 cheat sheet

       



        感謝您花時間閱讀 :D


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


--


沒有人會為弱者流眼淚



--
▄▄▄▄   ▄▄  ▄▄▄   . .    .‘‘ .
  ▇▄█   █    ▄▄█  .  ‘ .        .          telnet://bs2.to
▄█▄█ ▄█    █▄▄  。   .‘ .


Saturday, May 5, 2012

tcpdump in Perl


半夜睡不著不知道要幹嘛...

爬起來摸 CPAN 上一些簡單的 packet sniffer in Perl 的 module

玩著玩著就寫(ㄔㄠ)出一個了

基本上還是用 pcap(3) (Packet Capture library)

不過 Perl 有 NetPacket module 把他抽象化了

http://search.cpan.org/search?query=NetPacket

概念上很簡單,就一層一層把 header 拆掉 (encapsulation ?)

把 link layer => IP layer => transport layer 依序拆開

可能有念過 networking 會比較有概念 :P

最後用 Data::HexDumper 把 binary 拆成 hex 跟 ascii 比較好閱讀

http://search.cpan.org/~dcantrell/Data-Hexdumper-3.00/lib/Data/Hexdumper.pm



#!/usr/bin/perl                                                                 
                                                                                
use 5.012;                                                                      
                                                                                
use Net::PcapUtils;                                                             
use NetPacket::Ethernet qw(:strip);                                             
use NetPacket::IP qw(IP_PROTO_TCP);                                             
use NetPacket::TCP;                                                             
use Data::HexDump;                                                              
                                                                                
                                                                                
sub process_pkt {                                                               
    my ($user_data,$header, $packet) = @_;                                      
    # decode the Ethernet and IP headers                                        
    my $ip = NetPacket::IP->decode(eth_strip($packet));                         
                                                                                
    if ($ip->{proto} == IP_PROTO_TCP) {                                         
        # decode TCP headers                                                    
        my $tcp = NetPacket::TCP->decode($ip);                                  
        # now we get TCP packet XD                                              
        say "\n$ip->{src_ip}($tcp->{src_port}) -> $ip->{dest_ip}($tcp->{dest_port})";
        say HexDump $ip->{data};                                                
    }                                                                           
}                                                                               
                                                                                
my $filter = join(" ", @ARGV);                                                  
say $filter;                                                                    
Net::PcapUtils::loop(\&process_pkt, SNAPLEN=> 65536, FILTER => $filter);




Usage


    sudo ./pcap.pl


    sudo ./pcap.pl host 140.113   # 支援簡單的 filter

Friday, May 4, 2012

Jail in FreeBSD

Jail 是 FreeBSD 上面提供 OS level virtualization 的工具

他提供了比 chroot 還要更強大的功能

可以把一台 FreeBSD 裝在裏面

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

建一台 jail 很簡單只要幾個步驟

http://www.freebsd.org/doc/handbook/jails-build.html


# setenv D /usr/jail/jailname
# mkdir -p $D 
# cd /usr/src
# make buildworld                  # 要很久,請用 screen 掛著
# umount -f /tmp                   # 這邊因為 tmp 是不能 exec 的,所以要先 unmount 掉
# make installworld DESTDIR=$D 
# make distribution DESTDIR=$D 
# mount -t devfs devfs $D/dev

改 rc.conf
#vim /etc/rc.conf



jail_enable="YES"
jail_list="jailname"
jail_jailname_rootdir="/usr/jail/jailname"
jail_jailname_hostname=".xxxxxxxxxxxxxxxxxxxxxxxxx"
jail_jailname_ip="10.0.0.14"
jail_jailname_devfs_enable="YES"
jail_jailname_devfs_ruleset="devfsrules_jail"


把 ports 系統搬過去
# cp -r /usr/ports /usr/jail/jailname/usr/ports

開機

# /etc/rc.d/jail start jailname

關機
# /etc/rc.d/jail stop jailname

現在有幾個 jail

#jls



   JID  IP Address      Hostname    Path
     3  10.0.0.14       **********  /usr/jail/jailname




#jexec N /bin/tcsh    # N 是第幾個 jail ID

先裝好 portmaster 和基本 tools

記得 jail 的網卡要在外面 rc.conf 裏面設 alias 像這樣

ifconfig_em1_alias0="inet 10.0.0.14 netmask 255.255.255.0"

jail 裏面的 /etc/resolv.conf 也要一下,不然 DNS 找不到


search example.org
nameserver 140.113.1.1



要 ping 測試的話要在外面改 sysctl
# sysctl security.jail.allow_raw_sockets=1

在 jail 裏面要出來的話就 Ctrl - D 就好了