python3 socket 实现TFTP 文件上传

本代码运行环境:python3 + Ubuntu16

1:运行代码前需要运行tftp服务器端,把要上传的文件放在和执行文件同一个文件夹里
2:tftp服务器端ip要和ubuntu ip在同一网段

TFTP数据包的格式如下
python3 socket 实现TFTP 文件上传插图

粗糙的实现代码如下:

from socket import *
import struct
import sys


# 命令行传入参数
if len(sys.argv) != 2:
    print('-'*30)
    print('Run tips:')
    print('python3 filename.py destination_ip')
    print('-'*30)
else:
    ip = sys.argv[1]


tftp_upload = socket(AF_INET, SOCK_DGRAM)
# 构建数据包
u_pack = struct.pack("!H15sb5sb", 2, b'test_upload.jpg', 0, b'octet', 0)
address_ip_bind = (ip, 69)
tftp_upload.sendto(u_pack, address_ip_bind)

num = 0
# 以二进制读的模式打开文件
send_data = open('test_upload.jpg', 'rb')

while True:
    data_information, data_address = tftp_upload.recvfrom(1024)
    # 拆数据包
    data_unpack = struct.unpack("!HH", data_information[:4])
    # 操作码
    data_ack = data_unpack[0]
    # 块编号
    data_num = data_unpack[1]
    
    if data_ack == 4:
        data_read = send_data.read(512)
        if data_num == num:
            file_pack = struct.pack("!HH", 3, num+1) + data_read
            发送上传文件
            tftp_upload.sendto(file_pack, data_address)
            print('\rUpload data for the (%d) time' % (num+1), end='')
            num += 1
            # if len(data_read) == 0:
            #     print('Upload complete!')
            #     break
            if data_read == ''.encode('utf-8'):  # python3要转码,不然不执行
                print('Upload complete!')
                break


tftp_upload.close()
send_data.close()
THE END
分享
二维码
< <上一篇
下一篇>>