Skip to content

标题: ChatGPT编写的文件上传方案

作者: bluerust 创建: 2023-03-08 13:46 更新: 链接: https://scz.617.cn/network/202303081346.txt

背景大致如下

a) Win10位于堡垒机内侧,正常情况下外侧用户通过网页VNC控制Win10 b Win10的1024/TCP以上端口外侧可达,但无法主动向外connect c) 无法在Win10上用PowerShell,但找到.net编译器csc.exe,且cmd可用 d) 外侧Linux是己方完全可控主机,Linux->Win10可单向建立TCP连接 e) 原始需求是从Linux向Win10上传Python安装包

首先去找csc.exe,这玩意不在缺省PATH上,但很多Win10上都有,比如

dir /S C:\csc.exe

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe

然后我让ChatGPT用C#写一个收文件的服务端(server.cs)


using System; using System.IO; using System.Net; using System.Net.Sockets;

class Program { static void Main () { // Set the IP address and port number to listen on // Change this to your desired IP address IPAddress IP = IPAddress.Parse( "x.x.x.x" ); // Change this to your desired port number int Port = 1314; // Create the TCP listener and start listening for incoming connections TcpListener listener = new TcpListener( IP, Port ); listener.Start(); Console.WriteLine( "Server listening on {0}:{1}", IP, Port ); while ( true ) { // Wait for a client connection to come in TcpClient client = listener.AcceptTcpClient(); Console.WriteLine( "Client connected from {0}", client.Client.RemoteEndPoint ); // Create a binary reader to read incoming data from the client BinaryReader reader = new BinaryReader( client.GetStream() ); // Read the first 4 bytes to get the length of the incoming file int FileSize = reader.ReadInt32(); // Read the file data into a buffer byte[] FileData = reader.ReadBytes( FileSize ); // Close the client connection client.Close(); // Write the file data to disk File.WriteAllBytes( "some.bin", FileData ); Console.WriteLine( "File received and saved to some.bin" ); } } }


看了一眼它这个实现,前4字节是文件大小,之后是文件内容,没法直接和nc配合, 于是我又让ChatGPT用Python写一个发文件的客户端(client.py)


import sys, socket

Set the server IP address and port number

Change this to your server's IP address

IP = 'x.x.x.x'

Change this to your server's port number

Port = 1314

Create a TCP socket and connect to the server

Sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) Sock.connect( ( IP, Port ) ) print( 'Connected to server' )

Open the binary file to send to the server

with open( sys.argv[1], 'rb' ) as f : # Read the file data into a buffer data = f.read() # Convert the file size to a 4-byte binary representation size = len( data ).to_bytes( 4, byteorder='big' ) # Send the file size to the server Sock.send( size ) # Send the file data to the server Sock.send( data )

print( 'File sent to server' )

Close the socket

Sock.close()

在Win10上编译并执行服务端

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /nologo server.cs server.exe

在Linux上执行客户端

python3 client.py some.bin

在Linux上取文件哈希

sha256sum some.bin

在Win10上校验文件哈希

certutil -hashfile some.bin sha256

整套方案未必是最优解,但胜在快速达成目的,生产力工具,妥妥的。