Advertisement
Guest User

Untitled

a guest
Oct 17th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.90 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3. import sys
  4. import getopt
  5. import socket
  6.  
  7. def main(argv):
  8. """Parse command line arguements to transfer file"""
  9. #Attempt to parse command line args, catch error
  10. try:
  11. options, arguements = getopt.getopt(argv, "a:f:hp:svw", ["address=", "file=", "help", "port=", "send", "verbose", "wait"])
  12. except getopt.GetoptError:
  13. error("Incorrect arguements")
  14.  
  15. #Parse getopt option, arguement tuples to a dictionary
  16. args = dict(options)
  17.  
  18. #Store whether the command should be verbose
  19. global verbose_bool
  20. verbose_bool = "-v" in args.keys() or "--verbose" in args.keys()
  21.  
  22. #Test for presence of a wait and/or send flag
  23. wait_bool = "-w" in args.keys() or "--wait" in args.keys()
  24. send_bool = "-s" in args.keys() or "--send" in args.keys()
  25.  
  26. #Resolve script action from flags
  27. if wait_bool and send_bool:
  28. error("Cannot wait and send.")
  29. elif wait_bool:
  30. #Wait on the specified port
  31. port = args.get("-p") or args.get("--port")
  32. if port is None:
  33. error("Must specify port to wait on")
  34. wait(port)
  35. elif send_bool:
  36. #Retrieve the target address
  37. address = args.get("-a") or args.get("--address")
  38. if address is None:
  39. error("Must specify address to send to.")
  40.  
  41. #Retrive port to transfer on
  42. port = args.get("-p") or args.get("--port")
  43. if port is None:
  44. error("Must specify port to transfer on")
  45.  
  46. #Retrieve the filename
  47. filename = args.get("-f") or args.get("--file")
  48. if filename is None:
  49. error("Must specify file to send")
  50.  
  51. #Send the file to the adress
  52. send(address, port, filename)
  53. elif "-h" in args.keys() or "--help" in args.keys():
  54. #Display usage and exit
  55. usage()
  56. sys.exit(0)
  57. else:
  58. error("Must send, wait, or help")
  59.  
  60. def wait(port):
  61. """Wait for a transfer on specified port"""
  62.  
  63. print ("Waiting for connection on port", port + "...")
  64.  
  65. #Establish server socket
  66. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Set up server socket
  67. server.bind(('', int(port))) #Bind socket to specified port
  68. server.listen(1) #Listen for up to 1 connection on bound port
  69. connection, address = server.accept() #On connection accept, store new connection and address
  70. print ("Connected to address", address)
  71.  
  72. #Recieve the data
  73. if verbose_bool: print ("\nRecieving data")
  74. data = ""
  75. while True:
  76. new_data = connection.recv(512)
  77. if not new_data:
  78. break
  79. data += new_data
  80. if verbose_bool: print ("Data recieved")
  81.  
  82. #Seperate filename and file content via delimeter
  83. delim_index = data.find("///")
  84. delim_end = delim_index + 3
  85. filename = data[:delim_index]
  86. file_content = data[delim_end:]
  87.  
  88. #Save file
  89. if verbose_bool: print ("\nSaving file", filename)
  90. f = open(filename, "w")
  91. f.write(file_content)
  92. f.close()
  93. print ("File", filename, "saved")
  94.  
  95. #Close connection"2
  96.  
  97. if verbose_bool: print ("\nClosing connection")
  98. connection.close()
  99.  
  100. def send(address, port, filename):
  101. """Send a file to an address on specified port"""
  102.  
  103. print ("Establishing connection on port", port)
  104.  
  105. #Establish client socket
  106. client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Set up client socket
  107. client.connect((address, int(port)))
  108. print ("Connection established")
  109.  
  110. #Read in file
  111. if verbose_bool: print ("\nReading file")
  112. try:
  113. f = open(filename, "r")
  114. except IOError:
  115. print ("Error: File", filename, "not found")
  116. client.close()
  117. sys.exit(1)
  118. file_content = f.read()
  119. f.close()
  120. if verbose_bool: print ("File read")
  121.  
  122. #Format data for sending
  123. data = filename + "///" + file_content
  124.  
  125. #Send data
  126. if verbose_bool: print ("\nSending", filename)
  127. while data:
  128. send_data = data[:512]
  129. data = data[512:]
  130. client.send(send_data)
  131. print ("Sent", filename)
  132.  
  133. #Close client connection
  134. if verbose_bool: print ("\nClosing connection")
  135. client.close()
  136.  
  137. def error(msg):
  138. """Print an error message and usage, then quit"""
  139. print (msg, "\n")
  140. usage()
  141. sys.exit(2)
  142.  
  143. def usage():
  144. """Print script usage"""
  145. print ("Usage: sendfile [OPTION] ...")
  146. print ("Sends a file to another sendfile user on the other end.")
  147. print ("")
  148. print ("-a, --address The adress to send to ")
  149. print ("-f, --file Filename to send")
  150. print ("-h, --help Print this usage and quit")
  151. print ("-p, --port The port to send or wait on")
  152. print ("-s, --send Flag telling sendfile to send")
  153. print ("-w, --wait Flag telling sendfile to wait")
  154.  
  155. if __name__ == "__main__":
  156. main(sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement