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的异常处理
Jun 19 Python
python django 实现验证码的功能实例代码
May 18 Python
解决python文件字符串转列表时遇到空行的问题
Jul 09 Python
pandas数据预处理之dataframe的groupby操作方法
Apr 13 Python
python3.6使用pymysql连接Mysql数据库
May 25 Python
Python时间和字符串转换操作实例分析
Mar 16 Python
如何将 awk 脚本移植到 Python
Dec 09 Python
tensorflow之获取tensor的shape作为max_pool的ksize实例
Jan 04 Python
详解pycharm连接不上mysql数据库的解决办法
Jan 10 Python
Python正则re模块使用步骤及原理解析
Aug 18 Python
Django执行源生mysql语句实现过程解析
Nov 12 Python
Python 解决空列表.append() 输出为None的问题
May 23 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
ThinkPHP控制器间实现相互调用的方法
2014/10/31 PHP
CI框架入门示例之数据库取数据完整实现方法
2014/11/05 PHP
详解在PHP的Yii框架中使用行为Behaviors的方法
2016/03/18 PHP
Zend Framework教程之Zend_Db_Table表关联实例详解
2016/03/23 PHP
jQuery 判断页面元素是否存在的代码
2009/08/14 Javascript
JavaScript 学习笔记(五)
2009/12/31 Javascript
在jQuery 1.5中使用deferred对象的代码(翻译)
2011/03/10 Javascript
node.js中的buffer.fill方法使用说明
2014/12/14 Javascript
javascript实现的多个层切换效果通用函数实例
2015/07/06 Javascript
Bootstrap每天必学之导航条(二)
2016/03/01 Javascript
AngularJS通过$location获取及改变当前页面的URL
2016/09/23 Javascript
JS产生随机数的用法小结
2016/12/10 Javascript
BootstrapTable请求数据时设置超时(timeout)的方法
2017/01/22 Javascript
关于前后端json数据的发送与接收详解
2017/07/30 Javascript
EasyUI框架 使用Ajax提交注册信息的实现代码
2017/09/27 Javascript
利用node实现一个批量重命名文件的函数
2017/12/21 Javascript
Vue中fragment.js使用方法小结
2020/02/17 Javascript
浅谈Vue static 静态资源路径 和 style问题
2020/11/07 Javascript
Python 获得命令行参数的方法(推荐)
2018/01/24 Python
对Tensorflow中的变量初始化函数详解
2018/07/27 Python
kafka-python批量发送数据的实例
2018/12/27 Python
ipython和python区别详解
2019/06/26 Python
numpy实现神经网络反向传播算法的步骤
2019/12/24 Python
python3.6连接mysql数据库及增删改查操作详解
2020/02/10 Python
利用keras使用神经网络预测销量操作
2020/07/07 Python
Python3.9最新版下载与安装图文教程详解(Windows系统为例)
2020/11/28 Python
Python爬虫定时计划任务的几种常见方法(推荐)
2021/01/15 Python
Paradigit比利时电脑卖场:购买笔记本、电脑、平板和外围设备
2016/11/28 全球购物
Surfdome西班牙:世界上最受欢迎的生活方式品牌
2019/02/13 全球购物
数学专业推荐信范文
2013/11/21 职场文书
生物专业个人自荐信范文
2013/11/29 职场文书
财务会计专业推荐信
2013/11/30 职场文书
淘宝中秋节活动方案
2014/01/31 职场文书
2014学雷锋活动总结
2014/03/09 职场文书
2014年教务处工作总结
2014/12/03 职场文书
详细介绍python类及类的用法
2021/05/31 Python