欢迎来到李先生的博客

深山的鹿,不知归处;万般皆苦,只可自渡。
扩大
缩小

Python3结合paramiko执行命令

使用默认的方式(2017年写的版本)

1、最简单的使用paramiko登录远程机器执行一些命令,学习实验楼的paramiko记录下来,第一次使用ConfigParser这个库,对于封装这些还是不太熟悉,只能慢慢来,嘿嘿嘿

 

这是python脚本文件,还有一个变量文本

import paramiko
import ConfigParser

class ParamikoClient:
    def __init__(self,config_str):
        self.config = ConfigParser.ConfigParser()
        self.config.read(config_str)

        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    def connet(self):

        try:
            self.client.connect(hostname=self.config.get('ssh','host'),port=self.config.getint('ssh','port'),username=self.config.get('ssh','username'),password=self.config.get('ssh','password'))
        except Exception,e:
            print e
            try:
                self.client.close()
            except:
                pass
    def run_cmd(self,cmd_str):
            stdin, stdout, stderr = self.client.exec_command(cmd_str)
            print stdout.read()

client = ParamikoClient('config.ini')
client.connet()
client.run_cmd('date')

 

config.ini文件

[ssh]
host = 192.168.1.101
port = 22
username = root
password = 123456

 

 

使用自定义秘钥实现远程登录执行命令(2019年9月版本)

 1、代码如下

import paramiko

'''
Author: LiLe
Date: 20190905
Version: V2.0
Contact: 15274326058
Description: Paramiko库登录远程主机执行命令并返回结果
Document: http://docs.paramiko.org/en/2.6/
'''


class ParamikoClient:
    def __init__(self, config):
        self.host = config['host']
        self.port = config['port']
        self.username = config['username']
        self.key = config['key']

    # 连接
    def connects(self):
        try:
            # 使用自定义秘钥
            private_key = paramiko.RSAKey.from_private_key_file(self.key)
            self.client = paramiko.SSHClient()
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.client.connect(hostname=self.host, port=self.port, username=self.username,pkey=private_key)
        except Exception as err:
            print(err)

    # 关闭
    def close(self):
        try:
            self.client.close()
        except:
            pass

    # 执行命令
    def exec_command(self, cmd):
        stdin, stdout, stderr = self.client.exec_command(cmd)
        return stdout.read()


if __name__ == '__main__':
    paramiko_config = {
        'host': '10.*.*.*',
        'port': 22,
        'username': 'lile',
        'key': 'lile.pem',
    }

    paramik = ParamikoClient(paramiko_config)
    paramik.connects()
    result = paramik.exec_command("date")
    print(result)
    paramik.close()

 

注意事项

1、有时候执行ifconfig等命令时,返回的值为空值

原因:ifconfig等命令需要写全路径,把环境变量也加上

paramik.exec_command("/sbin/ifconfig eth0 |grep inet |awk -F' ' '{print $2}'")

 

posted on 2017-04-15 18:12  Captain_Li  阅读(920)  评论(0编辑  收藏  举报

导航