Guest User

Untitled

a guest
Jun 18th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. # encoding: utf-8
  2. __author__ = 'liuyun'
  3.  
  4. import paramiko
  5. from paramiko_expect import SSHClientInteraction
  6. import traceback
  7.  
  8. def process_tail(strs, current_line):
  9. for str in strs:
  10. if current_line.find(str) != -1:
  11. return current_line
  12. return ""
  13.  
  14. def end_tail(result, current_line):
  15. for key in result:
  16. if current_line.find(key) != -1:
  17. result[key] = True
  18.  
  19. return False if False in result.values() else True
  20.  
  21.  
  22. class SshClient:
  23.  
  24. def __init__(self, hostname, port, username, password):
  25. self.hostname = hostname
  26. self.port = port
  27. self.username = username
  28. self.password = password
  29. self.s = self._conn()
  30.  
  31. def _conn(self):
  32. s = paramiko.SSHClient()
  33. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  34. s.connect(hostname=self.hostname, port=self.port, username= self.username, password=self.password)
  35. return s
  36.  
  37. def close(self):
  38. if(self.s): self.s.close()
  39.  
  40. def is_grep_str_sucess(self, filename, strs, timeout=None):
  41. try:
  42. interact = SSHClientInteraction(self.s, timeout=10, display=False)
  43. interact.send('tail -f -n 0 %s' % filename)
  44. results = {str:False for str in strs}
  45. interact.tail(callback=lambda line_prefix, current_line:process_tail(strs, current_line),
  46. stop_callback=lambda current_line:end_tail(results, current_line),
  47. timeout=timeout)
  48. return True
  49.  
  50. except Exception:
  51. traceback.print_exc()
  52. return False
  53.  
  54.  
  55. def execCmd(self, cmd):
  56. stdin, stdout, stderr = self.s.exec_command(cmd)
  57. # stdin.write("Y") # Generally speaking, the first connection, need a simple interaction.
  58. return stdin, stdout, stderr
  59.  
  60.  
  61.  
  62. if __name__ == "__main__":
  63. sshclient = SshClient("192.168.1.193", "22", "****", "****")
  64. print sshclient.is_grep_str_sucess("test.txt", ["liuyun", "robot"], 60)
  65. sshclient.close()
Add Comment
Please, Sign In to add comment