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()

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

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

  这样就简单的 一个简单可以用的脚本就编写完了,在以后工作中还有进一步的作用。

 

github 地址:https://github.com/liwanlei . qq群:python|测试|技术交流群 194704520 
python测试开发交流群 683894834 
python接口测试群:651392041
腾讯视频:http://v.qq.com/vplus/6797e52f56a39105a0b6c87bb849e22c/videos 

    

posted @ 2018-07-07 12:34  北漂的雷子  阅读(389)  评论(0编辑  收藏  举报