logo头像
Snippet 博客主题

Python 利用paramiko模块监控服务器

在需要对远程服务器进行监控或者一些文件操作的时候, 可以使用paramiko 模块来操作.

安装:

1
pip install paramiko

Linux 下还得安装python-devel, 不然会报错

下面是示例代码:

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python
# encoding=utf-8
import datetime
import threading
import paramiko

def sshCmd(ip, username, passwd, cmds):
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(ip, 22, username, passwd, timeout=5)
for cmd in cmds:
stdin, stdout, stderr = client.exec_command(cmd)
lines = stdout.readlines()
# print out
for line in lines:
print line,
print '%s\t 运行完毕\r\n' % (ip)
except Exception, e:
print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
finally:
client.close()

#上传文件
def uploadFile(ip,username,passwd):
try:
t=paramiko.Transport((ip,22))
t.connect(username=username,password=passwd)
sftp=paramiko.SFTPClient.from_transport(t)
remotepath='/root/main.py'
localpath='/home/data/javawork/pythontest/src/main.py'
sftp.put(localpath,remotepath)
print '上传文件成功'
except Exception, e:
print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
finally:
t.close()

#下载文件
def downloadFile(ip,username,passwd):
try:
t=paramiko.Transport((ip,22))
t.connect(username=username,password=passwd)
sftp=paramiko.SFTPClient.from_transport(t)
remotepath='/root/storm-0.9.0.1.zip'
localpath='/home/data/javawork/pythontest/storm.zip'
sftp.get(remotepath,localpath)
print '下载文件成功'
except Exception, e:
print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
finally:
t.close()

if __name__ == '__main__':
# 需要执行的命令列表
cmds = ['ls /root', 'ifconfig']
# 需要进行远程监控的服务器列表
servers = ['xxx.xxx.xxx.xxx']

username = "root"
passwd = "xxxxxx"
threads = []
print "程序开始运行%s" % datetime.datetime.now()
# 每一台服务器创建一个线程处理
for server in servers:
th = threading.Thread(target=sshCmd, args=(server, username, passwd, cmds))
th.start()
threads.append(th)

# 等待线程运行完毕
for th in threads:
th.join()

print "程序结束运行%s" % datetime.datetime.now()

#测试文件的上传与下载
uploadFile(servers[0],username,passwd)
downloadFile(servers[0],username,passwd)

评论系统未开启,无法评论!