Windows服务器Pyton辅助运维
01.自动Copy文件(文件夹)到远程服务器所在目录
开发环境:
u Web服务器:
Windows Server 2008 R2 SP1
IIS 7.5
u 运维服务器:
工作内容说明:
生产环境中有很多台Web服务器,均为IIS环境,每次开发人员都提供站点补丁包给我进行系统升级,我需要将这些补丁包更新到所有Web服务器的指定目录下以完成系统更新的工作。
实现过程:
整一个配置文件记录基本信息AppConfig.ini
1 [DepolyFiles] 2 3 LocalDir=C:Deploy 4 5 RemoteDir=E:Deploy 6 7 Servers=192.168.1.2-23|192.168.1.37 8 9 UserId=administrator 10 11 Password=******* 12 13 UseIISRestart= false
Servers配置节中“|”是分隔符,可以填写多个IP,“-”符号表示连续IP。
然后去搜一个WMI的Python实现代码如下RemoteCopyFiles.py
1 __author__="*****" 2 __date__ ="*****" 3 4 import os 5 import wmi 6 import shutil 7 import win32wnet 8 import ConfigParser 9 10 REMOTE_PATH = 'c:\' 11 12 def main(): 13 pIniFileName = "AppConfig.ini"; 14 15 config = ConfigParser.ConfigParser() 16 config.readfp(open(pIniFileName,"rb")) 17 18 LocalDir = config.get("DepolyFiles","LocalDir").strip() 19 RemoteDir = config.get("DepolyFiles","RemoteDir").strip() 20 Servers = config.get("DepolyFiles","Servers").strip() 21 UserId = config.get("DepolyFiles","UserId").strip() 22 Password = config.get("DepolyFiles","Password").strip() 23 UseIISRestart = config.get("DepolyFiles","UseIISRestart").strip() 24 25 print "LocalDir : "+LocalDir 26 print "RemoteDir : "+RemoteDir 27 print "Servers : "+Servers 28 print "UserId : "+UserId 29 print "Password : "+Password 30 print "UseIISRestart : "+UseIISRestart 31 32 pServerSplit = Servers.split('|'); 33 pServerList = list(); 34 for itemServer in pServerSplit: 35 sServerString = itemServer.strip(); 36 if(sServerString.find('-')>0): 37 tempList = sServerString.split('-'); 38 iStartValue = int(tempList[0].split('.')[3]); 39 iEndValue = int(tempList[1]); 40 sFrontString = tempList[0].split('.')[0]+"."+tempList[0].split('.')[1]+"."+tempList[0].split('.')[2]+"."; 41 while iStartValue<=iEndValue: 42 pServerList.append(sFrontString+str(iStartValue)); 43 iStartValue=iStartValue+1; 44 else: 45 pServerList.append(sServerString); 46 47 for webServer in pServerList: 48 print ''; 49 sPrint = "Deploy Servers : {0} start.".format(webServer); 50 print sPrint 51 ip = webServer 52 username = UserId 53 password = Password 54 server = WindowsMachine(ip, username, password) 55 result = server.copy_folder(LocalDir,RemoteDir); 56 sPrint = "Deploy Servers : {0} completed.".format(webServer); 57 print sPrint 58 59 print "**********Deploy Completed*************"; 60 61 def create_file(filename, file_text): 62 f = open(filename, "w") 63 f.write(file_text) 64 f.close() 65 66 class WindowsMachine: 67 def __init__(self, ip, username, password, remote_path=REMOTE_PATH): 68 self.ip = ip 69 self.username = username 70 self.password = password 71 self.remote_path = remote_path 72 try: 73 print "Establishing connection to %s" %self.ip 74 self.connection = wmi.WMI(self.ip, user=self.username, password=self.password) 75 print "Connection established" 76 except wmi.x_wmi: 77 print "Could not connect to machine" 78 raise 79 80 def net_copy(self, source, dest_dir, move=False): 81 """ Copies files or directories to a remote computer. """ 82 print "Start copying files to " + self.ip 83 if self.username == '': 84 if not os.path.exists(dest_dir): 85 os.makedirs(dest_dir) 86 else: 87 # Create a directory anyway if file exists so as to raise an error. 88 if not os.path.isdir(dest_dir): 89 os.makedirs(dest_dir) 90 shutil.copy(source, dest_dir) 91 92 else: 93 self._wnet_connect() 94 95 dest_dir = self._covert_unc(dest_dir) 96 97 # Pad a backslash to the destination directory if not provided. 98 if not dest_dir[len(dest_dir) - 1] == '\': 99 dest_dir = ''.join([dest_dir, '\']) 100 101 # Create the destination dir if its not there. 102 if not os.path.exists(dest_dir): 103 os.makedirs(dest_dir) 104 else: 105 # Create a directory anyway if file exists so as to raise an error. 106 if not os.path.isdir(dest_dir): 107 os.makedirs(dest_dir) 108 109 if move: 110 shutil.move(source, dest_dir) 111 else: 112 shutil.copy(source, dest_dir) 113 114 def _wnet_connect(self): 115 unc = ''.join(['\\', self.ip]) 116 try: 117 win32wnet.WNetAddConnection2(0, None, unc, None, self.username, self.password) 118 except Exception, err: 119 if isinstance(err, win32wnet.error): 120 # Disconnect previous connections if detected, and reconnect. 121 if err[0] == 1219: 122 win32wnet.WNetCancelConnection2(unc, 0, 0) 123 return self._wnet_connect(self) 124 raise err 125 126 def _covert_unc(self, path): 127 """ Convert a file path on a host to a UNC path.""" 128 return ''.join(['\\', self.ip, '\', path.replace(':', '$')]) 129 130 def copy_folder(self, local_source_folder, remote_dest_folder): 131 files_to_copy = os.listdir(local_source_folder) 132 for file in files_to_copy: 133 file_path = os.path.join(local_source_folder, file) 134 print "Copying " + file 135 if(os.path.isdir(file_path)): 136 self.copy_folder(file_path,remote_dest_folder+"\"+file); 137 else: 138 try: 139 self.net_copy(file_path, remote_dest_folder) 140 except WindowsError: 141 print 'could not connect to ', self.ip 142 except IOError: 143 print 'One of the files is being used on ', self.ip, ', skipping the copy procedure' 144 145 if __name__ == "__main__": 146 main()
备注:请确保在一个运维机器和Web服务器在同一个局域网中.