用python模拟TCP3次握手连接及发送数据

源码如下:

 1 from scapy.all import *
 2 
 3 
 4 import logging
 5 logging.getLogger('scapy.runtime').setLevel(logging.ERROR)
 6 
 7 target_ip       = '192.168.1.1'
 8 target_port     = 80
 9 data            = 'GET / HTTP/1.0 \r\n\r\n'
10 
11 def start_tcp(target_ip,target_port):
12     global sport,s_seq,d_seq    #主要是用于TCP3此握手建立连接后继续发送数据
13     try:
14         #第一次握手,发送SYN包
15         ans = sr1(IP(dst=target_ip)/TCP(dport=target_port,sport=RandShort(),seq=RandInt(),flags='S'),verbose=False)
16         sport = ans[TCP].dport   #源随机端口
17         s_seq = ans[TCP].ack     #源序列号(其实初始值已经被服务端加1)
18         d_seq = ans[TCP].seq + 1 #确认号,需要把服务端的序列号加1
19         #第三次握手,发送ACK确认包
20         send(IP(dst=target_ip)/TCP(dport=target_port,sport=sport,ack=d_seq,seq=s_seq,flags='A'),verbose=False)
21     except Exception,e:
22         print '[-]有错误,请注意检查!'
23         print e
24 
25 def trans_data(target_ip,target_port,data):
26     #先建立TCP连接
27     start_tcp(target_ip=target_ip,target_port=target_port)
28     #print sport,s_seq,d_seq
29     #发起GET请求
30     ans = sr1(IP(dst=target_ip)/TCP(dport=target_port,sport=sport,seq=s_seq,ack=d_seq,flags=24)/data,verbose=False)
31     #ans.show()
32     #读取服务端发来的数据
33     rcv = ans[Raw]
34     print rcv
35 
36 if __name__ == '__main__':
37     #start_tcp(target_ip,target_port)
38     trans_data(target_ip,target_port,data)

 

运行结果如下:

1 # python exp3.py
2 <meta http-equiv="Pragma" content="no-cache">
3 <meta http-equiv="Expires" content="wed, 26 Feb 1997 08:21:57 GMT">
4 <html><head><title>505 HTTP Version not supported</title></head><body><center><h1>505 HTTP Version not supported</h1></center></body></html>�p�-1���-1��2��2��D��o�p�-1��`��D

wireshark抓包截图如下:

posted @ 2017-10-05 19:46  挣扎的猪  阅读(7419)  评论(0编辑  收藏  举报