2011-05-30 120 views
7

想知道是否有人知道如何捕獲和識別到達終端的命令write。我試過使用script -f,然後使用tail -f來跟蹤while循環中的輸出,但由於我追蹤的終端沒有啓動write,所以它不會被輸出。不幸的是,我沒有root權限,不能和pts或screendump一起玩,想知道是否有人知道一種方法來實現這一點?響應「寫入」消息

例子:

Terminal 1 $ echo hello | write Terminal 2 

Terminal 2 $ 
Message from Terminal 1 on pts/0 at 23:48 ... 
hello 
EOF 

*Cause a trigger from which I can send a return message 

回答

3

我想不出任何明顯的方法來做到這一點。這裏的原因...

殼牌從接收其輸入,而其輸出發送到,一些終端設備 :

+-----------+ 
    |   | 
    | bash | 
    |   | 
    +-----------+ 
     ^| 
     | | 
     | v 
     +----------------------+ 
     | some terminal device | 
     +----------------------+ 

write寫到終端,它發送的數據直接到同一個終端設備。它不會去任何地方你的shell附近:

+-----------+  +-----------+ 
    |   |  |   | 
    | bash |  | write | 
    |   |  |   | 
    +-----------+  +-----------+ 
     ^|    | 
     | |    | 
     | v    v 
     +----------------------+ 
     | some terminal device | 
     +----------------------+ 

因此,爲了讓您能夠捕捉到什麼是write發送,你需要通過終端設備本身提供了一些鉤子,和我不沒想到有什麼可以用來做到這一點。

那麼script如何工作,爲什麼不捕獲write輸出?

script也無法掛入終端設備。它真的想在你的shell和你的終端之間進行自我介入,但是沒有一個好的方法可以直接做到這一點。

因此,它創建了一個新的終端設備(一個僞終端,也被稱爲「pty」)並在其中運行一個新的shell。一個pty包含兩個方面:「主」,它只是一個字節流,和一個「奴隸」,它看起來就像任何其他交互式終端設備。

新的外殼連接到從屬端,而script控制主端 - 這意味着它可以將字節流保存到文件中,並在新外殼和原始端子之間轉發它們:

+-----------+ 
    |   | 
    | bash | 
    |   | 
    +-----------+ 
     ^| 
     | | 
     | v 
+-----------------+ <=== slave side of pty -- presents the interface of 
| pseudo-terminal |        an interactive terminal 
+-----------------+ <=== master side of pty -- just a stream of bytes 
     ^|      
     | v  
    +-----------+ 
    |   | 
    | script | 
    |   | 
    +-----------+ 
     ^| 
     | | 
     | v 
     +----------------------+ 
     | some terminal device | 
     +----------------------+ 

現在你可以看到一個write到原來的終端設備繞過一切,就像它在上面的簡單的情況下所做的:

+-----------+ 
    |   | 
    | bash | 
    |   | 
    +-----------+ 
     ^| 
     | | 
     | v 
+-----------------+ <=== slave side of pty -- presents the interface of 
| pseudo-terminal |        an interactive terminal 
+-----------------+ <=== master side of pty -- just a stream of bytes 
     ^|      
     | v  
    +-----------+  +-----------+ 
    |   |  |   | 
    | script |  | write | 
    |   |  |   | 
    +-----------+  +-----------+ 
     ^|    | 
     | |    | 
     | v    v 
     +----------------------+ 
     | some terminal device | 
     +----------------------+ 

如果你將數據寫入到的從屬面新的終端在這裏,你的會看到輸出顯示出來,因爲它會出現在主控端的數據流中,即script看到的。您可以從script內的shell中找到命令的新pty的名稱。

不幸的是,這並不write幫助,因爲你可能會無法write它:您的登錄會話與原來的終端,而不是新的關聯,並write可能會抱怨你」沒有登錄。但是,如果你例如echo hello >/dev/pts/NNN,您會看到它確實顯示在script輸出中。

+0

感謝您長時間詳細的解釋,我沒有意識到'腳本'通過輔助僞終端工作,所以很有趣。我想我會嘗試投入一些時間來查看是否讓我的腳本檢測到新的pty,並將其用於原來的目的,儘管將不得不嘗試將'write'的功能複製到不關心ID的東西。 – 2011-06-01 06:14:17