命令行发送文件到远程主机

2016-12-08  本文已影响0人  CG7

简述

在命令行敲如下命令,发送指定文件到指定的主机

环境

代码

将下面的代码保存为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()
上一篇下一篇

猜你喜欢

热点阅读