批量管理程序必备模块

  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='') # 连接远程主机
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='')
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='')
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='')
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)

[ Python - 13 ] 批量管理主机必备模块的更多相关文章

  1. python运维之使用python进行批量管理主机

    1. python运维之paramiko 2. FABRIC 一个与多台服务器远程交互的PYTHON库和工具 3. SSH连接与自动化部署工具paramiko与Fabric 4. Python批量管理 ...

  2. 第四百零一节,Django+Xadmin打造上线标准的在线教育平台—生产环境部署virtualenv虚拟环境安装,与Python虚拟环境批量安装模块

    第四百零一节,Django+Xadmin打造上线标准的在线教育平台—生产环境部署virtualenv虚拟环境安装,与Python虚拟环境批量安装模块 virtualenv简介 1.安装virtuale ...

  3. python数据库操作之pymysql模块和sqlalchemy模块(项目必备)

    pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 1.下载安装 pip3 install pymysql 2.操作数据库 (1).执行sql #! ...

  4. Python爬虫与数据分析之模块:内置模块、开源模块、自定义模块

    专栏目录: Python爬虫与数据分析之python教学视频.python源码分享,python Python爬虫与数据分析之基础教程:Python的语法.字典.元组.列表 Python爬虫与数据分析 ...

  5. Python之进程 2 - multiprocessing模块

    ​ 我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创建的.因此,运行起来的python程序也是一个进程,那么我们也可以在程序中再创建进程.多个进程可以实现并发效果,也就是说, ...

  6. 自学Zabbix9.4 zabbix low-level discover底层发现(zabbix批量部署必备)

    点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 自学Zabbix9.4 zabbix low-level discover底层发现(zabbix批 ...

  7. Python全栈开发【模块】

    Python全栈开发[模块] 本节内容: 模块介绍 time random os sys json & picle shelve XML hashlib ConfigParser loggin ...

  8. python学习笔记之常用模块(第五天)

    参考老师的博客: 金角:http://www.cnblogs.com/alex3714/articles/5161349.html 银角:http://www.cnblogs.com/wupeiqi/ ...

  9. Python 之路 Day5 - 常用模块学习

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

随机推荐

  1. Leetcode 672.灯泡开关II

    灯泡开关II 现有一个房间,墙上挂有 n 只已经打开的灯泡和 4 个按钮.在进行了 m 次未知操作后,你需要返回这 n 只灯泡可能有多少种不同的状态. 假设这 n 只灯泡被编号为 [1, 2, 3 . ...

  2. SpringBoot:工厂模式实现定时任务可配置

    pringBoot:工厂模式实现定时任务可配置 需要:使用springboot,实现定时任务可配置. 定时任务可在代码中写死,在配置文件中配置,这些都不能实现定时任务在服务器不重启的情况下可配置. 为 ...

  3. spring mvc:实现给Controller函数传入list<pojo>参数

    [1]前端js调用示例: ...insertStatisData?statisDatas=[{'cid':'2','devId':'9003','deviceName':'测试名','endTime' ...

  4. BZOJ 4031 HEOI2015 小Z的房间 基尔霍夫矩阵+行列式+高斯消元 (附带行列式小结)

    原题链接:http://www.lydsy.com/JudgeOnline/problem.php?id=4031 Description 你突然有了一个大房子,房子里面有一些房间.事实上,你的房子可 ...

  5. 软件工程项目组Z.XML会议记录 2013/09/18

    软件工程项目组Z.XML会议记录 [例会时间]2013年9月18日周三21:00-23:00 [例会形式]小组讨论 [例会地点]三号公寓楼会客厅 [例会主持]李孟 [会议记录]毛宇 会议整体流程 一. ...

  6. 点击查看大图Activity

    1.使用方式 Intent intent = new Intent(FriendCircleActivity.this, ImageGralleryPagerActivity.class);//0,索 ...

  7. Uva 1590 IP Networks

    这道题目是一道关于IP地址的题目,要深入理解这道题需要有一定的网络基础. 这道题目我第一次做的时候虽然也AC了,但代码写的比较复杂,不够精炼.近期刚刚参加了网络方面的培训,在有一定知识的基础上,又重写 ...

  8. io学习-相关文章

    文章:IO编程 地址:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143 ...

  9. 【SQLAlchemy】SQLAlchemy技术文档(中文版)(中)

    10.建立联系(外键) 是时候考虑怎样映射和查询一个和Users表关联的第二张表了.假设我们系统的用户可以存储任意数量的email地址.我们需要定义一个新表Address与User相关联. from ...

  10. Citrix Netscaler版本管理和选择

    Citrix Netscaler版本管理和选择 来源 http://blog.51cto.com/caojin/1898164 随着Citrix Netscaler的快速发展,有很多人在维护设备时经常 ...