Python changes the name of Windows 10 computer to take effect without restarting

Generally speaking, when you modify the computer name in Windows computer properties, you need to restart the computer for it to take effect.

In fact, the computer name is stored in the Windows registry. We can modify the computer name by directly modifying the registry.

The modification process is as follows:

  1. Create new registry files according to rules and define new computer names;
  2. Use the regedit /s command to import the registry generated previously;
  3. Finally, use the python module subprocess.call() to call the windows system cmd command line for execution.
import subprocess

name = 'Python_Test7'
scripts = '''REGEDIT4 
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName] 
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName]  
"ComputerName"="{name}" 
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName]  
"ComputerName"="{name}" 
[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\ComputerName\ComputerName]  
"ComputerName"="{name}" 
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]  
"NV Hostname"="{name}"  
"Hostname"="{name}" 
[HKEY_USERS\S-1-5-18\Software\Microsoft\Windows\ShellNoRoam]  
@="{name}" 
[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\ComputerName\ActiveComputerName]  
"ComputerName"="{name}" 
[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Tcpip\Parameters]  
"NV Hostname"="{name}"  
"Hostname"="{name}" 
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]  
"DefaultDomainName"="{name}"  
"AltDefaultDomainName"="{name}" '''
cmdline = scripts.format('{}',name=name).split('\n')
cmdlines = []
for v in  cmdline:
    cmdlines.append(v + '\n')

fileName = 'c:/windows/reg.reg'
with open(fileName,'w',encoding='utf-8') as file:
    file.writelines(cmdlines)

cmd_rename = 'regedit /s c:/windows/reg.reg'
subprocess.call(cmd_rename)

reference:

Yiliang Cool. Modify the computer name with one click (no need to restart) . CSDN Blog. 2019.07

Guess you like

Origin blog.csdn.net/xiaoyw/article/details/132410300