您好,登錄后才能下訂單哦!
#!/usr/bin/env python #-*- encoding:utf8 -*- #--------------------------------------------------------------------------------------- # FILE: sshd.py # USAGE: sshd.py # DESCRIPTION: Copy python style guide and coding standard . # The default copy example is the current text . # Dont.t find text on other directories . # OPTIONS: see fuction 'usage' below # BUGS: --- # AUTHOR: Dr.-Vision. Simple(sp) # VERSION: 1.0 # CREATED: 08.18.2014 - 10:15:30 # REVISION: 12.02.2014 # PROJECT: XXX # COPYRITHT: Copyright(c)2002-2014 Python, All Rights Reserved #--------------------------------------------------------------------------------------- # import python module #--------------------------------------------------------------------------------------- # define python import modules . #--------------------------------------------------------------------------------------- import os import sys sys.path.append('../module') from zgtz import idsTempDic,showServerStart,showServerEnd import socket import time import pexpect import paramiko import getpass # Python Function comments #======== Function ==================================================================== # NAME: # DESCRIPTION: Display usage information for this script. # PARAMETER 1: --- #======================================================================================= class SSH(object): user = "用戶名" port = "端口" passwd = "明文密碼" cmd = "命令行" local_path = "本地路徑" remote_path = "遠程路徑" known_host = "host文件" public_rsa_file = "RSA公鑰文件" private_rsa_file = "RSA私鑰文件" public_dsa_file = "DSA公鑰文件" private_dsa_file = "DSA私鑰文件" auth_key_file = "authorized_keys" rsa_cmd = "RSA keygen" dsa_cmd = "DSA keygen" record_log = 'ssh日志文件' t1 = "函數啟動時間" t2 = "函數結束時間" def __init__(self): self.user = "root" self.port = 22 self.passwd = "" self.cmd = "ls ./tmp" self.local_path = os.environ['HOME']+'/.ssh/' self.remote_path = os.environ['HOME']+'/.ssh/' self.known_host = "known_hosts" self.public_dsa_file = "id_dsa.pub" self.private_dsa_file = "id_dsa" self.public_rsa_file = "id_rsa.pub" self.private_rsa_file = "id_rsa" self.auth_key_file = "authorized_keys" self.rsa_cmd = "/usr/bin/ssh-keygen -t rsa " self.dsa_cmd = "/usr/bin/ssh-keygen -t dsa " self.record_log = "./tmp/paramiko.log" self.t1 = time.time() def key_rw(self,host): self.host = host if os.path.exists(self.local_path+self.auth_key_file) and os.path.getsize(self.local_path+self.auth_key_file) != 0 : print "%sFileName ===%10s\tCVM_Address === %s\t[ CVM 跳板機 Is Exists ! ] %s" %(rx,self.auth_key_file,self.host,ry) all = [] os.chdir(self.local_path) Fname= open(self.auth_key_file,'r') for line in Fname: #print line all.append(line) return all Fname.close() else: try: all = [] ls = os.linesep rdsa=['rsa', 'dsa'] #print self.local_path os.chdir(self.local_path) try: for i in rdsa: FName = open('id_%s.pub'%(str(i))) for line in FName: #print line.rstrip('\n'), all.append(line) F_KEY = open(self.local_path+self.auth_key_file,'w') F_KEY.writelines(['%s%s'% (x,ls)for x in all]) print "%sFileName ===%10s\tCVM_Address === %s\t[ CVM 跳板機 NoKey OK ] %s" %(rx,self.auth_key_file,self.host,ry) return all FName.close() F_KEY.close() except IOError ,e: print "*** file open failed:",e except: print "Open %s file failed !" %(self.auth_key_file) raise def rsync_ssh(self,host): self.host = host try: scp = paramiko.Transport((self.host,self.port)) scp.connect(username=self.user,password=self.passwd) sftp = paramiko.SFTPClient.from_transport(scp) except Exception,e: print e scp.close() else: try: sftp.mkdir(self.remote_path) except IOError: #print('(assuming ~/.ssh already exists)') with sftp.open(self.remote_path+self.auth_key_file,'a+') as f: f.write("#Create SSH Address == %s\n"%(self.host)) with open(self.local_path+self.public_rsa_file,'r') as f: data = f.read() sftp.open(self.remote_path+self.auth_key_file,'a+').write(data) sftp.open(self.remote_path+self.auth_key_file,'a').write('\n') print '%sFileName ===%s\tCVM_Address === %s\t[ Finish NoKey OK ]%s' %(rx,self.auth_key_file,self.host,ry) else: with sftp.open(self.remote_path+self.auth_key_file, 'w') as f: f.write("#This Is NoKey Record .\n") with open(self.local_path+self.public_rsa_file,'r') as f: data = f.read() sftp.open(self.remote_path+self.auth_key_file,'w').write(data) print '%sFileName ===%s\tCVM_Address === %s\t[ Finish NoKey OK ]%s' %(rx,self.auth_key_file,self.host,ry) if __name__ == '__main__': #格式化打印 star="\033[1;33;40m=\033[0m" rx="\033[1;33;40m" ry="\033[0m" showStart = showServerStart() temp_data = idsTempDic() ids_sorted = sorted(temp_data.items(),key=lambda d:int(d[0])) for k,v in ids_sorted: print '\t'.join(v) showEnd = showServerEnd() while True: ids = [] errids = [] try: inputs=str(raw_input('%s請輸入CVM_ID[多個請用空格隔開,全部(all),反選("-"開頭),返回(b)]:%s'%(rx,ry)).strip().lower()) print inputs #inputs=raw_input('請輸入CVM_ID[多個請用空格隔開,全部(all),反選("-"開頭),返回(b)]:').strip().lower() if inputs == "b": print '%s您沒有選擇,返回主界面! %s'%(rx,ry) raw_input() continue elif inputs == "all": ids = temp_data.keys() # 此處返回字典key,類型為list類型 #print ids break elif inputs.startswith('-'): ex = inputs[1:].split() #print ''.join(ex) all = temp_data.keys() ids = [x for x in all if x not in ex] #反選后的CVM_ID exids = [x for x in ex if x not in all] #反選CVM_ID break else: ids = inputs.split() ids=sorted(set(ids),key=ids.index) for id in ids: running = temp_data.has_key(id) if running == False: ids.remove(id) errids.append(id) print ids elif running == True: print "%s輸入正確的CVM_ID:%s %s"%(rx,id,ry) else: raise ValueError break except (NameError,KeyboardInterrupt): print "\n" sys.exit() except (ValueError,KeyError): print "%s 無此CVM_ID,輸入錯誤,請重新輸入! %s"%(rx,ry) raw_input() if not ids: print "%s你輸入的CVM_ID有誤%s"%(rx,ry) if inputs == "all": print "%s選擇所有服務器 %s"%(rx,ry) elif inputs.startswith('-'): #print exids print "\033[1;33;40m去除的id為:%s\033[0m "%",".join(ex) print "\033[1;33;40m反選后id為:\033[0m", for gid in ids: name = temp_data[gid][0] if name: print name+' ', print '\t' else: print "\033[1;33;40m去除的id為:%s\033[0m "%",".join(ids) print "對應的游戲服為:", for gid in ids: name = temp_data[gid][0] if name: print name+' ', if errids: print "%s你輸入的id部分有誤,已經排除:%s"%(rx,ry) print '\t'.join(errids) try: if raw_input("\n確認?(y/n)") == "y": print "%s更新的CVM_ID為%s:"%(rx,ry)+' '.join(ids) sshdir ="~/.ssh" if os.path.exists(sshdir): pass else: for gid in ids: Host_Wan = temp_data[gid][3] Host_Lan = temp_data[gid][4] print Host_Wan,Host_Lan if Host_Lan == "10.1.1.1": SSH2 = SSH() #SSH2.key_rw(Host_Wan) #SSH2.rsync_ssh(Host_Lan) print "%s跳過運維跳板機%s" else: try: SSH2 = SSH() SSH2.rsync_ssh(Host_Lan) SSH2.known_hosts(Host_Lan) SSH2.known_hosts(Host_Wan) except Exception as e: print e print "%s所選CVM_ID %s已經更新完成! %s"%(rx,ids,ry) else: sys.exit() except (KeyboardInterrupt,EOFError): print "\n" sys.exit()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。