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程序员开发中常犯的10个错误
Jul 07 Python
Python中处理字符串的相关的len()方法的使用简介
May 19 Python
在Linux系统上通过uWSGI配置Nginx+Python环境的教程
Dec 25 Python
python中set()函数简介及实例解析
Jan 09 Python
python隐藏终端执行cmd命令的方法
Jun 24 Python
Python with用法:自动关闭文件进程
Jul 10 Python
tensorflow 只恢复部分模型参数的实例
Jan 06 Python
Python多进程multiprocessing、进程池用法实例分析
Mar 24 Python
关于python tushare Tkinter构建的简单股票可视化查询系统(Beta v0.13)
Oct 19 Python
python实现自定义日志的具体方法
May 28 Python
深入理解python协程
Jun 15 Python
仅用几行Python代码就能复制她的U盘文件?
Jun 26 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 三维饼图的实现代码
2008/09/28 PHP
php array_unique之后json_encode需要注意
2011/01/02 PHP
php 人员权限管理(RBAC)实例(推荐)
2017/05/24 PHP
Laravel 6.2 中添加了可调用容器对象的方法
2019/10/22 PHP
js调试工具 Javascript Debug Toolkit 2.0.0版本发布
2008/12/02 Javascript
用Mootools获得操作索引的两种方法分享
2011/12/12 Javascript
JS使用getComputedStyle()方法获取CSS属性值
2014/04/23 Javascript
js取模(求余数)隔行变色
2014/05/15 Javascript
javascript学习笔记(六)数据类型和JSON格式
2014/10/08 Javascript
js获取UserControl内容为拼html时提供方便
2014/11/02 Javascript
SyntaxHighlighter 3.0.83使用笔记
2015/01/26 Javascript
高性能JavaScript循环语句和条件语句
2016/01/20 Javascript
JavaScript下拉菜单功能实例代码
2017/03/01 Javascript
JS实现的DOM插入节点操作示例
2018/04/04 Javascript
详解vue-cli 本地开发mock数据使用方法
2018/05/29 Javascript
vue中filters 传入两个参数 / 使用两个filters的实现方法
2019/07/15 Javascript
详解vuejs中执行npm run dev出现页面cannot GET/问题
2020/04/26 Javascript
vue实现图片上传到后台
2020/06/29 Javascript
javascript实现下拉菜单效果
2021/02/09 Javascript
跟老齐学Python之编写类之四再论继承
2014/10/11 Python
详解使用python的logging模块在stdout输出的两种方法
2017/05/17 Python
对Pyhon实现静态变量全局变量的方法详解
2019/01/11 Python
用Python识别人脸,人种等各种信息
2019/07/15 Python
Python线程指南分享
2019/11/19 Python
详解pyinstaller生成exe的闪退问题解决方案
2020/06/19 Python
HTML5 device access 设备访问详解
2018/05/24 HTML / CSS
运动会领导邀请函
2014/02/05 职场文书
办公室主任职责范本
2014/03/07 职场文书
工作散漫检讨书
2014/09/16 职场文书
学校党委副书记个人对照检查材料思想汇报
2014/09/28 职场文书
毕业生的自我鉴定表范文
2019/05/16 职场文书
小学语文的各类谚语(70首)
2019/08/15 职场文书
详解Html5项目适配系统深色模式方案总结
2021/04/14 HTML / CSS
Python pandas读取CSV文件的注意事项(适合新手)
2021/06/20 Python
《吸血鬼:避世 血猎》官宣4.27发售 系列首款大逃杀
2022/04/03 其他游戏
Elasticsearch 批量操作
2022/04/19 Python