paramiko 简单的使用

             感觉自己操作服务器还要用xshell,麻烦很多,于是呢就去google,找到了paramiko。

            使用这个模块还是很简单的,

   我们链接服务器,只需要导入 SSHClient,AutoAddPolicy 两个类就可以使用了。

    代码如下

# -*- coding: utf-8 -*-
# @Date    : 2018-07-07 11:56:22
# @Author  : leizi
from paramiko import  SSHClient
from paramiko import AutoAddPolicy
class Telecent(object):
	def __init__(self,host,username,password):
		self.host=host
		self.username=username
		self.password=password
	def telecent(self):
		ssh=SSHClient()
		ssh.set_missing_host_key_policy(AutoAddPolicy())
		try:
			ssh.connect(hostname=self.host,username=self.username,password=self.password,allow_agent=True)
			return ssh
		except Exception as e:
			raise e
	def exec_command(self,cmd):
		try:
			stdin,stdout,stderr=self.telecent().exec_command(cmd)
			result=stdout.read()
			return str(result).encode('utf-8')
		except Exception as e:
			raise e
		finally:
			self.telecent().close()	
	def copy_file(self,intputpath,outpath):
		try:
			ftp=self.telecent().open_sftp()
			ftp.put(intputpath,outpath)
		except Exception as e:
			raise e
		finally:
			ftp.close()

  我这里每次函数我都有异常处理,暂时针对异常呢,我这里处理的方式是直接抛出去。

      在后续的,我会做进一步的处理,这个在以后我们的测试过程中是可以会遇到的。

      在后续我会把自动回滚的代码给处理上去。

    

猜你喜欢

转载自www.cnblogs.com/leiziv5/p/9276962.html