声明:忘记参考了哪位大神的代码了,找不到链接,如果有发现盗版的请提示我,到时候我把出处添加上。
首先我用的开发环境是window+eclipse,环境的安装要求:
1、eclipse安装有python的开发插件
2、window安装有python
3、pip install paramiko
下面直接上代码
#!/usr/bin/env python
# encoding: utf-8
'''
Created on 2018年5月10日
@author: Jenson
'''
import paramiko
import time
class ParammikoUtil(object):
# 通过IP, 用户名,密码,超时时间初始化一个远程Linux主机
def __init__(self, ip, username, password, timeout=40):
self.ip = ip
self.username = username
self.password = password
self.timeout = timeout
# transport和chanel
self.t = ''
self.chan = ''
# 链接失败的重试次数
self.try_times = 3
# 调用该方法连接远程主机
def connect(self):
while True:
# 连接过程中可能会抛出异常,比如网络不通、链接超时
try:
self.t = paramiko.Transport(sock=(self.ip, 22))
self.t.connect(username=self.username, password=self.password)
self.chan = self.t.open_session()
self.chan.settimeout(self.timeout)
self.chan.get_pty()
self.chan.invoke_shell()
# 如果没有抛出异常说明连接成功,直接返回
print u'连接%s成功' % self.ip
# 接收到的网络数据解码为str
self.receLog()
return
# 这里不对可能的异常如socket.error, socket.timeout细化,直接一网打尽
except Exception, e1:
if self.try_times != 0:
print u'连接%s失败,进行重试' %self.ip
self.try_times -= 1
else:
print u'重试3次失败,结束程序'
exit(1)
# 断开连接
def close(self):
self.chan.close()
self.t.close()
#获取log
def receLog (self):
while True :
#每0.5s执行一次
time.sleep(0.5)
result = self.chan.recv(65535).decode('utf-8')
print result
#print result.split('\n')[len(result.split('\n'))-1]
if result.split('\n')[len(result.split('\n'))-1] == '[root@master03 ~]# ' :
break
#发送一般命令
def runCMD(self , cmd):
cmd += '\r'
# 发送要执行的命令
print '输入命令:'
self.chan.send(cmd)
#获取结果
self.receLog()
#输入安装软件的命令
def runInstall(self,cmd):
cmd += '\r'
# 发送要执行的命令
print '输入命令:'
self.chan.send(cmd)
while True :
#每0.5s执行一次
time.sleep(0.5)
result = self.chan.recv(65535).decode('utf-8')
print result
#需要输入y
if result.split('\n')[len(result.split('\n'))-1] == r'Is this ok [y/d/N]: ':
#print 1111
#print result
self.chan.send('y'+'\n')
#判断是否处理完
elif result.split('\n')[len(result.split('\n'))-1] == '[root@master03 ~]# ' :
break
#发送卸载软件的命令
def runRemove(self,cmd):
cmd += '\r'
# 发送要执行的命令
print '输入命令:'
self.chan.send(cmd)
while True :
#每0.5s执行一次
time.sleep(0.5)
result = self.chan.recv(65535).decode('utf-8')
print result
#需要输入y
if result.split('\n')[len(result.split('\n'))-1] == r'Is this ok [y/N]: ':
#print 1111
#print result
self.chan.send('y'+'\n')
#判断是否处理完
elif result.split('\n')[len(result.split('\n'))-1] == '[root@master03 ~]# ' :
break
if __name__ == '__main__':
host = ParammikoUtil('master03', 'root', 'root')
host.connect()
#host.runCMD('ls -a')
#host.runInstall('yum install git')
#host.runRemove('yum remove git')
host.close()