一、场景概述
刚入职新公司的第3天,接到任务说需要获取100多台物理服务器的信息,其中有:主机名、IP地址、磁盘数量,磁盘设备编号。悲催的是现有的生产环境没有任何可用的工具去做这个事情,本想用Ansible去搞,但因对ansible还不是很熟悉,因此决定徒手撸一个脚本来实现,所以呢才有了此脚本的诞生。
二、脚本的基本思路
1、python pexpect模块,用该模块来实现ssh连接
2、连接后在远程主机跑相关命令
3、返回结果
4、返回的结果随便你怎么处理,可视化也好,分析也好,存储到数据库也行
三、代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#!/usr/bin/env python
#Describe:
# Gets the physical hard disk number of each host
#Author: Tantianran
#Email: 996298929@qq.com
#time: 2016-10-09 17:28
# -*- coding: utf-8 -*-
import
pexpect
def
ssh_cmd(ip,shell_cmd):
passwd
=
'1qaz#EDC'
ssh
=
pexpect.spawn(
'ssh root@%s "%s"'
%
(ip, shell_cmd))
try
:
i
=
ssh.expect([
'password:'
,
'continue connecting (yes/no)?'
], timeout
=
5
)
if
i
=
=
0
:
ssh.sendline(passwd)
elif
i
=
=
1
:
ssh.sendline(
'yes\n'
)
ssh.expect(
'password: '
)
ssh.sendline(passwd)
ssh.expect(
'#'
)
ssh.sendline(shell_cmd)
ssh.expect(
'#'
)
except
pexpect.EOF:
data
=
ssh.before
#读取shell命令运行的结果
ssh.close()
except
pexpect.TIMEOUT:
print
"Connect Timeout..."
ssh.close()
return
data
#返回shell命令运行结果
def
get_host():
cmd
=
'''
name=`hostname`
ip=`ifconfig eth0 | grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'`
disk=`ls -l /dev/vd[a-z] | wc -l`
list=`ls -l /dev/vd[a-z] | awk '{print $10}'`
echo "hostname:"$name "ip"$ip "disk:"$disk "info:"$list
'''
return
cmd
for
i
in
range
(
165
,
167
):
ipaddr
=
'192.168.122.%s'
%
i
data
=
ssh_cmd(ipaddr,get_host())
print
data
f
=
open
(
'host_info.txt'
,
'a'
)
f.write(data)
|
四、测试环境说明
在写这个脚本的时候,建立了两台VM用来模拟生产环境的一个场景。 VM01:192.168.122.165,VM02:192.168.122.166
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/1862140