linux shell 脚本实现tcp/upd协议通讯(重定向应用)

2019-09-23 09:24:10于丽

前几天发了重定向以及管道相关使用方法,今天这里发些很有趣的例子。通过重定向实现基于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/22
SSH-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/
总计 0
lrwx------ 1 chengmo chengmo 64 10-21 23:05 0 -> /dev/pts/0
lrwx------ 1 chengmo chengmo 64 10-21 23:05 1 -> /dev/pts/0
lrwx------ 1 chengmo chengmo 64 10-21 23:05 2 -> /dev/pts/0
lr-x------ 1 chengmo chengmo 64 10-21 23:05 3 -> /proc/22185/fd
lrwx------ 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/
总计 0
lrwx------ 1 chengmo chengmo 64 10-21 23:08 0 -> /dev/pts/0
lrwx------ 1 chengmo chengmo 64 10-21 23:08 1 -> /dev/pts/0
lrwx------ 1 chengmo chengmo 64 10-21 23:08 2 -> /dev/pts/0
lr-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.1nnnnn">&6; 
#将HEAD 信息,发送给socket连接
 
cat<&6; 
#从socket读取返回信息,显示为标准输出
 
exec 6<&-;
exec 6>&-; 
#关闭socket的输入,输出
 
exit 0;

脚本建立后:存为testhttphead.sh