python 采用paramiko 远程执行命令及报错解决

 更新时间:2019年10月21日 11:16:28   作者:百变小超  
这篇文章主要介绍了python 采用paramiko 远程执行命令及报错解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了python 采用paramiko 远程执行命令及报错解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

import sys
import paramiko
import config_reader
from check_utils import standout_print, parse_remainsize_response_lines, error_out_print
from time import time


class RemoteModel:
  """ remote options model
  execute remote command
  """

  def __init__(self, host, port=22):
    self.hostname = host
    self.port = port

    self.username, self.password = self.load_conf()
    self.s = None
    self.session = None
    self.init_conn()

  def load_conf(self):
    """
      read config get the login info of remote host machine
    :return:
      login username and password of SSH login of this host
    """
    if self.hostname.find("10.179.1.110") != -1:
      error_out_print("Error : the remote machine of KOR can not provide. please know")
      sys.exit(-1)

    username, password = config_reader.read_login_config(self.hostname)

    if not username or not password:
      error_out_print(
        'Error: can not find ssh login info in this host[%s]. check need ' % self.hostname)
      sys.exit(-1)

    return username, password

  def init_conn(self):
    """
      make a connection with the remote machine
    :return:
    """
    try:
      paramiko.util.log_to_file("paramiko_log.log")
      self.s = paramiko.SSHClient()
      self.s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      self.s.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password)

      standout_print('success connect the remote machine [host=%s]' % self.hostname)

    except Exception, e:
      standout_print(str(e))
      standout_print(
        'connect failed.in host[%s] user[%s] or pwd[%s] maybe wrong. ' % (
          self.hostname, self.username, self.password))
      sys.exit(-1)

  def close(self):
    """
    close
    if close can not use this connection
    :return:
    """
    if self.s:
      self.s.close()
      self = None

  def execute_command(self, command):
    """
    :param command:
      execute cmd
    :return:
      the response lines
    """
    standout_print("Info: execute command [%s]" % command)
    stdin, stdout, stderr = self.s.exec_command(command)
    stdin.write("pwd"+"\n")
    stdin.flush()

    response_lines = stdout.readlines()
    error_info = stderr.read()

    if error_info and error_info.strip():
      error_out_print(' remote command error info : %s' % stderr.read())
      error_out_print(error_info)
      return None

    # info_arr = response_info.split('\n')

    return response_lines

  def remain_space_size(self, directory_path):
    """
    :param directory_path:

    :return:
      free size of the directory
      unit size : MB
    """

    cmd = 'sudo df -m %s 1>&2' % directory_path # /usr/local/pgsql/data/ssd1

    response_lines = self.execute_command(cmd)
    # response_lines = self.execute_command_channel(cmd)

    return parse_remainsize_response_lines(response_lines)

  def execute(self, command, sudo=False):
    feed_password = False
    if sudo and self.username != "root":
      command = "sudo %s" % command
      feed_password = "pwd"
    stdin, stdout, stderr = self.s.exec_command(command, get_pty=True)
    if feed_password:
      stdin.write(self.password + "\n")
      stdin.flush()
    return {'out': stdout.readlines(),
        'err': stderr.readlines(),
        'retval': stdout.channel.recv_exit_status()}


if __name__ == '__main__':
  host = ""
  hostname = ""
  command = "sudo df -m /data/pgsql94/data"
  rm = RemoteModel(host=hostname)
  print rm.execute_command(command)
  # print rm.execute("df -m /data/pgsql94/data 1>&2", True)

报错1:

remote command error info : 
sudo: sorry, you must have a tty to run sudo

是由于

self.s.exec_command(command, get_pty=True)

没有设置

get_pty=True

报错2:

会卡死在

stdout.readlines()

是由于 SSH在等待输入用户名的密码

stdin.write("pwd"+"\n")
stdin.flush()

该种方式进行交互,注意必须要换行"\n",和前面必须不能有空格等其他字符,确保密码正确

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 升级python导致Yum崩溃的解决办法

    升级python导致Yum崩溃的解决办法

    这篇文章主要介绍了升级python导致Yum崩溃的三种解决办法,文中通过代码示例讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-11-11
  • python调用API实现智能回复机器人

    python调用API实现智能回复机器人

    这篇文章主要为大家详细介绍了python调用API实现智能回复机器人,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • 七个生态系统核心库[python自学收藏]

    七个生态系统核心库[python自学收藏]

    无论你是想快速入手Python,还是想成为数据分析大神或者机器学习大佬,亦或者对Python代码进行优化,本文的python库都能为你提供一些帮助
    2021-08-08
  • 使用Python和Scrapy实现抓取网站数据

    使用Python和Scrapy实现抓取网站数据

    Scrapy是一个功能强大的网络爬虫框架,允许开发者轻松地抓取和解析网站内容,这篇文章主要为大家介绍了如何使用Python的Scrapy库进行网站数据抓取,需要的可以参考一下
    2023-05-05
  • Python根据文件名批量转移图片的方法

    Python根据文件名批量转移图片的方法

    今天小编就为大家分享一篇Python根据文件名批量转移图片的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • 树莓派4B安装Tensorflow的方法步骤

    树莓派4B安装Tensorflow的方法步骤

    这篇文章主要介绍了树莓派4B安装Tensorflow的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • python手写均值滤波

    python手写均值滤波

    这篇文章主要为大家详细介绍了python手写均值滤波的相关代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-02-02
  • 使用Python和OpenCV检测图像中的物体并将物体裁剪下来

    使用Python和OpenCV检测图像中的物体并将物体裁剪下来

    这篇文章主要介绍了使用Python和OpenCV检测图像中的物体并将物体裁剪下来,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • 使用python-Jenkins批量创建及修改jobs操作

    使用python-Jenkins批量创建及修改jobs操作

    这篇文章主要介绍了使用python-Jenkins批量创建及修改jobs操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python 中拼音库 PyPinyin 用法详解

    Python 中拼音库 PyPinyin 用法详解

    很多朋友问小编怎样把一批中文文件转拼音命名呢?下面就让我们来了解 Python 的一个库 PyPinyin 吧,感兴趣的朋友跟随小编一起看看吧
    2021-05-05

最新评论