---
title: "python paramiko - paramiko 安装"
author: "飞奔的熊猫"
date: "2014-08-27T17:34:59Z"
tags: []
categories: ["开源软件"]
slug: "python-paramiko-paramiko"
draft: false
lastmod: "2014-11-24T18:03:30Z"
id: 2109684
url: "https://runpanda.iteye.com/blog/2109684"
---

【基本介绍】
Python SSH module.一般用来通过ssh远程来执行命令，远程传输文件等等。

【安装paramiko】 - 这里我们使用pip来进行安装
Python中使用SSH需要用到OpenSSH，而OpenSSH依赖于paramiko模块，而paramiko模块又依赖于pycrypto模块，因此要在Python中使用SSH，则需要先安装模块顺序是：pycrypto -> paramiko

安装过程中会报ImportError: No module named Crypto.PublicKey并且找不到vcvarsall.bat。我们直接下载已经编译好的pycrypto来进行安装就好了.
<http://www.voidspace.org.uk/python/modules.shtml#pycrypto>

【基本使用】

```python
def sshConnection(self,hostname,port,username,password,type):
	'''connection to remote server by ssh or ftp'''
	try:
		if type == 'ssh':
			self.ssh = paramiko.SSHClient()
 		    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
			self.ssh.connect(hostname,port,username,password)
			self.logger.info('ssh to '+hostname)
		elif type == 'sftp':
			ftp = paramiko.Transport((hostname,port))
			ftp.connect(username=username,password=password)
			self.sftp = paramiko.SFTPClient.from_transport(ftp)
			self.logger.info('sftp to '+hostname)
		else:
			#print 'type correct connect type(ssh , ftp)'
			self.logger.info('use invalid type: '+type)
		print 'connect to ' + hostname + ' [ok]'
	except Exception:
		self.logger.info('connection refused: '+hostname)
		print 'connect to ' + hostname + ' [not ok]'
		sys.exit()

		
def sshRunCommand_getOutput(self,command):
	'''after connect then get output'''
	stdin , stdout , stderr = self.ssh.exec_command(command)



```


或者可以pip install pycrypto-on-pypi
<http://www.nqwang.com/2014/0216/89093.html>

【参考】
<http://www.voidspace.org.uk/python/modules.shtml#pycrypto>
<http://blog.chinaunix.net/uid-24917554-id-3476396.html>