简述
在命令行敲如下命令,发送指定文件到指定的主机
发送到默认IP和端口
$ sender msg.xml
发送到默认IP指定端口
$ sender msg.xml 9999
发送到指定IP指定端口
$ sender msg.xml 192.168.0.110 9999
环境
- Linux
- Python
代码
将下面的代码保存为sender.py,执行$ chmod +x sender.py
#! /usr/bin/python
import socket
import sys
import os
class msg_sender():
host = '127.0.0.1'
port = 9999
def __init__(self):
if len(sys.argv) < 2:
print 'Usage: s file [ip][port]'
return None
elif len(sys.argv) == 3:
self.port = sys.argv[2]
elif len(sys.argv) == 4:
self.host = sys.argv[2]
self.port = sys.argv[3]
print 'Remote:', self.host, self.port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
file_size = os.stat(sys.argv[1]).st_size
fd = open(sys.argv[1], 'r')
buf = fd.read()
buf = str(file_size).zfill(8) + buf
fd.close()
print 'File Name', sys.argv[1]
print 'Data Size', file_size
print 'Send Date', buf
s.send(buf)
print 'Send Total', len(buf)
print 'Receiving ...'
buf = s.recv(1024)
print 'Received Date:', buf
print 'Received Total:', len(buf)
print 'Data Size:', int(buf[0:8])
s.close()
if __name__ == '__main__':
s = msg_sender()