记录:备忘录。
名词:
TFTP(Trivial File Transfer Protocol,简单文件传输协议)是TCP/IP协议族中的一个用来在客户机与服务器之间进行简单文件传输的协议,提供不复杂、开销不大的文件传输服务。
1.下载
import struct
from socket import *
import os
def downLoad():
"""下载文件"""
#文件名
downFileName = input("输入下载的文件名:")
#下载信息
# !H%dsb5sb
# ! 表示网络字节序,大端字节 H
# H 表示第二个参数1
# %d 表示文件名长度
# b 表示第四个参数长度 0
# 5s 表示第五个参数长度
download_args = struct.pack("!H%dsb5sb" % len(downFileName.encode("UTF-8")), 1,downFileName.encode("UTF-8"), 0, "octet".encode("UTF-8"), 0)
#创建socket
downSocket = socket(AF_INET, SOCK_DGRAM)
#TFTP服务器的ip和端口
downSocket.sendto(download_args, ("127.0.0.1", 69))
flag = True
num = 0
f = open(downFileName, "w", encoding='UTF-8')
while True:
responseData = downSocket.recvfrom(1024)
recvData, serverInfo = responseData
opNum = struct.unpack("!H", recvData[:2])
packetNum = struct.unpack("!H", recvData[2:4])
if opNum[0] == 3:
num = num + 1
if num == 65536:
num = 0
if num == packetNum[0]:
f.write(str(recvData[4:],encoding = "utf-8"))
num = packetNum[0]
ackData = struct.pack("!HH", 4, packetNum[0])
downSocket.sendto(ackData, serverInfo)
elif opNum[0] == 5:
flag = False
if len(recvData) < 516:
print("文件下载完成!")
break
if flag == True:
f.close()
else:
os.unlink(downFileName)
#关闭链接
downSocket.close()
def main():
downLoad()
if __name__ == '__main__':
main()
2.上传
import socket
import struct
def upLoad():
"""上传文件"""
upFileName = input("输入上传的文件名:")
code = 0
block_number = 0
current_number = 1
upload_args = struct.pack("!H{}sb5sb".format(len(upFileName)), 2, upFileName.encode("UTF-8"), 0, "octet".encode("UTF-8"), 0)
upSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
upSocket.bind(("127.0.0.1", 7777))
upSocket.sendto(upload_args, ("127.0.0.1", 69))
while True:
data, addr = upSocket.recvfrom(1024)
code, block_number = struct.unpack("!HH", data[:4])
if code == 4:
if block_number == 0:
f = open(upFileName, 'rb')
if block_number + 1 == current_number:
file_data = f.read(512)
send_data = struct.pack('!HH', 3, current_number) + file_data
upSocket.sendto(send_data, addr)
print("第{}次传输数据!".format(current_number))
block_number += 1
current_number += 1
if len(send_data) < 516:
f.close()
print("文件上传完成!")
break
elif code == 5:
f.close()
print("上传文件失败!error info: {}".format(data[4:].decode()))
break
# 关闭链接
upSocket.close()
def main():
upLoad()
if __name__ == '__main__':
main()
3.测试工具
Tftpd32工具辅助测试,无需设置,只用TFTP服务器功能,运行后,即是一个TFTP服务器。
以上,感谢。