使用paramiko执行远程linux主机命令

  paramiko是python的SSH库,可用来连接远程linux主机,然后执行linux命令或者通过SFTP传输文件。

  关于使用paramiko执行远程主机命令可以找到很多参考资料了,本文在此基础上做一些封装,便于扩展与编写脚本。

  下面直接给出代码:

  

 1 # coding: utf-8
 2 
 3 import paramiko
 4 import re
 5 from time import sleep
 6 
 7 # 定义一个类,表示一台远端linux主机
 8 class Linux(object):
 9     # 通过IP, 用户名,密码,超时时间初始化一个远程Linux主机
10     def __init__(self, ip, username, password, timeout=30):
11         self.ip = ip
12         self.username = username
13         self.password = password
14         self.timeout = timeout
15         # transport和chanel
16         self.t = ''
17         self.chan = ''
18         # 链接失败的重试次数
19         self.try_times = 3
20 
21     # 调用该方法连接远程主机
22     def connect(self):
23         while True:
24             # 连接过程中可能会抛出异常,比如网络不通、链接超时
25             try:
26                 self.t = paramiko.Transport(sock=(self.ip, 22))
27                 self.t.connect(username=self.username, password=self.password)
28                 self.chan = self.t.open_session()
29                 self.chan.settimeout(self.timeout)
30                 self.chan.get_pty()
31                 self.chan.invoke_shell()
32                 # 如果没有抛出异常说明连接成功,直接返回
33                 print u'连接%s成功' % self.ip
34                 # 接收到的网络数据解码为str
35                 print self.chan.recv(65535).decode('utf-8')
36                 return
37             # 这里不对可能的异常如socket.error, socket.timeout细化,直接一网打尽
38             except Exception, e1:
39                 if self.try_times != 0:
40                     print u'连接%s失败,进行重试' %self.ip
41                     self.try_times -= 1
42                 else:
43                     print u'重试3次失败,结束程序'
44                     exit(1)
45 
46     # 断开连接
47     def close(self):
48         self.chan.close()
49         self.t.close()
50 
51     # 发送要执行的命令
52     def send(self, cmd):
53         cmd += '\r'
54         # 通过命令执行提示符来判断命令是否执行完成
55         p = re.compile(r':~ #')
56 
57         result = ''
58         # 发送要执行的命令
59         self.chan.send(cmd)
60         # 回显很长的命令可能执行较久,通过循环分批次取回回显
61         while True:
62             sleep(0.5)
63             ret = self.chan.recv(65535)
64             ret = ret.decode('utf-8')
65             result += ret
66             if p.search(ret):
67                 print result
68                 return result

  下面进行测试:

 1 # 主机IP错误,无法连接的情况
 2 if __name__ == '__main__':
 3     host = Linux('192.168.180.12', 'root', 'xxxx')
 4     host.connect()
 5      6     host.send('ls -l')
 7     host.close()
 8
 1 # 链接正常的情况
 2 if __name__ == '__main__':
 3     host = Linux('192.168.180.128', 'root', 'love')
 4     host.connect()
 5     host.send('ls -l')
 6     host.close()
 7 
 8 运行结果:
 9 连接192.168.180.128成功
10 Last login: Sat May 21 07:25:39 2016 from 192.168.180.1
11 Have a lot of fun...
12 
13 ls -l
14 192:~ # ls -l
15 total 28
16 -rw------- 1 root root 18 May 21 07:17 .bash_history
17 drwxr-xr-x 1 root root 28 May 21 06:02 .config
18 drwx------ 1 root root 22 May 21 05:57 .dbus
19 drwx------ 1 root root  0 Sep 25  2014 .gnupg
20 drwxr-xr-x 1 root root 10 May 21 06:15 .local
21 -rw------- 1 root root 55 May 21 06:03 .xauth5mesuo
22 -rw------- 1 root root 55 May 21 07:22 .xauthEYqDmK
23 -rw------- 1 root root 55 May 21 07:25 .xauthGTrohO
24 -rw------- 1 root root 55 May 21 07:09 .xauthP90TnG
25 -rw------- 1 root root 48 May 21 07:40 .xauthjW8pI9
26 -rw------- 1 root root 48 May 21 07:40 .xauthx8T4ED
27 drwxr-xr-x 1 root root  0 Sep 25  2014 bin
28 drwxr-xr-x 1 root root 38 May 21 05:43 inst-sys
29 192:~ # 
30 
31 Process finished with exit code 0

 

 9 连接192.168.180.12失败,进行重试
10 连接192.168.180.12失败,进行重试
11 连接192.168.180.12失败,进行重试
12 重试3次失败,结束程序
13 
14 Process finished with exit code 1

  从上面代码可以看出,通过简单封装之后,执行远端linux主机就非常简单了,只需简单几行代码即可。

posted @ 2016-05-20 23:46  oceany  阅读(13417)  评论(0编辑  收藏  举报