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)

参考 http://www.developerq.com/article/1493123866

报错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",和前面必须不能有空格等其他字符,确保密码正确

				
时间: 2024-08-09 11:39:41

python 采用paramiko 远程执行命令的相关文章

python之paramiko 远程执行命令

有时会需要在远程的机器上执行一个命令,并获得其返回结果.对于这种情况,python 可以很容易的实现. 1 .工具 Python paramiko 1) Paramiko模块安装 在Linux的Terminal中,直接输入pip install paramiko 命令安装. 2)确定paramiko安装成功 在python命令行输入import paramiko,确认是否安装成功,没报错就没问题. 2.步骤 1 .导入 paramiko 模块 #!/usr/bin/python import p

python 实现ssh远程执行命令 上传下载文件

使用密码远程执行命令 [[email protected] script]# cat daramiko_ssh.py  #!/usr/bin/env python #_*_coding:utf-8 _*_ __author__ = 'gaogd' import paramiko import sys,os host = sys.argv[1] user = 'root' password = 'ddfasdsasda2015' cmd = sys.argv[2] s = paramiko.SSH

使用paramiko远程执行命令、下发文件

写部署脚本时,难免涉及到一些远程执行命令或者传输文件. 之前一直使用 "sh" 库,调用sh.ssh远程执行一些命令,sh.scp传输文件,但是实际使用中还是比较麻烦的,光是模拟用户登陆这一点,还需要单独定义方法模拟输入. 感受一下: 来自 "官方文档" 后来发现 "paramiko" 库更加优雅. http://pic.cnhubei.com/space.php?uid=4593&do=album&id=1083522http:

python 网络编程(远程执行命令与粘包)

远程执行命令 先来学习一个新模块 , 一会用到的.. 新模块: subprocess 执行系统命令 r = subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE) subprocess.Popen(a,b,c,d) a: 要执行的系统命令(str) b: shell = True 表示确定我当前执行的命令为系统命令 c: 表示正确信息的输出管道 d: 表示错误信息的输出管道 下边直接上代码,

python模块paramiko的上传下载和远程执行命令

#!/usr/bin/python # -*- coding: utf-8 -*- import paramiko,os,datetime server_ip = '192.168.1.123' server_user = 'root' server_passwd = '10241010' server_port = 22 #local_dir='C:\Python27' #remote_dir='/soft2/nba/' def ssh_connect(): ssh = paramiko.SS

python之实现批量远程执行命令(堡垒机)

python远程批量执行 我并不是一个专业的开发,我一直在学习linux运维,对于python也是接触不久,所以代码写的并不是很规范简洁. 前段时间一个同学找我一起做一个自动化运维平台,我对python的django还没有了解,并且对于HTML和JS这类开发学习还没有涉及,所以我说我做些后台的实现,前端就交给我的同学做.不扯淡了,下面说下我做批量执行的思路. 用到的模块:paramiko 功能:很简单就是批量执行命令,类似于ansible,本来想用Fabric,但是想一想还是用paramiko,

远程执行命令:paramiko

paramiko模块用于通过 ssh 登录到远程客户端主机并执行命令,常见用法如下: [[email protected] ~]$ yum install -y python-paramiko 通过用户名密码登录远程客户端主机并执行命令: #!/usr/bin/env python #-*- coding:utf-8 -*- import paramiko ssh = paramiko.SSHClient() # 创建一个ssh客户端对象 ssh.set_missing_host_key_pol

Zabbix远程执行命令

原文发表于cu:2016-06-14 Zabbix触发器(trigger)达到阀值后会有动作(action)执行:发送告警信息或执行远程命令. 本文主要配置验证zabbix执行远程命令. 一.环境 Server:基于CentOS-7-x86_64-1511: Zabbix:zabbix-3.0.1server/agent. 二.注意事项 一些能想到的比较重要的注意事项: 远程执行命令是server端向agent端执行,不支持主动模式的agent: 不支持代理模式: zabbix用户必须对命令具有

day8-套接字sock 实现SSH远程执行命令功能

复习 #面向对象编程#类:#对象#实例化 :从一个类到产生一个对象的过程    #对象 = 类名()   #__init__初始化方法,是为了给一个具体的对象放一些初识的属性#在类中:    # 静态属性 直接定义在类中的属性,使用静态属性:类名.对象名都可以调用    # 动态属性 就是方法 就是定义在类中的函数 默认传一个self# class Person:#     money = 100# sister = Person()# father = Person()# Person.mon