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增加矩阵维度的实例讲解
Apr 04 Python
Django使用redis缓存服务器的实现代码示例
Apr 28 Python
使用Filter过滤python中的日志输出的实现方法
Jul 17 Python
Python使用Slider组件实现调整曲线参数功能示例
Sep 06 Python
OpenCV+Python--RGB转HSI的实现
Nov 27 Python
JupyterNotebook设置Python环境的方法步骤
Dec 03 Python
python 实现将小图片放到另一个较大的白色或黑色背景图片中
Dec 12 Python
Python 内置函数globals()和locals()对比详解
Dec 23 Python
150行python代码实现贪吃蛇游戏
Apr 24 Python
pytorch 查看cuda 版本方式
Jun 23 Python
树莓派升级python的具体步骤
Jul 05 Python
为了顺利买到演唱会的票用Python制作了自动抢票的脚本
Oct 16 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
自动分页的不完整解决方案
2007/01/12 PHP
javascript div 遮罩层封锁整个页面
2009/07/10 Javascript
JS 学习笔记 防止发生命名冲突
2009/07/30 Javascript
JavaScript 学习笔记(十五)
2010/01/28 Javascript
javascript 窗口加载蒙板 内嵌网页内容
2010/11/19 Javascript
JS 获取滚动条高度示例代码
2013/10/24 Javascript
浅谈jQuery中对象遍历.eq().first().last().slice()方法
2014/11/26 Javascript
Javascript基础教程之JavaScript语法
2015/01/18 Javascript
canvas学习之API整理笔记(一)
2016/12/29 Javascript
ajax分页效果(bootstrap模态框)
2017/01/23 Javascript
BootstrapTable refresh 方法使用实例简单介绍
2017/02/20 Javascript
javascript 正则表达式分组、断言详解
2017/04/20 Javascript
jQuery接受后台传递的List的实例详解
2017/08/02 jQuery
Vue Router去掉url中默认的锚点#
2018/08/01 Javascript
vue填坑之webpack run build 静态资源找不到的解决方法
2018/09/03 Javascript
vue项目中使用vue-i18n报错的解决方法
2019/01/13 Javascript
OpenLayers3实现对地图的基本操作
2020/09/28 Javascript
微信小程序实现多行文字滚动
2020/11/18 Javascript
实例解析Python的Twisted框架中Deferred对象的用法
2016/05/25 Python
巧用python和libnmapd,提取Nmap扫描结果
2016/08/23 Python
Python学习小技巧之利用字典的默认行为
2017/05/20 Python
Python利用递归和walk()遍历目录文件的方法示例
2017/07/14 Python
python读文件保存到字典,修改字典并写入新文件的实例
2018/04/23 Python
html5设计原理(推荐收藏)
2014/05/17 HTML / CSS
FORZIERI福喜利中国官网:奢侈品购物梦工厂
2019/05/03 全球购物
职业技术学校毕业生推荐信
2013/12/03 职场文书
社区包粽子活动方案
2014/01/21 职场文书
三年级数学教学反思
2014/01/31 职场文书
教师党性分析材料
2014/02/04 职场文书
对祖国的寄语大全
2014/04/11 职场文书
营销总经理岗位职责范本
2014/09/02 职场文书
房产销售独家委托书范本
2014/10/01 职场文书
2014年企业员工工作总结
2014/12/09 职场文书
英文邀请函
2015/02/02 职场文书
被告代理词范文
2015/05/25 职场文书
小兵张嘎观后感300字
2015/06/03 职场文书