Baboon
Baboon

Reputation: 307

How to transfer a file between two connected computers in python?

I don't know if this has been answered before(i looked online but couldn't find one), but how can i send a file (.exe if possible) over a network to another computer that is connected to the network? I tried sockets but i could only send strings and i've tried to learn ftplib but i don't understand it at all or if ftp is even what i am looking for, so i am at a complete standstill. Any input is appreciated (even more so if someone can explain FTP, is it like socket? All the examples i've seen don't have a server program where the client can connect to.)

Upvotes: 8

Views: 31141

Answers (4)

Zach Kelling
Zach Kelling

Reputation: 53829

A. Python3

We can use http.server for this. From SO answer here, SimpleHTTPServer is moved to http.server in python3.

python -m http.server

Python2:

I use SimpleHTTPServer for this sometimes:

python -m SimpleHTTPServer

...which would serve the files in the current directory on port 8000. Open your web browser on the other computer and download whatever you want.

To know the IP address of your computer, you can use (in Ubuntu) ifconfig, e.g:

$ ifconfig
enp0s31f6 Link encap:Ethernet  HWaddr xx:xx:xx:xx:xx:xx
          inet addr:10.0.0.3  Bcast:10.0.0.255  Mask:255.255.255.0

In windows it is ipconfig.

Then, in the other computer, you send the browser to: http://10.0.0.3:8000.

B. If you have SSH enabled you could use paramiko to connect and SFTP transfer whatever you want.

Upvotes: 11

Jesvin Jose
Jesvin Jose

Reputation: 23088

ZeroMQ helps to replace sockets.

You can send an entire file in one command.

A ZMQ 'party' can be written in any major language and for a given ZMQ-powered software, it doesnt matter what the other end it written in.

From their site:

It gives you sockets that carry whole messages across various transports like in-process, inter-process, TCP, and multicast. You can connect sockets N-to-N with patterns like fanout, pub-sub, task distribution, and request-reply.

Upvotes: 3

g.d.d.c
g.d.d.c

Reputation: 47988

Some simplistic example code for the sending side:

if os.path.exists(df):
  with open(df, 'rb') as f:
    packet = f.read(blocksize)

    while packet != '':
      conn.send(packet)

      packet = f.read(blocksize)

Where:

df = 'path/to/data/file'
blocksize = 8192 # or some other size packet you want to transmit.  
                 # Powers of 2 are good.
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Upvotes: 7

joel3000
joel3000

Reputation: 1319

Check out paramiko. It can do scp and sftp.

http://www.lag.net/paramiko/

Upvotes: 3

Related Questions