[ Python

批量管理程序必备模块  

  1. optparse
  2. configparser
  3. paramiko

optparse模块

    简介:
        optparse模块主要用来为脚本传递命令参数功能

    使用步骤:

        1. import optparse
        2. parser = optparse.OptionParser()
        3. parser.add_option()
        4. options, args = parser.parse_args(command) # command 为 list 类型

    方法add_option()中参数:
        action: 验证输入数据类型是否和type匹配,并将符合要求的这个参数存储到dest变量中
        store 默认值
            store_true
            store_false
                标记而已,辅助流程控制。
        
        type: 指定是对应于参数类型,如-f,-n 接下来参数的数据类型,可以为int, string, float等
        dest: 用于保存临时变量,其值可以作为options的属性进行访问,很方便。
        help: 提供帮助解释
        default: 为dest设置默认值

#!_*_coding:utf-8_*_
# Author: hkey
import optparse
parser = optparse.OptionParser()
cmd = ['--cmd', 'du -sh', '/'] # 命令必须通过split方法转换为list类型
parser.add_option('--cmd', action='store', type='string', dest='command', help='command')
options, args = parser.parse_args(cmd)
print('options:', options)
print('args:', args)
print('command:', options.command)        


输出信息:
options: {'command': 'du -sh'}
args: ['/']
command: du -sh

使用default默认值:

import optparse
parser = optparse.OptionParser()
cmd = ['--cmd', 'du -sh', '/'] 
parser.add_option('--cmd', action='store', type='string', dest='command', default='abc', help='command') # 为dest添加默认值
options, args = parser.parse_args()  # 没有传入cmd参数
print('options:', options)
print('args:', args)
print('command:', options.command)


输出信息:
options: {'command': 'abc'}
args: []
command: abc

configparser模块

    简介:
        读写ini格式的配置文件
   

   使用步骤:

        1. import configparser
        2. config = configparser.ConfigParser()
        3. config.read('配置文件')
        4. config (get or set)

hosts.cfg

#hosts.cfg

[host1]
ip = 192.168.118.10
port = 22
username = user
password = 123456

[host2]
ip = 192.168.118.11
port = 22
username = root
password = 123456

[group]
server = host1,host2

[host3]
ip = 192.168.118.12
#!_*_coding:utf-8_*_
# Author: hkey
import configparser
config = configparser.ConfigParser()

# 读取配置文件
config.read('hosts.cfg')
sections = config.sections() # 获取配置文件所有的sections
options = config.options('host1')   # 获取host1下所有的key值
values = config['host1']['username'] # 通过sections和key获取values
print(sections)
print(options)
print(values)
# 写入配置文件
config.set("host1", "username", "user") # 将sections为'host1'且key为'username'的值修改为user
config.add_section('host3')     # 新增一个sections
config.set('host3', 'ip','192.168.118.12') # 在sections为host3下面增加key为host3,值为'192.168.118.12'
config.write(open('hosts.cfg', 'w'))    # 写回配置文件

paramiko模块

    简介:
        提供了ssh及sftp进行远程登录服务器执行命令和上传下载文件的功能,这是第三方包,使用前需要安装.
        安装 pip install paramiko        

    远程ssh使用步骤:

        1. import paramiko
        2. ssh = paramiko.SSHClient() 
        3. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 允许将信任的主机自动加入到host_allow列表,此方法必须放在connect方法的前面
        4. ssh.connect(hostname='ip', port=22, username='root', password='123456') # 连接远程主机
        5. stdin, stdout, stderr = ssh.exec_command('df -Th')    # 在远程主机执行命令
        6. res, err = stdout.read(), stderr.read()    # 执行成功,stdout接收,错误, stderr接收
        7. result = res if res else err     # 三元运算判断
#!_*_coding:utf-8_*_
# Author: hkey
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.118.10', port=22, username='root', password='123456')
stdin, stdout, stderr = ssh.exec_command('df -Th')
res, err = stdout.read(), stderr.read()
result = res if res else err
print(result.decode())    # 输出信息是二进制格式需要转换


输出结果:
Filesystem               Type      Size  Used Avail Use% Mounted on
/dev/mapper/vg00-lv_root xfs        92G  2.6G   89G   3% /
devtmpfs                 devtmpfs  3.9G     0  3.9G   0% /dev
tmpfs                    tmpfs     3.9G     0  3.9G   0% /dev/shm
tmpfs                    tmpfs     3.9G   17M  3.9G   1% /run
tmpfs                    tmpfs     3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/vda1                xfs       497M  125M  373M  25% /boot
tmpfs                    tmpfs     783M     0  783M   0% /run/user/0

    sftp上传下载使用步骤:

        1. import paramiko
        2. transport = paramiko.Transport(('ip', 22))
        3. transport.connect(username='root', password='123456')
        4. sftp = paramiko.SFTPClient.from_transport(transport)
        5. sftp.put('abc.txt', '/tmp/abc.txt')     # 将本地abc.txt 上传至 /tmp/abc.txt 这里要注意必须要写文件名,不然会报错。
        6. transport.close()
#!_*_coding:utf-8_*_
# Author: hkey
import paramiko
transport = paramiko.Transport(('192.168.118.10', 22))
transport.connect(username='root', password='123456')
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put('abc.txt', '/tmp/abc.txt')
transport.close()


最后一个完整的例子,使用到上面三个模块实现一个批量执行命令的脚本:

#!_*_coding:utf-8_*_
# Author: hkey


import optparse, configparser, paramiko
cmd = ['batch_run', '-H', 'h1,h2', '-g', 'server,g1', '--cmd', 'df -Th /']
parser = optparse.OptionParser()
parser.add_option('-H', dest='host', help='host')
parser.add_option('-g', dest='group', help='group')
parser.add_option('--cmd', dest='cmd', help='cmd')

options, args = parser.parse_args(cmd)

if args or args[0] == 'batch_run':
    if options.host is not None or options.group is not None or options.cmd is not None:
        host = options.host.split(',')
        # print(host)
        group = options.group.split(',')
        # print(group)
        config = configparser.ConfigParser()
        config.read('hosts.cfg')
        for i in group:
            if i not in config['group']:
                print('未找到[%s]' %i)
                group.remove(i)
        host_list = []
        host_list1 = []
        for i in group:
            s = config['group'][i]
            s = s.split(',')
        host_list = host + s
        sections = config.sections()
        del sections[-1]
        for i in host_list:
            if i in sections:
                host_list1.append(i)
            else:
                print('找不到主机[%s]' %i)
                continue
        host_dict = {}
        for i in host_list1:
            host_dict[i] = {
                'ip': config[i]['ip'],
                'port': config[i]['port'],
                'username': config[i]['username'],
                'password': config[i]['password'],
            }

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        for i in host_dict:

            ssh.connect(hostname=host_dict[i]['ip'], port=int(host_dict[i]['port']),
                        username=host_dict[i]['username'], password=host_dict[i]['password'])
            stdin, stdout, stderr = ssh.exec_command(options.cmd)
            res, err = stdout.read(), stderr.read()
            result = res if res else err
            print('[%s]'.center(50, '-') % host_dict[i]['ip'])
            print(result.decode())
    else:
        print('找不到命令:[%s]' % args)
原文地址:https://www.cnblogs.com/hukey/p/7275033.html