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迭代器实例简析
Sep 25 Python
使用Pyrex来扩展和加速Python程序的教程
Apr 13 Python
在Python的Flask框架下收发电子邮件的教程
Apr 21 Python
python生成器generator用法实例分析
Jun 04 Python
Python备份目录及目录下的全部内容的实现方法
Jun 12 Python
Python编程实现生成特定范围内不重复多个随机数的2种方法
Apr 14 Python
Python 3.8中实现functools.cached_property功能
May 29 Python
Python中调用其他程序的方式详解
Aug 06 Python
python GUI库图形界面开发之PyQt5时间控件QTimer详细使用方法与实例
Feb 26 Python
详解基于Jupyter notebooks采用sklearn库实现多元回归方程编程
Mar 25 Python
浅析Python中的套接字编程
Jun 22 Python
python 使用tkinter与messagebox写界面和弹窗
Mar 20 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面试题附答案
2009/01/07 PHP
php 无限级分类学习参考之对ecshop无限级分类的解析 带详细注释
2010/03/23 PHP
PHP curl 并发最佳实践代码分享
2012/09/05 PHP
ThinkPHP单字母函数(快捷方法)使用总结
2014/07/23 PHP
PHP Echo字符串的连接格式
2016/03/07 PHP
PHP之图片上传类实例代码(加了缩略图)
2016/06/30 PHP
用javascript实现读取txt文档的脚本
2007/07/20 Javascript
对字符串进行HTML编码和解码的JavaScript函数
2010/02/01 Javascript
一步一步制作jquery插件Tabs实现过程
2010/07/06 Javascript
基于jQuery UI CSS Framework开发Widget的经验
2010/08/21 Javascript
js判断当前浏览器类型,判断IE浏览器方法
2014/06/02 Javascript
JS使用cookie实现DIV提示框只显示一次的方法
2015/11/05 Javascript
详解javascript高级定时器
2015/12/31 Javascript
纯js实现手风琴效果
2020/04/17 Javascript
jquery使用on绑定a标签无效 只能用live解决
2016/06/02 Javascript
VUE axios上传图片到七牛的实例代码
2017/07/28 Javascript
微信小程序页面间值传递的两种方法
2018/11/26 Javascript
js中数组对象去重的两种方法
2019/01/18 Javascript
微信公众平台获取access_token的方法步骤
2019/03/29 Javascript
如何换个角度使用VUE过滤器详解
2019/09/11 Javascript
解决layui table表单提示数据接口请求异常的问题
2019/09/24 Javascript
Vue实现base64编码图片间的切换功能
2019/12/04 Javascript
一分钟学会JavaScript中的try-catch
2020/12/14 Javascript
[02:30]辉夜杯主赛事第二日胜者组半决赛 CDEC.Y赛后采访
2015/12/26 DOTA
[50:04]DOTA2上海特级锦标赛D组小组赛#2 Liquid VS VP第二局
2016/02/28 DOTA
简单介绍Python中用于求最小值的min()方法
2015/05/15 Python
对Python3.x版本print函数左右对齐详解
2018/12/22 Python
Python写出新冠状病毒确诊人数地图的方法
2020/02/12 Python
耐克巴西官方网站:Nike巴西
2016/08/14 全球购物
StubHub澳大利亚:购买或出售您的门票
2019/08/01 全球购物
通信工程专业毕业生推荐信
2013/12/25 职场文书
市场营销专业大学生职业生涯规划文
2014/03/06 职场文书
2015年工程师工作总结
2015/04/30 职场文书
初中政治教师教学反思
2016/02/23 职场文书
2016年离婚协议书范文
2016/03/18 职场文书
MySQL的存储过程和相关函数
2022/04/26 MySQL