使用PARAMIKO进行SSH的开发
http://www.cnblogs.com/gannan/archive/2012/02/06/2339883.html
PARAMIKO使用Python2.6
1. Install Pycrypto :
http://www.voidspace.org.uk/python/modules.shtml#pycrypto
2. Install
https://github.com/nischu7/paramiko
Download, unzip,
C:\python\python.exe setup.py build C:\python\python.exe setup.py install
然后就可以进行开发了。
import paramiko import os import datetime import base64 import sys import traceback hosts=[{'hostname':'10.249.75.37','username':'username','password':'password'}] port=22 local_dir='C:/Jojo/Work/Python/SSHConnect/grid/' remote_dir='/Users/maui/grid' command='deploy' def uploadFileToMachine(client,t,local_dir,remote_dir): try: print('connected,create folder--'+remote_dir) stdin,stdout,stderr = client.exec_command('mkdir '+remote_dir) for line in stdout: print('...'+line.strip('\n')) if(t==None ): t = client.get_transport() sftp=paramiko.SFTPClient.from_transport(t) files=os.listdir(local_dir) print(local_dir); dir = local_dir for f in files: path=dir+f print(path) if(os.path.isfile(path)): print ('') print('##################################################################') print('Beginning to upload file %s ' % datetime.datetime.now()) print('Uploading file:',os.path.join(local_dir,f),' to ',remote_dir+"/"+f) # sftp.get(os.path.join(dir_path,f),os.path.join(local_path,f)) #sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f)) sftp.put(os.path.join(local_dir,f),remote_dir+"/"+f) print('Upload file success %s ' % datetime.datetime.now() ) print ('' ) t.close() except Exception, e: print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) traceback.print_exc() try: t.close() except: pass def connectHost(host): hostname = host['hostname'] username = host['username'] password = host['password'] print('connecting ...'+hostname) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname, username=username, password=password) return client if command=="deploy": paramiko.util.log_to_file('deploy.log') for host in hosts: try: client = connectHost(host) uploadFileToMachine(client,None ,local_dir,remote_dir) client.close() except Exception, e: print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) traceback.print_exc() try: client.close() except: pass