forked from x4nth055/pythoncode-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsender.py
More file actions
55 lines (46 loc) · 1.58 KB
/
Copy pathsender.py
File metadata and controls
55 lines (46 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Client that sends the file (uploads)
"""
import socket
import tqdm
import os
import argparse
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 1024 * 4
def send_file(filename, host, port):
# get the file size
filesize = os.path.getsize(filename)
# create the client socket
s = socket.socket()
print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected.")
# send the filename and filesize
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
# start sending the file
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
while True:
# read the bytes from the file
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
# file transmitting is done
break
# we use sendall to assure transimission in
# busy networks
s.sendall(bytes_read)
# update the progress bar
progress.update(len(bytes_read))
# close the socket
s.close()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Simple File Sender")
parser.add_argument("file", help="File name to send")
parser.add_argument("host", help="The host/IP address of the receiver")
parser.add_argument("-p", "--port", help="Port to use, default is 5001", type=int, default=5001)
args = parser.parse_args()
filename = args.file
host = args.host
port = args.port
send_file(filename, host, port)