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服务器在同一个局域网中.

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

  1. Windows服务器Pyton辅助运维--02.远程重启IIS服务器

    Windows服务器Pyton辅助运维 02.远程重启IIS服务器 开发环境: u  Web服务器: Windows Server 2008 R2 SP1 IIS 7.5 u  运维服务器: Pyth ...

  2. Windows服务器Pyton辅助运维--03.安装Visual Studio 的 Python 开发插件 PTVS

    PTVS (Python Tools for Visual Studio) http://pytools.codeplex.com/ 当前版本:2.1 RC PTVS (Python Tools fo ...

  3. 运维开发:python websocket网页实时显示远程服务器日志信息

    功能:用websocket技术,在运维工具的浏览器上实时显示远程服务器上的日志信息 一般我们在运维工具部署环境的时候,需要实时展现部署过程中的信息,或者在浏览器中实时显示程序日志给开发人员看.你还在用 ...

  4. 运维小东西:每天备份sql到远程服务器上

    首先两台服务器可以无密码登录(这个方式比较简单,当然安全系数会降低) #ssh-keygen -t rsa #生成密钥发送给远程服务器上 #ssh-copy-id ~/root/id_rsa.pub ...

  5. 快速搭建windows服务器的可视化运维环境

    开发好的程序部署在服务器上,如何对服务器的基本指标进行监控呢?最近对一套工具进行了研究,可以快速搭建服务器监管环境,很是强大,最重要的是它还很酷炫. 原理:数据采集+时序数据库+可视化,下面记录一下搭 ...

  6. Facebook 运维内幕曝光:一人管理2万台服务器

    Facebook 运维内幕曝光:一人管理2万台服务器 oschina 发布于: 2013年11月23日 (29评) 分享到  新浪微博腾讯微博 收藏+32 11月30日 珠海 源创会,送U盘,先到先得 ...

  7. Windows系统 本地文件如何复制到远程服务器

    很多人在使用远程服务器的时候往往要将本地的文件传输到远程服务器内,方法有很多种,下面介绍下如何使用Windows自带的远程桌面连接程序将文件复制到远程服务器内. 1.首先,点击windows开始按钮, ...

  8. Linux系统复制文件/文件夹到远程服务器

    从一个服务器复制文件到另一个服务器,或者从本地到远程复制是 Linux 管理员的日常任务之一. 我觉得不会有人不同意,因为无论在哪里这都是你的日常操作之一.有很多办法都能处理这个任务,我们试着加以概括 ...

  9. Nginx+upstream针对后端服务器容错的运维笔记

    熟练掌握Nginx负载均衡的使用对运维人员来说是极其重要的!下面针对Nignx负载均衡upstream容错机制的使用做一梳理性说明: 一.nginx的upstream容错 1)nginx 判断节点失效 ...

随机推荐

  1. 通过模拟器和ida搭建Android动态调试环境的问题

    这几天在学Android的native层逆向.在按照教程用ida搭建动态调试环境时,第一步是把android_server 放到手机里执行,但是在手机里可以,在genymotion模拟器上就提示 no ...

  2. python Sina微博自动转发带抽奖字样的微博,添加关注,取消关注

    项目地址:https://github.com/chengshuyi/SinaWeibo 具有的功能 转发带抽奖字样的微博并可以@相应数量的好友 提取关注并添加关注 取消关注 获取粉丝列表

  3. svn不提交user文件

    http://godera.blog.163.com/blog/static/215023060201312011112966/

  4. 95秀-dialog 进度对话框 实用工具

    工具Util public class DialogUtil {     public static ProgressDialogView progressDialog;     /**      * ...

  5. css书写步骤

    CSS整体书写步骤1:CSS RESET 重置2:CSS GLABAL 全局属性3: CSS分模块属性,(先写默认样式和设计图相差最大的部分,先大块布局,后细致调整) <style>/*C ...

  6. 各种乱码,编码问题设置方法整理(UTF-8)

    一.tomcat中文乱码问题 打开tomcat安装目录,在conf文件夹中找到server.xml文件 ,找到   <Connector port="8009" protoc ...

  7. request.ServerVariables获取环境变量

    Request.ServerVariables("HTTP_X_FORWARDED_FOR")  透过代理服务器取得客户端的真实IP地址,有些用此方法读取到的仍然是代理服务器的IP ...

  8. c - 2/1, 3/2, 5/3, 8/5, 13/8...前20项的和

    double pres(const int n) { ; //分子. ; //分母. ; double tmp; ; i <= n; i++) { sum += (numerator / den ...

  9. 重置MySQL的root用户密码(Window)

    1.首先要停止Mysql服务.打开CMD,键入命令 net stop mysql 默认的mysql服务名就是mysql,如果你修改过服务名,请自行对照修改命令. 2.在CMD中进入mysql的bin目 ...

  10. java关键字 (jdk6),各自的含义是什么?

    Abstract 抽象的 一个Java语言中的关键字,用在类的声明中来指明一个类是不能被实例化的,但是可以被其它类继承.一个抽象类可以使用抽象方法,抽象方法不需要实现,但是需要在子类中被实现. bre ...