Windows服务器Pyton辅助运维--01.自动Copy文件(文件夹)到远程服务器所在目录
Windows服务器Pyton辅助运维
01.自动Copy文件(文件夹)到远程服务器所在目录
开发环境:
u Web服务器:
Windows Server 2008 R2 SP1
IIS 7.5
u 运维服务器:
工作内容说明:
生产环境中有很多台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服务器在同一个局域网中.
Windows服务器Pyton辅助运维--01.自动Copy文件(文件夹)到远程服务器所在目录的更多相关文章
- Windows服务器Pyton辅助运维--02.远程重启IIS服务器
Windows服务器Pyton辅助运维 02.远程重启IIS服务器 开发环境: u Web服务器: Windows Server 2008 R2 SP1 IIS 7.5 u 运维服务器: Pyth ...
- Windows服务器Pyton辅助运维--03.安装Visual Studio 的 Python 开发插件 PTVS
PTVS (Python Tools for Visual Studio) http://pytools.codeplex.com/ 当前版本:2.1 RC PTVS (Python Tools fo ...
- 运维开发:python websocket网页实时显示远程服务器日志信息
功能:用websocket技术,在运维工具的浏览器上实时显示远程服务器上的日志信息 一般我们在运维工具部署环境的时候,需要实时展现部署过程中的信息,或者在浏览器中实时显示程序日志给开发人员看.你还在用 ...
- 运维小东西:每天备份sql到远程服务器上
首先两台服务器可以无密码登录(这个方式比较简单,当然安全系数会降低) #ssh-keygen -t rsa #生成密钥发送给远程服务器上 #ssh-copy-id ~/root/id_rsa.pub ...
- 快速搭建windows服务器的可视化运维环境
开发好的程序部署在服务器上,如何对服务器的基本指标进行监控呢?最近对一套工具进行了研究,可以快速搭建服务器监管环境,很是强大,最重要的是它还很酷炫. 原理:数据采集+时序数据库+可视化,下面记录一下搭 ...
- Facebook 运维内幕曝光:一人管理2万台服务器
Facebook 运维内幕曝光:一人管理2万台服务器 oschina 发布于: 2013年11月23日 (29评) 分享到 新浪微博腾讯微博 收藏+32 11月30日 珠海 源创会,送U盘,先到先得 ...
- Windows系统 本地文件如何复制到远程服务器
很多人在使用远程服务器的时候往往要将本地的文件传输到远程服务器内,方法有很多种,下面介绍下如何使用Windows自带的远程桌面连接程序将文件复制到远程服务器内. 1.首先,点击windows开始按钮, ...
- Linux系统复制文件/文件夹到远程服务器
从一个服务器复制文件到另一个服务器,或者从本地到远程复制是 Linux 管理员的日常任务之一. 我觉得不会有人不同意,因为无论在哪里这都是你的日常操作之一.有很多办法都能处理这个任务,我们试着加以概括 ...
- Nginx+upstream针对后端服务器容错的运维笔记
熟练掌握Nginx负载均衡的使用对运维人员来说是极其重要的!下面针对Nignx负载均衡upstream容错机制的使用做一梳理性说明: 一.nginx的upstream容错 1)nginx 判断节点失效 ...
随机推荐
- 利用MyEclipse的ant插件生成Hibernate的映射文件
先下载:xdoclet-plugins-dist-1.0.4-bin build.xml文件 <?xml version="1.0" encoding="UTF-8 ...
- Codeforces 362D Fools and Foolproof Roads 构造题
题目链接:点击打开链接 题意: 给定n个点 m条边的无向图 须要在图里添加p条边 使得图最后连通分量数为q 问是否可行,不可行输出NO 可行输出YES,并输出加入的p条边. set走起.. #incl ...
- 跨域请求,关于后端session会话丢失的解决办法
目前使用前后端分离的模式开发,后端提供跨域接口.前端jsonp调用,绑定数据,但是在该站点下有个人中心模块存在的情况下,服务端的session会话会被跨域请求覆盖改掉 大家都知道tomcat使用coo ...
- Android 网络编程与通信协议
大多数的Android应用程序都会使用HTTP协议来发送和接收网络数据,而Android中主要提供了两种方式来进行HTTP操作, HttpURLConnection和HttpClient.这两种方式都 ...
- Android - ContentProvider机制
以下资料摘录整理自老罗的Android之旅博客,是对老罗的博客关于Android底层原理的一个抽象的知识概括总结(如有错误欢迎指出)(侵删):http://blog.csdn.net/luosheng ...
- css08盒子模型
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- HTML5文件加载进度管理
/** * 文件加载进度管理 */ DownloadUtils = function(options){ options = options || {}; this.init(options); }; ...
- no drawer view found with gravity RIGHT(Android实现侧滑菜单从右面滑出) 解决办法
代码如下: <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width ...
- c - 给分数分级别
/* 题目: 学习成绩>=90 分的同学用 A 表示, 80-89 分之间的用 B 表示,70-79 分的用 C 表示, 60-69 分用 D表示,小于60分用E表示. 分析: 使用swith. ...
- 图文教程:手把手教你用U盘安装Ubuntu
说到ubuntu,有接触linux的童鞋都应该听过,用wubi安装只是像在电脑上安装一个软件,可以轻松体验ubuntu,不过毕竟性能会打折扣,所以本人是比较喜欢直接安装在硬盘上的. 这种方法只适合用d ...