[ Python - 13 ] 批量管理主机必备模块
批量管理程序必备模块
- optparse
- configparser
- 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 ] 批量管理主机必备模块的更多相关文章
- python运维之使用python进行批量管理主机
1. python运维之paramiko 2. FABRIC 一个与多台服务器远程交互的PYTHON库和工具 3. SSH连接与自动化部署工具paramiko与Fabric 4. Python批量管理 ...
- 第四百零一节,Django+Xadmin打造上线标准的在线教育平台—生产环境部署virtualenv虚拟环境安装,与Python虚拟环境批量安装模块
第四百零一节,Django+Xadmin打造上线标准的在线教育平台—生产环境部署virtualenv虚拟环境安装,与Python虚拟环境批量安装模块 virtualenv简介 1.安装virtuale ...
- python数据库操作之pymysql模块和sqlalchemy模块(项目必备)
pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 1.下载安装 pip3 install pymysql 2.操作数据库 (1).执行sql #! ...
- Python爬虫与数据分析之模块:内置模块、开源模块、自定义模块
专栏目录: Python爬虫与数据分析之python教学视频.python源码分享,python Python爬虫与数据分析之基础教程:Python的语法.字典.元组.列表 Python爬虫与数据分析 ...
- Python之进程 2 - multiprocessing模块
我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创建的.因此,运行起来的python程序也是一个进程,那么我们也可以在程序中再创建进程.多个进程可以实现并发效果,也就是说, ...
- 自学Zabbix9.4 zabbix low-level discover底层发现(zabbix批量部署必备)
点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 自学Zabbix9.4 zabbix low-level discover底层发现(zabbix批 ...
- Python全栈开发【模块】
Python全栈开发[模块] 本节内容: 模块介绍 time random os sys json & picle shelve XML hashlib ConfigParser loggin ...
- python学习笔记之常用模块(第五天)
参考老师的博客: 金角:http://www.cnblogs.com/alex3714/articles/5161349.html 银角:http://www.cnblogs.com/wupeiqi/ ...
- Python 之路 Day5 - 常用模块学习
本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...
随机推荐
- python 生成csv乱码问题解决方法
需求背景 最近为公司开发了一套邮件日报程序,邮件一般就是表格,图片,然后就是附件.附件一般都是默认写到txt文件里,但是PM希望邮件里的附件能直接用Excel这种软件打开,最开始想保存为Excel,但 ...
- HTML文档插入JS代码的几种方法
在HTML文档里嵌入客户端JavaScript代码有4中方法: 1.内联,放置在< script>和标签对之间. 2.放置在由< script>标签的src属性指定的外部文件中 ...
- 【Linux】如何设置Linux开机 ,默认进入图形界面或命令行界面?
原创链接: https://blog.csdn.net/prophet10086/article/details/78501019 [7版本] 在root用户权限下: 查看当前启动模式 systemc ...
- MYSQL 服务无法启动,错误日志:InnoDB: .\ibdata1 must be writable
这几天安装MYSQL 5.7版本的时候,出现了服务无法启动的问题,尝试了各种修改配置文件my.ini的方法都不行,查看到错误日志,一般错误日志在C:\Program Files\MySQL\MySQL ...
- JavaScript页面跳转
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding=& ...
- sql数值比较
- Python 类和对象-上
#类和对象 class Human: #属性 -> 成员属性(变量) ear = 2 mouth = 1 sex = 'man' age = 28 name = 'zhangwang' marr ...
- CF115B Lawnmower
题目描述 You have a garden consisting entirely of grass and weeds. Your garden is described by an n×mn×m ...
- 51nod1254 最大子段和 V2 DP
---题面--- 题解: 表示今天做题一点都不顺.... 这题也是看了题解思路然后自己想转移的. 看的题解其实不是这道题,但是是这道题的加强版,因为那道题允许交换k对数. 因为我们选出的是连续的一段, ...
- Idea 怎么远程debug
注意的问题:远程debug别人的服务器只能开一个debug,所以当你的同事比你先远程debug同一台服务器时,你应该报Error running 某某ip地址 .unable to open debu ...