Windows服务器Pyton辅助运维--01.自动Copy文件(文件夹)到远程服务器所在目录

时间:2021-05-01 07:44:34

Windows服务器Pyton辅助运维

01.自动Copy文件(文件夹)到远程服务器所在目录

开发环境:

Web服务器:

Windows Server 2008 R2 SP1

IIS 7.5

运维服务器:

Python 2.7.8

组件:pywin32(219)  wmi(1.4.9)

工作内容说明:

生产环境中有很多台Web服务器,均为IIS环境,每次开发人员都提供站点补丁包给我进行系统升级,我需要将这些补丁包更新到所有Web服务器的指定目录下以完成系统更新的工作。

实现过程:

整一个配置文件记录基本信息AppConfig.ini

 [DepolyFiles]

 LocalDir=C:\Deploy

 RemoteDir=E:\Deploy

 Servers=192.168.1.2-23|192.168.1.37

 UserId=administrator

 Password=*******

 UseIISRestart= false

Servers配置节中“|”是分隔符,可以填写多个IP,“-”符号表示连续IP。

然后去搜一个WMI的Python实现代码如下RemoteCopyFiles.py

 __author__="*****"
__date__ ="*****" import os
import wmi
import shutil
import win32wnet
import ConfigParser REMOTE_PATH = 'c:\\' def main():
pIniFileName = "AppConfig.ini"; config = ConfigParser.ConfigParser()
config.readfp(open(pIniFileName,"rb")) LocalDir = config.get("DepolyFiles","LocalDir").strip()
RemoteDir = config.get("DepolyFiles","RemoteDir").strip()
Servers = config.get("DepolyFiles","Servers").strip()
UserId = config.get("DepolyFiles","UserId").strip()
Password = config.get("DepolyFiles","Password").strip()
UseIISRestart = config.get("DepolyFiles","UseIISRestart").strip() print "LocalDir : "+LocalDir
print "RemoteDir : "+RemoteDir
print "Servers : "+Servers
print "UserId : "+UserId
print "Password : "+Password
print "UseIISRestart : "+UseIISRestart pServerSplit = Servers.split('|');
pServerList = list();
for itemServer in pServerSplit:
sServerString = itemServer.strip();
if(sServerString.find('-')>0):
tempList = sServerString.split('-');
iStartValue = int(tempList[0].split('.')[3]);
iEndValue = int(tempList[1]);
sFrontString = tempList[0].split('.')[0]+"."+tempList[0].split('.')[1]+"."+tempList[0].split('.')[2]+".";
while iStartValue<=iEndValue:
pServerList.append(sFrontString+str(iStartValue));
iStartValue=iStartValue+1;
else:
pServerList.append(sServerString); for webServer in pServerList:
print '';
sPrint = "Deploy Servers : {0} start.".format(webServer);
print sPrint
ip = webServer
username = UserId
password = Password
server = WindowsMachine(ip, username, password)
result = server.copy_folder(LocalDir,RemoteDir);
sPrint = "Deploy Servers : {0} completed.".format(webServer);
print sPrint print "**********Deploy Completed*************"; def create_file(filename, file_text):
f = open(filename, "w")
f.write(file_text)
f.close() class WindowsMachine:
def __init__(self, ip, username, password, remote_path=REMOTE_PATH):
self.ip = ip
self.username = username
self.password = password
self.remote_path = remote_path
try:
print "Establishing connection to %s" %self.ip
self.connection = wmi.WMI(self.ip, user=self.username, password=self.password)
print "Connection established"
except wmi.x_wmi:
print "Could not connect to machine"
raise def net_copy(self, source, dest_dir, move=False):
""" Copies files or directories to a remote computer. """
print "Start copying files to " + self.ip
if self.username == '':
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
else:
# Create a directory anyway if file exists so as to raise an error.
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
shutil.copy(source, dest_dir) else:
self._wnet_connect() dest_dir = self._covert_unc(dest_dir) # Pad a backslash to the destination directory if not provided.
if not dest_dir[len(dest_dir) - 1] == '\\':
dest_dir = ''.join([dest_dir, '\\']) # Create the destination dir if its not there.
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
else:
# Create a directory anyway if file exists so as to raise an error.
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir) if move:
shutil.move(source, dest_dir)
else:
shutil.copy(source, dest_dir) def _wnet_connect(self):
unc = ''.join(['\\\\', self.ip])
try:
win32wnet.WNetAddConnection2(0, None, unc, None, self.username, self.password)
except Exception, err:
if isinstance(err, win32wnet.error):
# Disconnect previous connections if detected, and reconnect.
if err[0] == 1219:
win32wnet.WNetCancelConnection2(unc, 0, 0)
return self._wnet_connect(self)
raise err def _covert_unc(self, path):
""" Convert a file path on a host to a UNC path."""
return ''.join(['\\\\', self.ip, '\\', path.replace(':', '$')]) def copy_folder(self, local_source_folder, remote_dest_folder):
files_to_copy = os.listdir(local_source_folder)
for file in files_to_copy:
file_path = os.path.join(local_source_folder, file)
print "Copying " + file
if(os.path.isdir(file_path)):
self.copy_folder(file_path,remote_dest_folder+"\\"+file);
else:
try:
self.net_copy(file_path, remote_dest_folder)
except WindowsError:
print 'could not connect to ', self.ip
except IOError:
print 'One of the files is being used on ', self.ip, ', skipping the copy procedure' if __name__ == "__main__":
main()

备注:请确保在一个运维机器和Web服务器在同一个局域网中.