paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。
由于使用的是python这样的能够跨平台运行的语言,所以所有python支持的平台,如Linux, Solaris, BSD, MacOS X, Windows等,paramiko都可以支持,因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系列的操作时,paramiko是最佳工具之一。
paramiko的再封装
import os
import logging
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
logging.basicConfig(filename='my.log', level=logging.WARN, format="%(asctime)s-%(filename)s-%(lineno)d- %(levelname)s: %(message)s ")
class SshRemoteHosts(object):
def __init__(self,host,user,pwd,cmd,port=22):
self.host=host
self.user=user
self.pwd=pwd
self.cmd=cmd
self.port=port
def run(self):
cmd_str=self.cmd.split()[0]
if hasattr(self,'do_' +cmd_str):
getattr(self,'do_'+cmd_str)()
else:
logging.error('目前不支持该操作...目前支持get,put,cmd')
print('目前不支持该操作...目前支持get,put,cmd')
def do_cmd(self):
print('正在执行命令...')
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=self.host,
username=self.user,
password=self.pwd
)
except NoValidConnectionsError as e:
logging.error('主机%s连接失败' % (self.host))
print('主机%s连接失败' % (self.host))
except AuthenticationException as e:
logging.error('主机%s密码错误' % (self.host))
print('主机%s密码错误' % (self.host))
except Exception as e:
logging.error('未知错误:', e)
print('未知错误:', e)
else:
cmd =' '.join(self.cmd.split()[1:])
stdin, stdout, stderr = client.exec_command(cmd)
res = (stdout.read().decode('utf-8'))
logging.error('%s主机执行命令%s的结果是:%s'%(self.host,self.cmd,res))
client.close()
print(res)
def do_put(self):
print('正在批量上传文件...')
def do_get(self):
print('正在批量下载文件...')
def main():
CONFDIR='conf'
print('主机组显示:'.center(50,'*'))
groups=[file.rstrip('.conf') for file in os.listdir(CONFDIR) if file.endswith('.conf')]
for group in groups:print('\t',group)
while True:
choicegroup=input('请输入操作的主机组名称(eg:web):')
if choicegroup not in groups:
print('%s不存在'%choicegroup)
else:
break
infostr='%s主机组包含的主机:' %(choicegroup)
print(infostr.center(50,'*'))
hostinfos=[]
with open('%s/%s.conf' %(CONFDIR,choicegroup)) as f:
for line in f:
hostinfos.append(line.strip().split(':'))
hostname,port,user,passwd=line.strip().split(':')
print(hostname)
print('批量执行脚本'.center(50,'*'))
while True:
cmd = input('-->:')
if cmd:
if cmd in ['quit','exit']:
print('执行结束,正在退出...')
exit(0)
else:
for host in hostinfos:
hostname,port,user,passwd=host
print(hostname.center(50,'*'))
sshobj=SshRemoteHosts(hostname,user,passwd,cmd,port)
sshobj.run()
if __name__ == '__main__':
main()