execUtil.py 1.0 KB

123456789101112131415161718192021222324252627282930
  1. # -*- coding: UTF-8 -*-
  2. import paramiko
  3. def run_cmd(ssh_client, cmd):
  4. """
  5. 运行单条命令
  6. :param ssh_client:
  7. :param cmd:
  8. :return:
  9. """
  10. # bash -l -c解释:-l(login)表示bash作为一个login shell;-c(command)表示执行后面字符串内的命令,这样执行的脚本,可以获取到/etc/profile里的全局变量,包括我们搜索命令的目录PATH
  11. print("执行命令: " + cmd)
  12. stdin, stdout, stderr = ssh_client.exec_command(cmd)
  13. res, err = stdout.read(), stderr.read()
  14. result = res if res else err
  15. result = result.decode('utf-8')
  16. print("运行结果: " + result)
  17. return result
  18. def get_client(json):
  19. """获取sshClient"""
  20. ssh_client = paramiko.SSHClient()
  21. ssh_client.load_system_host_keys()
  22. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  23. ssh_client.connect(hostname=json.get('host'), port=int(json.get('port')), username=json.get('username'),
  24. password=json.get('password'), timeout=int(json.get('timeout')))
  25. return ssh_client