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

python远程批量执行

    我并不是一个专业的开发,我一直在学习linux运维,对于python也是接触不久,所以代码写的并不是很规范简洁。

    前段时间一个同学找我一起做一个自动化运维平台,我对python的django还没有了解,并且对于HTML和JS这类开发学习还没有涉及,所以我说我做些后台的实现,前端就交给我的同学做。不扯淡了,下面说下我做批量执行的思路。

  1. 用到的模块:paramiko
  2. 功能:很简单就是批量执行命令,类似于ansible,本来想用Fabric,但是想一想还是用paramiko,因为我在学习ansible,ansible里面就有paramiko。后期还要将配置文件里面的主机组放到数据库里面。这里我想使用的mongodb,因为我的主机配置文件写的是字典的形式,保存在文档数据库中更为方便些。
  3. 配置文件格式:这里为了方便获取信息,直接写成了字典的形式,本来前期想用pickle模块进行序列化输入到文件中,但是后来发现如果主机要是多的话,手动输入还是太麻烦了。
  4. 类:为了后期更好的添加功能,我直接将paramiko的SSHClient写成了类。后面要添加上传文本,下载等功能,这就用到了SFTP的功能。
  5. 函数:这里面的函数就是对文件进行条件输出,找到符合的主机组名称。
  6. 讲解下paramiko:paramiko模块在我理解就是依赖ssh远程的一个模块。

    (1)、paramiko安装方式:使用pip安装即可。

    (2)、paramiko核心组件-----SSHClient

           SSHClient使用ssh的通道实现和主机的连接和命令执行。

           

SSHClient中的方法 参数和参数说明
connect(实现ssh连接和校验)

hostname:目标主机地址

port:主机端口

username:校验的用户名

password:登录密码

pkey:私钥方式身份验证

key_filename:用于私钥身份验证的文件名

timeout:连接超时设置

allow_agent:这是布尔型,设置False的时候禁止使用ssh代理

look_for_keys:也是布尔型,禁止在.ssh下面找私钥文件

compress:设置压缩

exec_command(远程执行命令)

stdin,stdout,stderr:这三个分别是标准输入、输出、错误,用来获取命令执行结果,并不算方法的参数

command:执行命令的字符串,带双引号。

bufsize:文件缓冲大小,默认为1

 

load_system_host_keys(加载本地的公钥文件) filename:指定远程主机的公钥记录文件
set_missing_host_key_policy(远程主机没有密钥)

AutoAddPolicy:自动添加主机名和主机密钥到本地的HostKeys对象

RejectPolicy:自动拒绝未知的主机名和密钥(默认)

WarningPolicy:接受未知主机,但是会有警告

             (3)paramiko的核心组件SFTPClient类

                     实现远程文件的操作,比如上传、下载、权限、状态等。

SFTPClient类的方法 参数和参数说明
from_transport(使用一个已经通过已经连通的SFTP客户端通道) t:使用的是已经验证过的传输对象
 put(上传本地文件到SFTP服务器)

localpath:本地文件的路径

remotepath:远程路径

callback:获取已接收的字节数和总传输的字节数

confirm:文件上传完毕后是否调用stat()方法,确定文件大小

 get(从SFTP服务器上下载文件到本地)

 remotepath:需下载的文件路径

localpath:保存本地的文件路径

callback:和put的一样。

 mkdir:简历目录

remove:删除

rename:重命名

stat:获取远程文件信息

listdir:获取指定目录列表

 
    (4)、还有个invoke_shell的用法经常使用
invoke_shell(*args, **kwds)

Request an interactive shell session on this channel. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the shell.

Normally you would call get_pty before this, in which case the shell will operate through the pty, and the channel will be connected to the stdin and stdout of the pty.

When the shell exits, the channel will be closed and can’t be reused. You must open a new channel if you wish to open another shell.

在这个通道请求一个交互式的shell会话,如果服务允许,这个通道将会直接连接标准输入、标准输入和错误的shell,通常我们会在使用它之前调用get_pty的用法,这样shell会话是通过伪终端处理的,并且会话连接标准输入和输出,当我们shell退出的时候,这个通道也会关闭,并且能再次使用,你必修重新开另一个shell。

 

    (4)实践堡垒机(摘自刘天斯老师的《python自动化运维》)
#定义服务器信息
hostname = "192.168.0.158"
username = "root"
password = "aixocm"

#定义登录日志和密码提示符
port = 22
passinfo = '\'s password:'
paramiko.util.log_to_file('syslogin.log')

#登录堡垒机,自动添加hostkeys信息到主机
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=blip,username=bluser,password=blpasswd)

#创建会话
channel = ssh.invoke_shell()
channel.settimeout(100)

#通道执行shell的ssh连接
buff = ''
resp = ''
channel.send('ssh '+username+'@'+hostname+'\n')
while not buff.endswith(passinfo):
   try:
       resp = channel.recv(9999)
   except Exception,e:
       print 'Error info:%s connection time.' % (str(e))
       channel.close()
       ssh.close()
       sys.exit()
   buff += resp
   if not buff.find('yes/no') == -1:
       channel.send('yes\n')
       buff = ''

channel.send(password+'\n')

buff = ''
while not buff.endswith('# '):
    resp = channel.recv(9999)
    if not resp.find(passinfo) == -1:
       print 'Error info:Authentication failed.'
       channel.close()
       ssh.close()
                                                                       
View Code

 

  1. 配置文件:代码:

 

{"hostname":"web","host_ip":["192.168.0.157","192.168.0.158","192.168.0.159"]}

 

类:#!/usr/bin/env pyth#coding:utf-8import paramiko

class action(object):
    def __init__(self, IP, username, command):
       self.IP = IP
       self.username = username
       self.command = command

    def ssh_connect(self):
      ssh = paramiko.SSHClient()
      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
            ssh.connect(hostname=self.IP, username=self.username)
            stdin,stdout,stderr=ssh.exec_command(self.command)
            print "######################> %s <####################" %(self.IP)
            print stderr.read()
            print stdout.read()
            ssh.close()

except Exception,e: print "######################> %s <####################" %(self.IP) print

执行主函数:

from simple1 import action
def
get_values(hostname): conf_file=open('scn.conf','r') lines = conf_file.readlines() for line in lines: line = line.strip("\n") line = eval(line) if hostname == line["hostname"]: return(line) break conf_file.close() if __name__ == "__main__": hostname = raw_input("write your hostname:") username = raw_input("write your username:") command = raw_input("write your excute command:") host = get_values(hostname) host_ip = list(host["host_ip"]) for i in range(0,len(host_ip)): conn = action(host_ip[i],username,command) conn.ssh_connect()

注意这里面我没有添加password和port,port默认使用的ssh的22号端口,password我直接使用ssh-keygen和ssh-copy-id进行无密码登录。

 

 

posted on 2017-03-13 11:40  循序渐进IT  阅读(18395)  评论(0编辑  收藏  举报

导航