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
【基本使用】
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