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,远程,执行,命令


猜你喜欢
MySQL无法存储Emoji表情问题的解决方法分析
2024-01-22 00:32:13

python之tensorflow手把手实例讲解猫狗识别实现
2021-12-26 14:46:11

深入浅出SQL之左连接、右连接和全连接
2009-08-30 15:14:00
numpy.random.choice()函数详解
2023-04-30 09:46:03
MySQL 函数索引的优化方案
2024-01-23 03:13:36
Python自动化测试笔试面试题精选
2021-05-17 03:32:59
python批量解压zip文件的方法
2022-08-26 16:20:00
php的ajax框架xajax入门与试用介绍
2023-09-27 14:46:16
Yolov5多边形标签和JSON数据格式转换
2023-11-06 17:31:24

python 获得任意路径下的文件及其根目录的方法
2022-02-02 17:32:15
MySQL表的重命名字段添加及字段属性修改操作语法
2024-01-21 07:18:35
python和pywin32实现窗口查找、遍历和点击的示例代码
2023-04-06 19:01:23
Python实现对中文文本分段分句
2022-09-16 18:16:50
PyTorch 中的 torch.utils.data 解析(推荐)
2021-09-14 01:58:16
python3 中使用urllib问题以及urllib详解
2022-01-09 05:59:16
Python基于ImageAI实现图像识别详解
2023-06-11 14:04:49
浅谈LogMiner的使用方法
2009-02-28 11:12:00
Python实用日期时间处理方法汇总
2022-10-21 03:07:48
PHP中获取文件创建日期、修改日期、访问时间的方法
2023-06-11 18:37:15
浅谈如何重构冗长的Python代码
2021-11-13 05:48:27