paramiko 简单的使用

Posted leiziv5

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()

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

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

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

 

    

以上是关于paramiko 简单的使用的主要内容,如果未能解决你的问题,请参考以下文章

python学习-paramiko简单使用

如何使用 Python 和 Paramiko 创建 SSH 隧道?

python的paramiko模块简单应用

paramiko模块,线程,进程

paramiko的简单使用(ssh远程执行脚本和上传文件)

windows下python安装paramiko模块和pycrypto模块(简单三步)