Change IP address_Auto log in to Netgear Router to Crawling an available IP w xpath_REG_SZ_WinError5

Use urllib to login in to the Netgear router

import urllib

user = 'admin'
pwd = 'LlQ54951'
host = '192.168.1.1'
url = 'http://' + host

passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, host, user, pwd)
authhandler = urllib.request.HTTPBasicAuthHandler(passman)

opener = urllib.request.build_opener(authhandler)
response = opener.open( url )

stuff = response.read()
response.close()

stuff

Use webdriver to login in to the Netgear router

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import win32com.client

driver = webdriver.Chrome( executable_path = "C:/chromedriver/chromedriver"
                          )

wait = WebDriverWait( driver, 2 )

username = 'admin'
password = 'LlQ54951'
url = 'http://192.168.1.1' #'http://192.168.1.1' # OR # 'http://routerlogin.net'

print(url)

wait = WebDriverWait(driver, 2)
driver.get( url ) # for netgear router
    
# https://social.technet.microsoft.com/wiki/contents/articles/5169.vbscript-sendkeys-method.aspx
shell = win32com.client.Dispatch("WScript.Shell")  
shell.Sendkeys(username)
shell.SendKeys('{ENTER}')
shell.Sendkeys('{TAB}')
shell.Sendkeys(password)
shell.SendKeys('{ENTER}')

while driver.current_url == 'http://routerlogin.net/MNU_access_setRecovery_index.htm' or \
        driver.current_url == 'http://192.168.1.1/MNU_access_setRecovery_index.htm':
    driver.get( url )
    shell = win32com.client.Dispatch("WScript.Shell")  
    shell.Sendkeys(username)
    shell.SendKeys('{ENTER}')
    shell.Sendkeys('{TAB}')
    shell.Sendkeys(password)
    shell.SendKeys('{ENTER}')
    
print( driver.current_url )
driver.page_source

Don't move your mouse(Check if the keyboard is in lowercase character mode, if not, click Tab key):

Why Using win32com.client.Dispatch("WScript.Shell") ?
Because: the login prompt of netgear is not an Alert.

 Note: http://192.168.1.1/DashBoard.htm

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import win32com.client

driver = webdriver.Chrome( executable_path = "C:/chromedriver/chromedriver"
                          )

wait = WebDriverWait( driver, 2 )

username = 'admin'
password = 'LlQ54951'
url = 'http://192.168.1.1' #'http://192.168.1.1' # OR # 'http://routerlogin.net'

print(url)

wait = WebDriverWait(driver, 2)
driver.get( url ) # for netgear router
    
# https://social.technet.microsoft.com/wiki/contents/articles/5169.vbscript-sendkeys-method.aspx
shell = win32com.client.Dispatch("WScript.Shell")  
shell.Sendkeys(username)
shell.SendKeys('{ENTER}')
shell.Sendkeys('{TAB}')
shell.Sendkeys(password)
shell.SendKeys('{ENTER}')

while driver.current_url == 'http://routerlogin.net/MNU_access_setRecovery_index.htm' or \
        driver.current_url == 'http://192.168.1.1/MNU_access_setRecovery_index.htm':
    driver.get( url )
    shell = win32com.client.Dispatch("WScript.Shell")  
    shell.Sendkeys(username)
    shell.SendKeys('{ENTER}')
    shell.Sendkeys('{TAB}')
    shell.Sendkeys(password)
    shell.SendKeys('{ENTER}')
    
print( driver.current_url )
# driver.get(url+'/DashBoard.htm')

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait.until( EC.presence_of_element_located( (By.ID, 
                                             'page_contain'
                                            ) 
                                          ) )

# since iframe id='page'
driver.switch_to.frame( driver.find_element_by_id("page") )

# OR # driver.find_element_by_xpath( '//html/body/table/tbody/tr[1]/td[3]' ).click()
driver.find_element_by_xpath( '//td[@id="AttachedDevices"]' ).click()
print( driver.current_url )

#driver.switch_to.frame( driver.find_element_by_id("page") )

# tr_list = driver.find_elements_by_xpath('//*[@id="target"]/table/tbody/tr[1]/td/div/table/tbody/tr[4]/td/table/tbody/tr')

# //*[@id="target"]/table/tbody/tr[1]/td/div/table/tbody/tr[4]/td/table/tbody/tr[1]

import pandas as pd
# full xpath: /html/body/div/form/table/tbody/tr[1]/td/div/table/tbody/tr[4]/td/table
df = pd.read_html( driver.page_source, header=0)[3] # [3] the 3th table from outside, 

 

df

AttachedDevices:

df= df.iloc[:,1:5]
df

df['Connection Type'].str.contains("NaN")

 

df = df[ df['Connection Type'].str.contains("NaN")==False ]
df

 

Go to Advance: 

# /html/body/table/tbody/tr/td/table[2]/tbody/tr/td/ul/li[2]/a
# If you did switch to the iframe, you cannot continue to manipulate the elements of the main document. 
# If you want to manipulate the content of the main document, you need to switch back to the main document:
driver.switch_to.default_content()
driver.find_element_by_xpath('//a[@id="AdvanceTab"]').click()

Click Setup ==> 

# /html/body/table/tbody/tr/td/table[2]/tbody/tr/td/div[2]/table/tbody/tr/td[1]/ul/li[4]/a
# //*[@id="setup_header"]/a
driver.find_element_by_xpath('//li[@id="setup_header"]').click()
wait.until( EC.presence_of_element_located( (By.ID, 
                                             'setup_header'
                                            ) 
                                          ) )

 Go to http://192.168.1.1/LAN_Lan.htm

# https://blog.csdn.net/Linli522362242/article/details/95042034
# <li class="SubActive" id="setup_header"> <a href="#"><span>Setup</span></a> </li>
# <li class="subHeader" id="set_hdr" style="display: list-item;"> 
#         <ul style="width:100%;height:128px">                               
#             <li class="SubMenu SubMenuWDS" id="int_set"><a href="BAS_basic.htm" onclick="return false"><span class="subMenu_text">Internet Setup</span></a></li>                                     
#             <li class="SubMenu SubMenu" id="wireless_set"><a href="WLG_wireless_dual_band_r8000.htm" onclick="return false"><span class="subMenu_text">Wireless Setup</span></a></li>
#             <li class="SubMenu SubMenuWDS" id="wan_set"><a href="WAN_wan.htm" onclick="return false"><span class="subMenu_text">WAN Setup</span></a></li>
#                                                #      ###
#             <li class="SubMenuWDS SubMenu" id="LAN_set"><a href="LAN_lan.htm" onclick="return false">
#                                                           <span class="subMenu_text">LAN Setup</span>
#                                                         </a>
#             </li>
#                                                #      ###
#             <li class="SubMenu SubMenuWDS" id="Qos_set"><a href="QOS_down_streaming_iqos.htm" onclick="return false"><span class="subMenu_text">QoS Setup</span></a></li>
#             <li class="SubMenu SubMenu" id="guest_set"><a href="WLG_wireless_dual_band_2_r8000.htm" onclick="return false"><span class="subMenu_text">Guest Network</span></a></li>
#         </ul>				            
#     </li>
# You can use:
# driver.find_element_by_xpath('//li[@id="setup_header"]/following-sibling::li[1]/ul/li[@id="LAN_set"]').click()
# OR 
# driver.find_element_by_xpath('//li[@id="LAN_set"]').click()
# OR
# note "text" is also an node, text()==> ../ ==> span ==>../ ==> a ==> ../ ==> li[@id="LAN_set"]
# driver.find_element_by_xpath('//a/span[text()="LAN Setup"]/../../../li[@id="LAN_set"]').click()
# OR
driver.find_elements_by_xpath('//a/span[text()="LAN Setup"]')[0].click() # click a
# OR # I'm not suggest to use find_element_by_xpath for link 'a' since sometimes will appear an error
# driver.find_element_by_xpath('//a/span[text()="LAN Setup"]').click() # click a

 Ctrl + F  and enter "254" OR dhcp_end OR dhcp_start to locate

 # Since input[@name="dhcp_start"] is in iframe[id="page2"]

driver.switch_to.frame( driver.find_element_by_id("page2") )
# /html/body/div/form/input[12]
dhcp_start = driver.find_element_by_xpath('//input[@name="dhcp_start"]').get_attribute("value")
dhcp_end = driver.find_element_by_xpath('//input[@name="dhcp_end"]').get_attribute("value")

ip_address = driver.find_element_by_xpath('//input[@name="lan_ipaddr"]').get_attribute("value")
ip_subnet_mask = driver.find_element_by_xpath('//input[@name="lan_netmask"]').get_attribute("value")

driver.quit()
print('DHCP start:', dhcp_start)
print('DHCP end:', dhcp_end)
print('IP Address:', ip_address)
print('IP Subnet Mask:', ip_subnet_mask)

   

 Get IP address reservation table(Prevent others from using the reserved IP address, and avoid IP address conflicts as well):

# note we are inside the first table
# /html/body/div/form/   table   /tbody/tr[2]/td/div/table/tbody/tr[15]/td/table/tbody
reservation_df = pd.read_html( driver.page_source, header=0 )[2] # [3] the 2th table inside first table
reservation_df = reservation_df.iloc[:, 2:reservation_df.shape[1]]    
print(reservation_df)

driver.quit()

 OR 

All code used in previous:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import win32com.client

driver = webdriver.Chrome( executable_path = "C:/chromedriver/chromedriver"
                          )

wait = WebDriverWait( driver, 2 )

username = 'admin'
password = 'LlQ54951'
url = 'http://routerlogin.net' #'http://192.168.1.1' # OR # 'http://routerlogin.net'

print(url)

wait = WebDriverWait(driver, 2)
driver.get( url ) # for netgear router
    
# https://social.technet.microsoft.com/wiki/contents/articles/5169.vbscript-sendkeys-method.aspx
shell = win32com.client.Dispatch("WScript.Shell")  
shell.Sendkeys(username)
shell.SendKeys('{ENTER}')
shell.Sendkeys('{TAB}')
shell.Sendkeys(password)
shell.SendKeys('{ENTER}')

while driver.current_url == 'http://routerlogin.net/MNU_access_setRecovery_index.htm' or \
        driver.current_url == 'http://192.168.1.1/MNU_access_setRecovery_index.htm':
    driver.get( url )
    shell = win32com.client.Dispatch("WScript.Shell")  
    shell.Sendkeys(username)
    shell.SendKeys('{ENTER}')
    shell.Sendkeys('{TAB}')
    shell.Sendkeys(password)
    shell.SendKeys('{ENTER}')
    
print( driver.current_url )
# driver.get(url+'/DashBoard.htm')

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait.until( EC.presence_of_element_located( (By.ID, 
                                             'page_contain'
                                            ) 
                                          ) )

# since iframe id='page'
driver.switch_to.frame( driver.find_element_by_id("page") )

# OR # driver.find_element_by_xpath( '//html/body/table/tbody/tr[1]/td[3]' ).click()
driver.find_element_by_xpath( '//td[@id="AttachedDevices"]' ).click()
print( driver.current_url )

# tr_list = driver.find_elements_by_xpath('//*[@id="target"]/table/tbody/tr[1]/td/div/table/tbody/tr[4]/td/table/tbody/tr')

# //*[@id="target"]/table/tbody/tr[1]/td/div/table/tbody/tr[4]/td/table/tbody/tr[1]

import pandas as pd
# full xpath: /html/body/div/form/table/tbody/tr[1]/td/div/table/tbody/tr[4]/td/table
df = pd.read_html( driver.page_source, header=0)[3] # [3] the 3th table from outside, 

df= df.iloc[:,1:5]
df = df[ df['Connection Type'].str.contains("NaN")==False ]
print(df)

# /html/body/table/tbody/tr/td/table[2]/tbody/tr/td/ul/li[2]/a
# If you did switch to the iframe, you cannot continue to manipulate the elements of the main document. 
# If you want to manipulate the content of the main document, you need to switch back to the main document:
driver.switch_to.default_content()
driver.find_element_by_xpath('//a[@id="AdvanceTab"]').click()


# /html/body/table/tbody/tr/td/table[2]/tbody/tr/td/div[2]/table/tbody/tr/td[1]/ul/li[4]/a
# //*[@id="setup_header"]/a
driver.find_element_by_xpath('//li[@id="setup_header"]').click()
wait.until( EC.presence_of_element_located( (By.ID, 
                                             'setup_header'
                                            ) 
                                          ) )

# https://blog.csdn.net/Linli522362242/article/details/95042034
# <li class="SubActive" id="setup_header"> <a href="#"><span>Setup</span></a> </li>
# <li class="subHeader" id="set_hdr" style="display: list-item;"> 
#         <ul style="width:100%;height:128px">                               
#             <li class="SubMenu SubMenuWDS" id="int_set"><a href="BAS_basic.htm" onclick="return false"><span class="subMenu_text">Internet Setup</span></a></li>                                     
#             <li class="SubMenu SubMenu" id="wireless_set"><a href="WLG_wireless_dual_band_r8000.htm" onclick="return false"><span class="subMenu_text">Wireless Setup</span></a></li>
#             <li class="SubMenu SubMenuWDS" id="wan_set"><a href="WAN_wan.htm" onclick="return false"><span class="subMenu_text">WAN Setup</span></a></li>
#                                                #      ###
#             <li class="SubMenuWDS SubMenu" id="LAN_set"><a href="LAN_lan.htm" onclick="return false">
#                                                           <span class="subMenu_text">LAN Setup</span>
#                                                         </a>
#             </li>
#                                                #      ###
#             <li class="SubMenu SubMenuWDS" id="Qos_set"><a href="QOS_down_streaming_iqos.htm" onclick="return false"><span class="subMenu_text">QoS Setup</span></a></li>
#             <li class="SubMenu SubMenu" id="guest_set"><a href="WLG_wireless_dual_band_2_r8000.htm" onclick="return false"><span class="subMenu_text">Guest Network</span></a></li>
#         </ul>				            
#     </li>
# You can use:
# driver.find_element_by_xpath('//li[@id="setup_header"]/following-sibling::li[1]/ul/li[@id="LAN_set"]').click()
# OR 
# driver.find_element_by_xpath('//li[@id="LAN_set"]').click()
# OR
# note "text" is also an node, text()==> ../ ==> span ==>../ ==> a ==> ../ ==> li[@id="LAN_set"]
# driver.find_element_by_xpath('//a/span[text()="LAN Setup"]/../../../li[@id="LAN_set"]').click()
# OR
driver.find_elements_by_xpath('//a/span[text()="LAN Setup"]')[0].click() # click a

driver.switch_to.frame( driver.find_element_by_id("page2") )
# /html/body/div/form/input[12]
dhcp_start = driver.find_element_by_xpath('//input[@name="dhcp_start"]').get_attribute("value")
dhcp_end = driver.find_element_by_xpath('//input[@name="dhcp_end"]').get_attribute("value")

ip_address = driver.find_element_by_xpath('//input[@name="lan_ipaddr"]').get_attribute("value")
ip_subnet_mask = driver.find_element_by_xpath('//input[@name="lan_netmask"]').get_attribute("value")

# driver.quit()
print('DHCP start:', dhcp_start)
print('DHCP end:', dhcp_end)
print('IP Address:', ip_address)
print('IP Subnet Mask:', ip_subnet_mask)

# note we are inside the first table
# /html/body/div/form/   table   /tbody/tr[2]/td/div/table/tbody/tr[15]/td/table/tbody
reservation_df = pd.read_html( driver.page_source, header=0 )[2] # [3] the 2th table inside first table
reservation_df = reservation_df.iloc[:, 2:reservation_df.shape[1]]    
print(reservation_df)

driver.quit()

 Process Dataset:

ip_list=df['IP Address'].to_list()
ip_list.append(ip_address) # ip_list.append('192.168.1.1')

if reservation_df.shape[0] > 0:
    for ip in reservation_df['IP Address']:
        if ip not in ip_list:
            ip_list.append(ip_list)
    
ip_list=sorted( ip_list )
ip_list

 

used=[]
for ip in ip_list:
    used.append( ip.split('.')[-1] )

new_ip = np.random.randint( int( dhcp_start.split('.')[-1] ), 
                            int( dhcp_end.split('.')[-1] ) + 1,
                            size=1
                          )[0]    
while ip in used:
    new_ip = np.random.randint( int( dhcp_start.split('.')[-1] ), 
                                int( dhcp_end.split('.')[-1] ) + 1,
                                size=1
                              )[0]   
new_ip = '.'.join([ '192.168.1', str(new_ip) ])
new_ip

 

OR

import re

used=[]

# ip_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4', '192.168.1.5']
for ip in ip_list:
    used.append( re.sub( '([0-9]{1,3}.){3}', # pattern
                         '',
                         ip
                       )
               )
print(used)    

new_ip = np.random.randint( int( re.sub( '([0-9]{1,3}.){3}', # pattern
                                         '',
                                         dhcp_start,
                                       )
                               ),
                            int(  re.sub( '([0-9]{1,3}.){3}', # pattern
                                          '',
                                          dhcp_end,
                                        )
                               )+1,
                            size=1
                          )[0]    
while ip in used:
    new_ip = np.random.randint( int( re.sub( '([0-9]{1,3}.){3}', # pattern
                                             '',
                                             dhcp_start,
                                           )
                                   ),
                                int(  re.sub( '([0-9]{1,3}.){3}', # pattern
                                              '',
                                              dhcp_end,
                                            )
                                   )+1,
                                size=1
                              )[0] 
    
new_ip = '.'.join([ '192.168.1', str(new_ip) ])
new_ip

 

Change IP address

 https://docs.python.org/3/library/winreg.html#winreg.HKEY_LOCAL_MACHINE

  • winreg.HKEY_LOCAL_MACHINE

    Registry entries subordinate to从属于 this key define the physical state of the computer, 
    including data about the bus type, system memory, and installed hardware and software.

==>

import winreg

# winreg.HKEY_LOCAL_MACHINE
#      Registry entries subordinate to this key define the physical state of the computer, 
#      including data about the bus type, system memory, and installed hardware and software.

hkey = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, \
                       r'System\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}'
                     )
hkey

 

  •  winreg.QueryInfoKey(key)

    Returns information about a key, as a tuple.
    key is an already open key, or one of the predefined HKEY_* constants.

The result is a tuple of 3 items:

Index

Meaning

0

An integer giving the number of sub keys this key has.

1

An integer giving the number of values this key has.

2

An integer giving when the key was last modified (if available) as 100’s of nanoseconds since Jan 1, 1601.

Raises an auditing event winreg.QueryInfoKey with argument key.

keyInfo = winreg.QueryInfoKey( hkey )
keyInfo

 I don't think '132737717659219844' is a time stamp

import datetime
import time

current_timestamp =  time.time_ns()
print(current_timestamp)
#dt = datetime.utcfromtimestamp(1629999511229597900 // 1000000000)

dt = datetime.datetime(1970, 1, 1) + \
     datetime.timedelta(seconds=current_timestamp // 1000000000) + \
     datetime.timedelta(hours=-4)
dt.strftime('%Y-%m-%d %H:%M:%S')

 

  • winreg.EnumKey(keyindex)

    Enumerates subkeys of an open registry key, returning a string.

    key is an already open key, or one of the predefined HKEY_* constants.
    index is an integer that identifies the index of the key to retrieve.
    The function retrieves the name of one subkey each time it is called. It is typically called repeatedly until an OSError exception is raised, indicating, no more values are available.
    Raises an auditing event winreg.EnumKey with arguments keyindex.
  • winreg.QueryValueEx(keyvalue_name)

    Retrieves the type and data for a specified value name associated with an open registry key.

    key is an already open key, or one of the predefined HKEY_* constants.

    value_name is a string indicating the value to query.

    The result is a tuple of 2 items:

    Index

    Meaning

    0

    The value of the registry item.

    1

    An integer giving the registry type for this value (see table in docs for SetValueEx())

    Raises an auditing event winreg.QueryValue with arguments keysub_keyvalue_name.('nolower', 1)

    ('wan', 1)

    ('ethernet', 1) # ('以太网', 1)


    ('tunnel', 1)

    ('wlan,ethernet,vwifi', 1) # vwifi 是汇尔微路由,全球第一款具有全网脱机下载功能的微电脑路由器,他替代了PC电脑的网络上传下载功能、文件存储及分类管理功能、还承载了无线智能路由器的全部功能。

    ('wlan,ethernet', 1) # ('无线局域网,以太网',1)

    # Find the adapter name corresponding to the network card netCfgInstanceID
    for index in range( keyInfo[0] ):
        hSubKeyName = winreg.EnumKey( hkey, index ) # ==> # 0000, 0001,...,0024, Properties
        if hSubKeyName == 'Properties':
            continue
        hSubKey = winreg.OpenKey(hkey, hSubKeyName)
        # <PyHKEY:0x0000000000000A9C>, <PyHKEY:0x0000000000000A94>, repeated...
        try:
            hNdiInfKey = winreg.OpenKey(hSubKey, r'Ndi\Interfaces')
            # <PyHKEY:0x0000000000000A9C>, <PyHKEY:0x0000000000000A94>, repeated...
            lowerRange = winreg.QueryValueEx(hNdiInfKey, 'LowerRange')
            
            # card manufacturer name and NIC name, Guid
            # ('ethernet', 1)
            if lowerRange[0] == 'ethernet':
                driverDesc = winreg.QueryValueEx(hSubKey, 'DriverDesc')[0]
                print('driver descritions:', driverDesc)
                # driverDesc
                # ('Marvell Yukon 88E8057 PCI-E Gigabit Ethernet Controller', 1)
                # ('DisplayLink Network Adapter NCM', 1)
                # ('TAP-Windows Adapter V9', 1)
                # ('Apple Mobile Device Ethernet', 1)
                
                # RootDevice's Data in the linkage
                netCfgInstanceID = winreg.QueryValueEx(hSubKey, 'NetCfgInstanceID')[0]
                print('Network adapter ID:', netCfgInstanceID, '\n')
                # netCfgInstanceID
                # ('{D622414E-F5F0-41F7-8907-1C0EDE2B5E24}', 1)
                # ('{A98CC15D-466E-4985-AB9F-7B84C71D5FCC}', 1)
                # ('{07D69288-DE47-4348-89D5-94D70DE90A9B}', 1)
                # ('{E0C996DE-475D-40A8-B8E5-EA4D483EE287}', 1)
                if netCfgInstanceID == None:
                    print('The network adapter is not found, the program exits!')
                    winreg.CloseKey(hNdiInfKey)
                    exit()
                elif driverDesc=='DisplayLink Network Adapter NCM':
                    winreg.CloseKey(hNdiInfKey)
                    break
            winreg.CloseKey(hNdiInfKey)
        
        except:
            print('Message:', 'No Ndi\Interfaces Key')
            
    winreg.CloseKey(hSubKey)
    winreg.CloseKey(hkey)  

    I want to change DisplayLink Network Adapter's IP address 

     
    Set the IP by modifying the registry
    Use the Registry Editor ==> Tcpip ==> right click you mouse ==> click "Copy Key Name"
    Then you will get: 

     HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{A98CC15D-466E-4985-AB9F-7B84C71D5FCC}\Parameters\Tcpip

    # Set the IP by modifying the registry
    # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{A98CC15D-466E-4985-AB9F-7B84C71D5FCC}\Parameters\Tcpip
    strKeyName= r'SYSTEM\CurrentControlSet\services\{0}\Parameters\Tcpip'.format(netCfgInstanceID)
    print( 'The registry address of the network adapter is:\n', strKeyName )

  • winreg.KEY_WRITE
    Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.

  • https://docs.python.org/3/library/configparser.html

    read_file(fsource=None)

    Read and parse configuration data from f which must be an iterable yielding Unicode strings (for example files opened in text mode).

    Optional argument source specifies the name of the file being read. If not given and f has a name attribute, that is used for source; the default is '<???>'.

  • get(sectionoption*raw=Falsevars=None[, fallback])

    Get an option value for the named section.
    If vars is provided, it must be a dictionary.
    The option is looked up in vars (if provided), section, and in DEFAULTSECT in that order. If the key is not found and fallback is provided, it is used as a fallback value. None can be provided as a fallback value.

    All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option.

    Changed in version 3.2: Arguments rawvars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol).

  • Use the Registry Editor to change the permissions on the key to allow you as a user to have access. (if not, the following code will appear:
    PermissionError: [WinError 5] Access is Denied
    )

    # Set the IP by modifying the registry
    # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{A98CC15D-466E-4985-AB9F-7B84C71D5FCC}\Parameters\Tcpip
    strKeyName= r'SYSTEM\CurrentControlSet\services\{0}\Parameters\Tcpip'.format(netCfgInstanceID)
    
    hkey=winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE,
                         strKeyName,
                         0,
                         winreg.KEY_ALL_ACCESS # (winreg.KEY_WOW64_64KEY + winreg.KEY_READ)
                       )
    ip_data, ip_type = winreg.QueryValueEx( hkey, "IPAddress" ) 
    subnetMask_data, subnetMask_type = winreg.QueryValueEx( hkey, "SubnetMask" )
    defaultGateWay_data, defaultGateWay_type = winreg.QueryValueEx( hkey, "DefaultGateWay" )
    
    print( ip_data, subnetMask_data, defaultGateWay_data )
    
    winreg.SetValueEx(hkey, "IPAddress", 1, winreg.REG_MULTI_SZ, ['192.168.1.10'])
    
    ip_data, ip_type = winreg.QueryValueEx( hkey, "IPAddress" )
    print( ip_data, subnetMask_data, defaultGateWay_data )

     Note, I just assign one list with one Ip address
    since window 7 system using winreg.REG_MULTI_SZ (a kind of ip list)

     So if I use winreg.REG_SZ to change the IP address

    # Set the IP by modifying the registry
    # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{A98CC15D-466E-4985-AB9F-7B84C71D5FCC}\Parameters\Tcpip
    strKeyName= r'SYSTEM\CurrentControlSet\services\{0}\Parameters\Tcpip'.format(netCfgInstanceID)
    
    hkey=winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE,
                         strKeyName,
                         0,
                         winreg.KEY_ALL_ACCESS # (winreg.KEY_WOW64_64KEY + winreg.KEY_READ)
                       )
    ip_data, ip_type = winreg.QueryValueEx( hkey, "IPAddress" ) 
    subnetMask_data, subnetMask_type = winreg.QueryValueEx( hkey, "SubnetMask" )
    defaultGateWay_data, defaultGateWay_type = winreg.QueryValueEx( hkey, "DefaultGateWay" )
    
    print( ip_data, subnetMask_data, defaultGateWay_data )
    
    winreg.SetValueEx(hkey, "IPAddress", 1, winreg.REG_SZ, '192.168.1.3')
    
    ip_data, ip_type = winreg.QueryValueEx( hkey, "IPAddress" )
    print( ip_data, subnetMask_data, defaultGateWay_data )

    Note, I just assign one Ip address

  • # Set the IP by modifying the registry
    # HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{A98CC15D-466E-4985-AB9F-7B84C71D5FCC}\Parameters\Tcpip
    strKeyName= r'SYSTEM\CurrentControlSet\services\{0}\Parameters\Tcpip'.format(netCfgInstanceID)
    
    hkey=winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE,
                         strKeyName,
                         0,
                         winreg.KEY_ALL_ACCESS # (winreg.KEY_WOW64_64KEY + winreg.KEY_READ)
                       )
    ip_data, ip_type = winreg.QueryValueEx( hkey, "IPAddress" ) 
    subnetMask_data, subnetMask_type = winreg.QueryValueEx( hkey, "SubnetMask" )
    defaultGateWay_data, defaultGateWay_type = winreg.QueryValueEx( hkey, "DefaultGateWay" )
    
    print( ip_data, subnetMask_data, defaultGateWay_data )
    
    winreg.SetValueEx(hkey, "IPAddress", 1, winreg.REG_MULTI_SZ, [new_ip])
    
    ip_data, ip_type = winreg.QueryValueEx( hkey, "IPAddress" )
    print( ip_data, subnetMask_data, defaultGateWay_data )
    just replace  the ip address with variable new_ip

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值