Windows服务器Pyton辅助运维--02.远程重启IIS服务器
Windows服务器Pyton辅助运维
02.远程重启IIS服务器
开发环境:
u Web服务器:
Windows Server 2008 R2 SP1
IIS 7.5
u 运维服务器:
工作内容说明:
每次排除故障的时候开发人员都会要求重启Web服务器上的IIS,有很多台IIS服务器需要重启,当然Google知道bat可以搞定这件事,但是本文用python来搞定。
实现过程:
先准备以下几个问题
使用Windows自带命令行工具如何远程重启IIS?
- WMI服务
需要远程服务器安装并启动WMI服务
如何写命令?
2. Psexesc工具
首先去微软网站上下载这个工具
然后执行下面这个命令
psexec \\192.168.1.X -u administrator -p ***** iisreset
然后会输出如下
Python代码的设计思路?
- 去搜个WMI的Python库(本文所采用)
- 去搜个Psexec的Python库(搜到了不会用Corelabs的Impacket)
- 直接import os 执行psexec远程命令(有问题无法看到返回信息)
整一个配置文件记录基本信息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实现代码如下RemoteCommands.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:
ip = webServer
username = UserId
password = Password
print ''; server = WindowsMachine(ip, username, password)
resultlist = server.run_remote('iisreset',async=True, output=True);
for linestring in resultlist:
print linestring 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 run_remote(self, cmd, async=False, minimized=True, output=False):
"""
this function runs cmd on remote machine, using wmi. the function create a .bat file,
copies it to the remote machine, and runs the .bat file
inputs: cmd - command to run
async - False, waits for command to finish, True, return immidiatly
mimimized - window state
output - True, returns the command's output
output: return value of the command
output of the command if true
"""
output_data = None
pwd = os.getcwd()
bat_local_path = os.path.join(pwd, 'output_{0}.bat'.format(self.ip))
bat_remote_path = os.path.join(self.remote_path, 'output_{0}.bat'.format(self.ip))
output_remote_path = os.path.join(self.remote_path, 'output_{0}.out'.format(self.ip))
output_local_path = os.path.join(pwd, 'output_{0}.out'.format(self.ip))
text = cmd + " > " + output_remote_path
create_file(bat_local_path, text)
self.net_copy(bat_local_path, self.remote_path)
batcmd = bat_remote_path SW_SHOWMINIMIZED = 0
if not minimized:
SW_SHOWMINIMIZED = 1
print "Executing %s" %cmd
startup = self.connection.Win32_ProcessStartup.new (ShowWindow=SW_SHOWMINIMIZED)
process_id, return_value = self.connection.Win32_Process.Create (CommandLine=batcmd, ProcessStartupInformation=startup)
if async:
watcher = self.connection.watch_for (
notification_type="Deletion",
wmi_class="Win32_Process",
delay_secs=1,
)
watcher () if output:
print 'copying back ' + output_remote_path
self.net_copy_back(output_remote_path, output_local_path)
output_data = open(output_local_path, 'r')
output_data = "".join(output_data.readlines())
self.net_delete(output_remote_path)
self.net_delete(bat_remote_path)
return return_value, output_data 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 net_copy_back(self, source_file, dest_file):
""" Copies files or directories to a remote computer. """
print "Start copying files " + source_file + " back from " + self.ip
if self.username == '':
shutil.copy(source_file, dest_file)
else:
self._wnet_connect()
source_unc = self._covert_unc(source_file)
shutil.copyfile(source_unc, dest_file) 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' def net_delete(self, path):
""" Deletes files or directories on a remote computer. """
try:
if self.username == '':
os.remove(path) else:
self._wnet_connect() path = self._covert_unc(path)
if os.path.exists(path):
# Delete directory tree if object is a directory.
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
else:
# Remove anyway if non-existent so as to raise an error.
os.remove(path)
except:
print 'could not delete ', path if __name__ == "__main__":
main()
备注:请确保在一个运维机器和Web服务器在同一个局域网中.请确保远程服务器WMI服务开启.
Windows服务器Pyton辅助运维--02.远程重启IIS服务器的更多相关文章
- Windows服务器Pyton辅助运维--01.自动Copy文件(文件夹)到远程服务器所在目录
Windows服务器Pyton辅助运维 01.自动Copy文件(文件夹)到远程服务器所在目录 开发环境: u Web服务器: Windows Server 2008 R2 SP1 IIS 7.5 u ...
- Windows服务器Pyton辅助运维--03.安装Visual Studio 的 Python 开发插件 PTVS
PTVS (Python Tools for Visual Studio) http://pytools.codeplex.com/ 当前版本:2.1 RC PTVS (Python Tools fo ...
- 自动化运维,远程交互从服务器A上ssh到服务器B上,然后执行服务器B上的命令。
第一种: ftp -v -n 192.168.0.1 21 <<! user ftp ftp123 bay ! 第二种: { echo -e "\n" echo -e ...
- 快速搭建windows服务器的可视化运维环境
开发好的程序部署在服务器上,如何对服务器的基本指标进行监控呢?最近对一套工具进行了研究,可以快速搭建服务器监管环境,很是强大,最重要的是它还很酷炫. 原理:数据采集+时序数据库+可视化,下面记录一下搭 ...
- 2019/01/17 基于windows使用fabric将gitlab的文件远程同步到服务器(git)
觉得django项目把本地更新push到gitlab,再执行fabric脚本从gitlab更新服务器项目挺方便的,当然从本地直接到服务器就比较灵活. 2019/01/17 基于windows使用fab ...
- powershell 远程重启/关闭服务器
powershell 远程重启/关闭服务器 #启动winrm PS C:\Windows\system32> winrm quickconfig -q #设置信任主机 PS C:\Windows ...
- Nginx+upstream针对后端服务器容错的运维笔记
熟练掌握Nginx负载均衡的使用对运维人员来说是极其重要的!下面针对Nignx负载均衡upstream容错机制的使用做一梳理性说明: 一.nginx的upstream容错 1)nginx 判断节点失效 ...
- 高级运维(二):搭建Nginx服务器、用户认证、基于域名的虚拟主机、SSL虚拟主机、Nginx反向代理
一.搭建Nginx服务器 目标: 在IP地址为192.168.4.5的主机上安装部署Nginx服务,并可以将Nginx服务器,要求编译时启用如下功能: 1> SSL加密功能 2> 设置Ng ...
- VisualStudio2017 远程 调试 IIS 服务器 web网站
小伙伴们,本次测试好好的程序发布到服务器挂到IIS后我勒个*,,, 神马情况,为啥和我本地运行结果不一致,Fuc*... 没遇到的小伙伴估计也看不到此篇文章了吧,Log日志调试,嗯 不错,good i ...
随机推荐
- django种表单post出现CSRF verification failed( CSRF验证失败 ) 的两种解决方式
现象 表单界面例如以下: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc29sbG9yNTI1/font/5a6L5L2T/fontsize/400/fi ...
- vs2008打包公布程序
vs2008打包公布程序 一vs2008中新建 安装项目,确定(新建 安装向导 也能够) 二.加入内容 1.加入主要内容: 应用程序目录=>右键=>加入=>文件,找到须要的文件,包含 ...
- CVPR读书笔记[5]:Gabor特征提取之Gabor核的实现
朱金华 jinhua1982@gmail.com 2014.08.09 本文參考http://blog.csdn.net/njzhujinhua/article/details/38460861 ...
- 如何为Myeclipse手工添加dtd支持
一.引言 在MyEclipse中开发三大框架的项目时候经常会写一些配置的xml文件,例如:Struts2的struts.xml和Hibernate的hibernate.cfg.xml.Spring的a ...
- WIN7 64位上 MYSQL的ODBC一些个人理解
最近电脑中毒了,无奈之下把32位的xp换成了64位的win7,无聊耗时的搭完开发环境,装了vs6.0(忽略掉一切的不兼容),装完64位的mysql(“mysql-5.6.10-winx64.zip”) ...
- Tab标签栏 切换 权威总结
angular的标签栏,有两种方法实现: 内容全部加载到页面中,再利用ng-show指令. 将每一块要加载的内容做成模板,利用ng-if指令加载. 用bootstrap的tab组件 用angular的 ...
- 手机Web网站,设置拒绝电脑访问
最近一段时间,都在使用Jquery-Mobile + MVC做手机Web,有一些心得.体会 下面介绍如何拒绝电脑访问手机网站 电脑的浏览器,跟手机的浏览器内核不一样,这是我设置拒绝访问的思路. 下面是 ...
- [php基础]PHP Form表单验证:PHP form validator使用说明
在PHP网站开发建设中,用户注册.留言是必不可少的功能,用户提交的信息数据都是通过Form表单提交,为了保证数据的完整性.安全性,PHP Form表单验证是过滤数据的首要环节,PHP对表单提交数据的验 ...
- 一个打砖块的小游戏1.0 KILL THE BLOCKS !
/******************************************** * 程序名称:MR.DUAN 的打砖块(KILL THE BLOCKS !) * 作 者:WindAutum ...
- c-100米球反弹
#include <iostream> #define TIMES 10 int main(void) { ; ; //第一次反弹的高度. ; i <= TIMES; i++) { ...