Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # encoding: utf-8
- __author__ = 'liuyun'
- import paramiko
- from paramiko_expect import SSHClientInteraction
- import traceback
- def process_tail(strs, current_line):
- for str in strs:
- if current_line.find(str) != -1:
- return current_line
- return ""
- def end_tail(result, current_line):
- for key in result:
- if current_line.find(key) != -1:
- result[key] = True
- return False if False in result.values() else True
- class SshClient:
- def __init__(self, hostname, port, username, password):
- self.hostname = hostname
- self.port = port
- self.username = username
- self.password = password
- self.s = self._conn()
- def _conn(self):
- s = paramiko.SSHClient()
- s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- s.connect(hostname=self.hostname, port=self.port, username= self.username, password=self.password)
- return s
- def close(self):
- if(self.s): self.s.close()
- def is_grep_str_sucess(self, filename, strs, timeout=None):
- try:
- interact = SSHClientInteraction(self.s, timeout=10, display=False)
- interact.send('tail -f -n 0 %s' % filename)
- results = {str:False for str in strs}
- interact.tail(callback=lambda line_prefix, current_line:process_tail(strs, current_line),
- stop_callback=lambda current_line:end_tail(results, current_line),
- timeout=timeout)
- return True
- except Exception:
- traceback.print_exc()
- return False
- def execCmd(self, cmd):
- stdin, stdout, stderr = self.s.exec_command(cmd)
- # stdin.write("Y") # Generally speaking, the first connection, need a simple interaction.
- return stdin, stdout, stderr
- if __name__ == "__main__":
- sshclient = SshClient("192.168.1.193", "22", "****", "****")
- print sshclient.is_grep_str_sucess("test.txt", ["liuyun", "robot"], 60)
- sshclient.close()
Add Comment
Please, Sign In to add comment