前幾天發了重定向以及管道相關使用方法,今天這里發些很有趣的例子。通過重定向實現基于tcp/udp協議的軟件通訊。
linux 設備里面有個比較特殊的文件:
/dev/[tcp|upd]/host/port 只要讀取或者寫入這個文件,相當于系統會嘗試連接:host 這臺機器,對應port端口。如果主機以及端口存在,就建立一個socket 連接。將在,/proc/self/fd目錄下面,有對應的文件出現。
一、測試下:/dev/tcp/host/post文件
[chengmo@centos5 shell]$ cat</dev/tcp/127.0.0.1/22SSH-2.0-OpenSSH_5.1#我的機器shell端口是:22#實際:/dev/tcp根本沒有這個目錄,這是屬于特殊設備[chengmo@centos5 shell]$ cat</dev/tcp/127.0.0.1/223-bash: connect: 拒絕連接-bash: /dev/tcp/127.0.0.1/223: 拒絕連接#223接口不存在,打開失敗 [chengmo@centos5 shell]$ exec 8<>/dev/tcp/127.0.0.1/22[chengmo@centos5 shell]$ ls -l /proc/self/fd/總計 0lrwx------ 1 chengmo chengmo 64 10-21 23:05 0 -> /dev/pts/0lrwx------ 1 chengmo chengmo 64 10-21 23:05 1 -> /dev/pts/0lrwx------ 1 chengmo chengmo 64 10-21 23:05 2 -> /dev/pts/0lr-x------ 1 chengmo chengmo 64 10-21 23:05 3 -> /proc/22185/fdlrwx------ 1 chengmo chengmo 64 10-21 23:05 8 -> socket:[15067661] #文件描述符8,已經打開一個socket通訊通道,這個是一個可以讀寫socket通道,因為用:"<>"打開[chengmo@centos5 shell]$ exec 8>&-#關閉通道[chengmo@centos5 shell]$ ls -l /proc/self/fd/總計 0lrwx------ 1 chengmo chengmo 64 10-21 23:08 0 -> /dev/pts/0lrwx------ 1 chengmo chengmo 64 10-21 23:08 1 -> /dev/pts/0lrwx------ 1 chengmo chengmo 64 10-21 23:08 2 -> /dev/pts/0lr-x------ 1 chengmo chengmo 64 10-21 23:08 3 -> /proc/22234/fd
從時間服務器讀取時間:
[chengmo@centos5 html]$ cat</dev/tcp/time-b.nist.gov/13
55491 10-10-22 11:33:49 17 0 0 596.3 UTC(NIST) *
上面這條語句使用重定向輸入語句就可以了。
二、通過重定向讀取遠程web服務器頭信息
#!/bin/sh #testhttphead.sh#實現通過主機名,端口讀取web 服務器header信息#copyright chengmo,qq:8292669 if(($#<2));then echo "usage:$0 host port"; exit 1;fi#如果參數缺失,退出程序,返回狀態1 exec 6<>/dev/tcp/$1/$2 2>/dev/null;#打開host的port 可讀寫的socket連接,與文件描述符6連接 if(($?!=0));then echo "open $1 $2 error!"; exit 1;fi#如果打開失敗,$?返回不為0,終止程序 echo -e "HEAD / HTTP/1.1/n/n/n/n/n">&6; #將HEAD 信息,發送給socket連接 cat<&6; #從socket讀取返回信息,顯示為標準輸出 exec 6<&-;exec 6>&-; #關閉socket的輸入,輸出 exit 0;
腳本建立后:存為testhttphead.sh
新聞熱點
疑難解答