python 一鍵Ftp 支持多機

#coding:utf-8
#__author__:swg
import paramiko,os,sys,json
current_file = sys.argv[0] if len(sys.argv)==1 else sys.argv[0]

#配置例子、丟失配置文件的時候幫助用戶添加,在當前目錄下存在sftp-config.json即可
config_demo = '''
{
	"mkdir": "True",
	"ignoreDir": [".git",".svn",".idea"],
	"base_dir" : "D:\\www\\app1\\",
	"upload_app:"www.app1.com",
	"uplpad_forder":["path1","path2\api2"],
	
	"remote_config" = {
		"Test-Host-A":{
			"hostname":'192.168.1.88',
			"username":'root',
			"password":'123456',
			"port":22,
			"path":"/home/www/games/"
		},
		"Test-Host-B" :{
			"hostname":'192.168.1.89',
			"username":'root',
			"password":'123456',
			"port":22,
			"path":"/home/www/web/"
		}
	}
}
'''

#config reader
config_path = os.path.join(os.path.dirname(current_file),"sftp-config.json")
if not os.path.exists(config_path):
	print "\n\n config file(sftp-config.json) not found, \n\nif you lost,creeat it like this: \n\n %s \n\n " % config_demo
	sys.exit()
	
config_content = file(config_path)
config = json.load(config_content)

#強制創建目錄
mkdir = config['mkdir']
#忽略目錄
ignoreDir = config['ignoreDir']

#本地項目根目錄
base_dir = config['base_dir']

#需要上傳的APP
upload_app = config['upload_app']

#需要上傳的目錄
uplpad_forder = config['upload_forder']

#遠程配置
remote_config = config['remote_config']


connect_pool = {}
for name,host in remote_config.items():
	try:
		sftp=paramiko.Transport((host['hostname'],host['port']))
		sftp.connect(username=host['username'],password=host['password'])
		sftp = paramiko.SFTPClient.from_transport(sftp)
		
		ssh = paramiko.SSHClient()  
		ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
		ssh.connect(host['hostname'], host['port'], host['username'], host['password'])  

		connect_pool[name] = {
			'sftp':sftp,
			'ssh':ssh,
			'path':host['path'],
			'host':host['hostname'],
		}
		
	except:
		raise "can not connect %s (%s)" % (name,host['hostname'])	
	print "connect %s (%s) ok" % (name,host['hostname'])


def UploadToRemote(files):
	global connect_pool,base_dir
	for name,host in connect_pool.items():
		local_file  =  (base_dir+'\\'+files).replace('/',"\\")
		remote_file =  (host['path'] +"/"+files).replace("///",'/') 
		print "%s ==> %s:%s " % (local_file.replace('\\\\\\','\\') ,host['host'],remote_file) ,
		try:
			host['sftp'].put(local_file,remote_file)
			print '    ok'
		except Exception ,e:
			print '    fail',e
	
def MkRemoteDir(dirs):
	global connect_pool
	for name,host in connect_pool.items():
		remote_dir = (host['path'] +dirs).replace('//','/')
		print "mkdir: " + remote_dir,
		try:
			# stdin, stdout, stderr = host['ssh'].exec_command('mkdir -p %s' % remote_dir)
			host['ssh'].exec_command('mkdir -p %s' % remote_dir)
			print "ok"
		except Exception ,e:
			print '  Fail!  '
			
for local_dir in uplpad_forder:

	for root,dirs,files in os.walk(base_dir +"\\"+ upload_app+"\\"+local_dir):
	
		for filespath in files:
			local_file = os.path.join(root,filespath)
			local_file = local_file.replace(base_dir,'')
			remote_file = local_file.replace("\\","/")
			
			passFile = False
			for f in ignoreDir:
				if remote_file.find(f)!=-1:
					print remote_file ,"============> ignore"
					passFile = True
					break;
			if not passFile:
				UploadToRemote(remote_file)
			
		if mkdir == True:
			for dirname in dirs:
				passFile = False
				full_dir = os.path.join(root,dirname)
				for f in ignoreDir:
					if full_dir.find(f)!=-1:
						# print full_dir ,"============> ignore"
						passFile = True
						break;
				if not passFile:
					dir_name = os.path.join(root,dirname)
					MkRemoteDir( dir_name.replace(base_dir,'').replace("\\","/") )
		else:
			pass

print "\n\nDone"

if sys.platform[:3] == 'win':
	os.system("pause")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章