Harman5007

ssh_server

Jun 17th, 2020
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. import socket
  2. import paramiko
  3. import threading
  4. import sys
  5.  
  6. # using the key from the Paramiko demo files
  7. host_key = paramiko.RSAKey(filename='test_rsa.key')
  8.  
  9. class Server (paramiko.ServerInterface):
  10.  
  11. def _init_(self):
  12. self.event = threading.Event()
  13. # This function Checks if there is any session is created or not
  14. def check_channel_request(self, kind, chanid):
  15. if kind == 'session':
  16. return paramiko.OPEN_SUCCEEDED
  17. return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
  18. def check_auth_password(self, username, password):
  19. if (username == 'harman') and (password == '5007'):
  20. return paramiko.AUTH_SUCCESSFUL
  21. return paramiko.AUTH_FAILED
  22.  
  23. server = sys.argv[1]
  24. ssh_port = int(sys.argv[2])
  25.  
  26. try:
  27. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  28.  
  29. # socket.SO_REUSEADDR allows protocols to use the same port on localhost #_____multiple times only if protocols request it
  30.  
  31. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  32. sock.bind((server, ssh_port))
  33. sock.listen(100)
  34. print('[+] Listening for connection ...')
  35. client, addr = sock.accept()
  36. except Exception as e:
  37. print (f'[-] Listen failed: {e}')
  38. sys.exit(1)
  39.  
  40. print('[+] Got a connection!')
  41.  
  42. try:
  43. bhSession = paramiko.Transport(client)
  44. #ssh.load_system_host_keys()
  45. bhSession.add_server_key(host_key)
  46. server1 = Server()
  47. try:
  48. bhSession.start_server(server=server1)
  49.  
  50. except paramiko.SSHException as x:
  51. print ('[-] SSH negotiation failed.')
  52.  
  53. chan = bhSession.accept(20)
  54. print('[+] Authenticated!')
  55. #chan.send('Welcome to bh_ssh'.encode('utf-8'))
  56. print(chan.recv(4096).decode('utf-8'))
  57. chan.send('Welcome to bh_ssh'.encode('utf-8'))
  58.  
  59. while not chan.closed:
  60. try:
  61. command = input("Enter command: ").rstrip()
  62. #if len(command):
  63. if command != 'exit':
  64. chan.send(command)
  65. print(chan.recv(4096).decode('utf-8') + '\n')
  66. else:
  67. print('exiting')
  68. bhSession.close()
  69. print("[*] SSH session closed")
  70. sys.exit(1)
  71. except Exception as err:
  72. print("[*] Caught Exception: ", str(err))
  73. print("[*] Exiting Script")
  74.  
  75. except Exception as e :
  76. print (f'[-] Caught exception:{e}')
  77. sys.exit(1)
Add Comment
Please, Sign In to add comment