如何用 Python 重啟遠端電腦 (WMI 教學)

4/23/2021 PythonPandasRemote

有時我們常會須要一次重開多台電腦,有沒有辦法透過 Python 來幫我們完成這個動作呢?
這篇來介紹該如何用 VMI 這個套件來幫我們完成這件事

# 遠端至其他伺服器

首先,我們把要重開的電腦 IP 都先記錄在 Excel 中,假設該 Excel 中有多個分頁,我們也可以在 pd.read_excel 的第二個參數指定分頁名稱

這邊我們的分頁名稱是 LLDOS002,且 Excel 的檔案位置在 Desktop\RPQS\RPQS.xlsx

ipList 則是取出分頁 LLDOS002 中的 IP 這一欄,並儲存成 list,接著逐一取出每個 IP,並用 wmi.WMI 來遠端進每個 IP

最後用 os.Reboot() 來重開該 IP,並將重開的 IP 存到 restartedIp,等一下可以藉由 restartedIp 將這些重開後的 IP 寄封信給自己

### Remote Account 
username = 'UserNameXXX'
password = 'PasswordXXX'

### Read files
desktopPath = winshell.desktop() # Get desktop path
filePath = desktopPath + r'\\RPQS\RPQS.xlsx'

# parameters(file path, sheet name)
reports = pd.read_excel(filePath, 'LLDOS002')

# Get IP from the report, remove nan in the Series & convert it from series to list
ipList = reports['IP'].dropna().tolist()

# Storing restarted IPs for sending mail
restartedIp = []

### Remote to PCs
def remotePC(ip, restartedIp):
    print('Logging to IP:', ip)
    try:
        # Initialize the COM libraries for the calling thread
        pythoncom.CoInitialize()
        # using WMI to connect PC remotely
        conn = wmi.WMI(ip, user=username, password=password)
        os = conn.Win32_OperatingSystem(Primary=1)[0]

        # start to restart PCs
        os.Reboot()
        print('IP:', ip, 'was restarted')
        print('')
        # Add ip to the ip list
        restartedIp.append(ip)
        return restartedIp
    except Exception as e:
        print('{} Logging failed'.format(ip))
        print('Excetion: {}'.format(e))


for ip in ipList:
    remotePC(ip, restartedIp)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# 寄送已重開 IP 郵件

想了解怎麼利用 Python 寄送郵件,可參考這篇

如何用 Python 寄送 HTML 郵件 ( Email ) (opens new window)

### Email Server Settings 
smtp_server = "mail.mailserver.com"
port = 25  # For starttls
server = smtplib.SMTP(smtp_server, port)
sender = "sender@mail.com"
receiver = "receiver@mail.com"
cc = ["cc@mail.com"]
receiverList = []


### Send notification Mail 
def sendMail(restartedIp):
    print('Send mail list = ', restartedIp)
    message = """\
        <html>
        <head></head>
        <body>

        The following PCs have been restarted:  <br/><br/>
        IP <br/><br/>
        {restartedIp} <br/><br/>
        </body>
        </html>
        """.format(restartedIp = restartedIp)

    msg = MIMEMultipart('alternative')
    msg = MIMEText(message, 'html')
    msg['Subject'] = "The following PCs have been restarted for updating Windows and antivirus"
    msg['Form'] = sender
    msg['To'] = receiver
    msg['Cc'] = ','.join(cc)

    toAddress = [receiver] + cc
    server.sendmail(sender, toAddress, msg.as_string())
    print("Mail was sent")
    server.quit()


sendMail(restartedIp)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

# Source Code

import winshell
import wmi
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import pandas as pd
import numpy as np
import pythoncom

### Read files
desktopPath = winshell.desktop() # get desktop path
filePath = desktopPath + r'\\RPQS\RPQS.xlsx'

# parameters(file path, sheet name)
reports = pd.read_excel(filePath, 'LLDOS002')

# Get IP from the report, remove nan in the Series & convert it from series to list
ipList = reports['IP'].dropna().tolist()

# Storing restarted IPs for sending mail
restartedIp = []

### Remote Account 
username = 'UserNameXXX'
password = 'PasswordXXX'


### Email Server Settings 
smtp_server = "mail.mailserver.com"
port = 25  # For starttls
server = smtplib.SMTP(smtp_server, port)
sender = "sender@mail.com"
receiver = "receiver@mail.com"
cc = ["cc@mail.com"]
receiverList = []


### Send notification Mail 
def sendMail(restartedIp):
    print('Send mail list = ', restartedIp)
    message = """\
        <html>
        <head></head>
        <body>

        The following PCs have been restarted:  <br/><br/>
        IP <br/><br/>
        {restartedIp} <br/><br/>
        </body>
        </html>
        """.format(restartedIp = restartedIp)

    msg = MIMEMultipart('alternative')
    msg = MIMEText(message, 'html')
    msg['Subject'] = "The following PCs have been restarted for updating Windows and antivirus"
    msg['Form'] = sender
    msg['To'] = receiver
    msg['Cc'] = ','.join(cc)

    toAddress = [receiver] + cc
    server.sendmail(sender, toAddress, msg.as_string())
    print("Mail was sent")
    server.quit()


### Remote to PCs
def remotePC(ip, restartedIp):
    print('Logging to IP:', ip)
    try:
        # Initialize the COM libraries for the calling thread
        pythoncom.CoInitialize()
        # using WMI to connect PC remotely
        conn = wmi.WMI(ip, user=username, password=password)
        os = conn.Win32_OperatingSystem(Primary=1)[0]

        # start to restart PCs
        os.Reboot()
        print('IP:', ip, 'was restarted')
        print('')
        # Add ip to the ip list
        restartedIp.append(ip)
        return restartedIp
    except Exception as e:
        print('{} Logging failed'.format(ip))
        print('Excetion: {}'.format(e))


for ip in ipList:
    remotePC(ip, restartedIp)

sendMail(restartedIp)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
Last Updated: 6/30/2023, 1:40:10 AM

歡迎點擊追蹤:

(adsbygoogle = window.adsbygoogle || []).push({});