¿Cómo habilitar/deshabilitar interfaces de red mediante programación?(Windows XP)
-
01-07-2019 - |
Pregunta
Necesito habilitar/deshabilitar completamente las interfaces de red desde un script en Windows XP.Estoy buscando una solución de Python, pero cualquier forma general (por ejemplo, WMI, alguna línea de comandos a la netsh, alguna llamada de Windows) es bienvenida y se ajustará.Gracias.
Solución
Uso de la interfaz de uso de la interfaz netsh Interface [name =] ifName [[admin =] habilitado | discapacitado [connect =] conectado | disconnected [newname =] Newname
Intente incluir todo lo que esté dentro de los corchetes exteriores:conjunto de interfaz netsh nombre de interfaz = "el nombre" admin = deshabilitado conectar = DESCONECTADO nuevo nombre = "el nombre"
Consulte también esta página de MS KB: http://support.microsoft.com/kb/262265/Podrías seguir cualquiera de sus sugerencias.Para deshabilitar el adaptador, deberá determinar una manera de hacer referencia al dispositivo de hardware.Si no habrá varios adaptadores con el mismo nombre en la computadora, posiblemente podría salir de la Descripción de la interfaz (o la ID PCI funciona bien).Después de eso, usando devcon (deshabilitar|habilitar).Devcon es una interfaz de consola complementaria para el Administrador de dispositivos.
Otros consejos
Hasta ahora he encontrado la siguiente solución Python:
>>> import wmi; c=wmi.WMI()
>>> o=c.query("select * from Win32_NetworkAdapter where NetConnectionID='wifi'")[0]
>>> o.EnableDevice(1)
(-2147217407,)
que se traduce, AFAIU, al error genérico de WMI 0x80041001.Podrían ser permisos.
Encontré este script .VBS en Internet.Tiene la gran ventaja de trabajar en máquinas donde no puedo hacer que NETSH funcione para este propósito.
Const ssfCONTROLS = 3
sConnectionName = "Local Area Connection"
sEnableVerb = "En&able"
sDisableVerb = "Disa&ble"
set shellApp = createobject("shell.application")
set oControlPanel = shellApp.Namespace(ssfCONTROLS)
set oNetConnections = nothing
for each folderitem in oControlPanel.items
if folderitem.name = "Network Connections" then
set oNetConnections = folderitem.getfolder: exit for
end if
next
if oNetConnections is nothing then
msgbox "Couldn't find 'Network Connections' folder"
wscript.quit
end if
set oLanConnection = nothing
for each folderitem in oNetConnections.items
if lcase(folderitem.name) = lcase(sConnectionName) then
set oLanConnection = folderitem: exit for
end if
next
if oLanConnection is nothing then
msgbox "Couldn't find '" & sConnectionName & "' item"
wscript.quit
end if
bEnabled = true
set oEnableVerb = nothing
set oDisableVerb = nothing
s = "Verbs: " & vbcrlf
for each verb in oLanConnection.verbs
s = s & vbcrlf & verb.name
if verb.name = sEnableVerb then
set oEnableVerb = verb
bEnabled = false
end if
if verb.name = sDisableVerb then
set oDisableVerb = verb
end if
next
'debugging displays left just in case...
'
'msgbox s ': wscript.quit
'msgbox "Enabled: " & bEnabled ': wscript.quit
'not sure why, but invokeverb always seemed to work
'for enable but not disable.
'
'saving a reference to the appropriate verb object
'and calling the DoIt method always seems to work.
'
if bEnabled then
' oLanConnection.invokeverb sDisableVerb
oDisableVerb.DoIt
else
' oLanConnection.invokeverb sEnableVerb
oEnableVerb.DoIt
end if
'adjust the sleep duration below as needed...
'
'if you let the oLanConnection go out of scope
'and be destroyed too soon, the action of the verb
'may not take...
'
wscript.sleep 1000
Parece que no puedo encontrar ninguna API básica para controlar interfaces en MSDN, aparte de las API de RAS, pero no creo que se apliquen a conexiones que no sean de acceso telefónico.Como usted mismo sugiere, netsh podría ser una opción, supuestamente también tiene una interfaz programática: http://msdn.microsoft.com/en-us/library/ms708353(VS.85).aspx
Si desea ser Python puro, quizás pueda abrir un conjunto de tuberías para comunicarse con un proceso netsh.
esto es VB.Net
Dim objectQuery As New ObjectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId IS NOT NULL")
Dim searcher As New ManagementObjectSearcher(scope, objectQuery)
Dim os As ManagementObject
Dim moColl As ManagementObjectCollection = searcher.Get()
Dim _list As String = ""
For Each os In moColl
Console.WriteLine(os("NetConnectionId"))
Next os
Eso obtendrá todas las interfaces en su computadora.Entonces puedes hacer netsh para desactivarlo.
interfaz netsh set interfaz discapacitado
El devcon La herramienta puede controlar la NIC, pero no la interfaz directamente.Es una versión de línea de comandos del subprograma Administrador de dispositivos.
devcon disable (id or portion of name)
devcon enable (id or portion of name)
Es posible que necesite utilizar WMI.Esto puede servir como un buen punto de partida:http://msdn.microsoft.com/en-us/library/aa394595.aspx