Linux Shell 脚本实现tcp/upd协议通讯

发表于:2015-12-09 09:57

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:程默    来源:51Testing软件测试网采编

  前几天发了重定向以及管道相关使用方法,今天这里发些很有趣的例子。通过重定向实现基于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.1\n\n\n\n\n">&6;
#将HEAD 信息,发送给socket连接
cat<&6;
#从socket读取返回信息,显示为标准输出
exec 6<&-;
exec 6>&-;
#关闭socket的输入,输出
exit 0;
  脚本建立后:存为testhttphead.sh
  运行结果:
  [chengmo@centos5 ~/shell]$ sh testhttphead.sh www.baidu.com 80
  HTTP/1.1 200 OK
  Date: Thu, 21 Oct 2010 15:17:23 GMT
  Server: BWS/1.0
  Content-Length: 6218
  Content-Type: text/html;charset=gb2312
  Cache-Control: private
  Expires: Thu, 21 Oct 2010 15:17:23 GMT
  Set-Cookie: BAIDUID=1C40B2F8C676180FD887379A6E286DC1:FG=1; expires=Thu, 21-Oct-40 15:17:23 GMT; path=/; domain=.baidu.com
  P3P: CP=" OTI DSP COR IVA OUR IND COM "
  Connection: Keep-Alive
  [chengmo@centos5 ~/shell]$ sh testhttphead.sh 127.0.0.1 8080
  open 127.0.0.1 8080 error!
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号