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


Posted in Python onOctober 21, 2019

这篇文章主要介绍了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 相关文章推荐
Python书单 不将就
Jul 11 Python
Python实现按特定格式对文件进行读写的方法示例
Nov 30 Python
python 处理dataframe中的时间字段方法
Apr 10 Python
Python设计模式之模板方法模式实例详解
Jan 17 Python
python-itchat 获取微信群用户信息的实例
Feb 21 Python
Django框架使用内置方法实现登录功能详解
Jun 12 Python
Django框架中序列化和反序列化的例子
Aug 06 Python
基于python3 的百度图片下载器的实现代码
Nov 05 Python
django序列化serializers过程解析
Dec 14 Python
python+Selenium自动化测试——输入,点击操作
Mar 06 Python
利用PyTorch实现VGG16教程
Jun 24 Python
opencv 阈值分割的具体使用
Jul 08 Python
python文件读写代码实例
Oct 21 #Python
python 动态调用函数实例解析
Oct 21 #Python
python 两个数据库postgresql对比
Oct 21 #Python
python多进程(加入进程池)操作常见案例
Oct 21 #Python
Python实现字符串中某个字母的替代功能
Oct 21 #Python
基于Python实现船舶的MMSI的获取(推荐)
Oct 21 #Python
基于Python解密仿射密码
Oct 21 #Python
You might like
php查询mssql出现乱码的解决方法
2014/12/29 PHP
php随机显示指定文件夹下图片的方法
2015/07/13 PHP
PHP连接数据库实现注册页面的增删改查操作
2016/03/27 PHP
页面版文本框智能提示JS代码
2009/11/20 Javascript
Extjs 几个方法的讨论
2010/01/28 Javascript
javascript拖拽上传类库DropzoneJS使用方法
2013/12/05 Javascript
jquery实现checkbox 全选/全不选的通用写法
2014/02/22 Javascript
JavaScript实现的简单拖拽效果
2015/06/01 Javascript
全面解析Bootstrap中transition、affix的使用方法
2016/05/30 Javascript
使用vue框架 Ajax获取数据列表并用BootStrap显示出来
2017/04/24 Javascript
web前端vue filter 过滤器
2018/01/12 Javascript
详解js类型判断
2018/05/22 Javascript
JS实现前端页面的搜索功能
2018/06/12 Javascript
Vue实现搜索结果高亮显示关键字
2019/05/28 Javascript
Python多进程分块读取超大文件的方法
2016/04/13 Python
Python实现简易端口扫描器代码实例
2017/03/15 Python
Python如何通过subprocess调用adb命令详解
2017/08/27 Python
python3.4+pycharm 环境安装及使用方法
2019/06/13 Python
Python画图高斯分布的示例
2019/07/10 Python
django创建超级用户过程解析
2019/09/18 Python
python GUI框架pyqt5 对图片进行流式布局的方法(瀑布流flowlayout)
2020/03/12 Python
使用openCV去除文字中乱入的线条实例
2020/06/02 Python
使用Python解析Chrome浏览器书签的示例
2020/11/13 Python
英国度假别墅预订:Sykes Cottages
2017/06/12 全球购物
加拿大时装零售商:Influence U
2018/12/22 全球购物
上海期货面试题
2014/01/31 面试题
会展策划与管理专业大学生职业生涯规划
2014/02/07 职场文书
办公室主任主任岗位责任制
2014/02/11 职场文书
幼儿园父亲节活动方案
2014/03/11 职场文书
课程改革实施方案
2014/03/16 职场文书
个人合作协议书范本
2014/04/18 职场文书
公司市场专员岗位职责
2014/06/29 职场文书
教师师德师风自我剖析材料
2014/09/29 职场文书
运动会开幕式新闻稿
2015/07/17 职场文书
Python 居然可以在 Excel 中画画你知道吗
2022/02/15 Python
Python实现仓库管理系统
2022/05/30 Python