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

作者:百变小超 时间:2021-01-23 19:17:16 

这篇文章主要介绍了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",和前面必须不能有空格等其他字符,确保密码正确

来源:https://www.cnblogs.com/dasheng-maritime/p/7606266.html

标签:python,paramiko,远程,执行,命令
0
投稿

猜你喜欢

  • 一个较复杂的字符串截取函数

    2009-11-02 10:45:00
  • php线性表顺序存储实现代码(增删查改)

    2023-11-19 06:51:53
  • 用书的概念理解小网站结构

    2007-10-31 18:08:00
  • python将每个单词按空格分开并保存到文件中

    2023-07-01 12:46:31
  • INSERT INTO SELECT语句与SELECT INTO FROM语句的一些区别

    2012-06-06 19:38:28
  • BOF、EOF 属性

    2009-05-11 12:37:00
  • asp精妙的SQL语句例子

    2008-03-04 17:42:00
  • 基于python实现把json数据转换成Excel表格

    2021-02-20 05:22:04
  • golang如何通过viper读取config.yaml文件

    2023-07-22 05:46:11
  • 面向站长和网站管理员的Web缓存加速指南[翻译]

    2008-04-22 21:04:00
  • JavaScript能判定两个function等价吗?

    2009-08-13 14:45:00
  • PHP设计模式(八)装饰器模式Decorator实例详解【结构型】

    2023-11-24 05:59:31
  • 详解Python装饰器

    2023-11-12 12:40:06
  • 简单form标准化实例——整体布局

    2007-05-11 17:04:00
  • java-jsp springmvc-controller 传值到页面的方法

    2023-06-16 18:19:52
  • 探讨php中防止SQL注入最好的方法是什么

    2023-09-11 14:20:48
  • python-httpx的具体使用

    2023-08-12 00:25:53
  • 一段查看ASP文件源码的ASP程序

    2007-09-21 12:53:00
  • python命令行参数argparse模块基本用法详解

    2023-07-31 03:14:21
  • python GUI库图形界面开发之PyQt5拖放控件实例详解

    2023-04-26 08:43:24
  • asp之家 网络编程 m.aspxhome.com