python 采用paramiko 远程执行命令及报错解决
作者:百变小超 发布时间:2021-01-23 19:17:16
标签:python,paramiko,远程,执行,命令
这篇文章主要介绍了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


猜你喜欢
- 1.socket黏包问题原理黏包:指数据与数据之间没有明确的分界线,导致不能正确的读取数据。应用数据想要发送数据就必须将数据交给操作系统,而
- 简介这是一个操作数据库(sqlite3)的项目,用PyQt5进行界面封装。此次项目最主要的是,主界面与子界面的交互,一个主界面与三个子界面交
- 尽管XML还处在开发阶段,其标准正在由W3C组织制定,但是已经有许多公司表示全力支持XML,并开发了不少XML工具。Adobe公司的Fram
- scrollHeight: 获取对象的滚动高度。 scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离 sc
- 曾经遇过,差点抓狂,有装MSSQL的朋友,赶紧试一下,删除以下的组件.当然,前提是你要把自己的数据库搞定后再去删除,否则组件删除后很多功能不
- cmake-2.8.3.tar.gzmysql-5.5.8.tar.gz一,cmake-2.8.3的安装:tar -zxf cmake-2.
- 问题Jupyter Notebook可以说是非常好用的小工具,但是不经过配置只能够在本机访问笔者参阅了文档对jupyter notebook
- 本文为大家分享了python实现大音频文件语音识别功能的具体代码,供大家参考,具体内容如下实现思路:先用ffmpeg将其他非wav格式的音频
- 背景有时本地服务器的时间不准了,需要同步互联网上的时间。解决方案NTP时间同步,找到一些可用的NTP服务器进行同步即可。通过获取一些大型网站
- 一、效果快放10倍总共分为三部分,左上角的正文,下方的心形和右下角的署名特别需要注意的一点是这种东西不但要装Python,还与分辨率有关(换
- 茎叶图from itertools import groupbynums2=[225, 232,232,245,235,245,270,22
- 经过一个阶段的asp学习,下面我们结合所学过的内容建立一个最简单的聊天室,虽然很简单,但是大家可以通过他来掌握一个聊天室建立的基本过程,并且
- 简介主要是尝试简单的使用pyhton的爬虫功能,于是使用有道进行尝试,并没有进行深入的诸如相关api的调用。以下是需要的POST数据代码以下
- 区别:xx:公有变量,所有对象都可以访问;xxx:双下划线代表着是系统定义的名字。__xxx:双前置下划线,避免与子类中的属性命名冲突,无法
- 1、es的批量插入这是为了方便后期配置的更改,把配置信息放在logging.conf中用elasticsearch来实现批量操作,先安装依赖
- 大家好,在之前的文章中详细介绍了time和datetime模块的使用。这两个模块更多的是用于处理时间和日期相关的问题。本文介绍的是第三个模块
- Python中的数据类型共有六个,分别是:字符串,数字,布尔类型,列表,元祖,字典,集合其中分为可变的类型和不可变的:可变类型:列表,字典,
- 1、并双击新建工程窗口中ActiveX DLL图标,VB将自动为项目添加一个类模块,并将该项目类型设置为ActiveX DLL。2、在属性窗
- 本文实例讲述了Python 网络编程之TCP客户端/服务端功能。分享给大家供大家参考,具体如下:demo.py(TCP客户端):import
- 随着当今世界的发展,计算机视觉技术的应用越来越广泛。伴随着硬件设备的不断升级,构造复杂的计算机视觉应用变得越来越容易了。OpenCV像是一个