python">
import subprocessdef open_share ( to_shared_adapter, from_shared_adapter) : """打开以太网的网络 共享:return: None""" powershell_script = f"""# Register the HNetCfg library (once)# regsvr32 hnetcfg.dll# Create a NetSharingManager object$m = New-Object -ComObject HNetCfg.HNetShare# List connections$m.EnumEveryConnection |% {{ $m.NetConnectionProps.Invoke($_) }}# Find connection$c = $m.EnumEveryConnection |? {{ $m.NetConnectionProps.Invoke($_).Name -eq " { to_shared_adapter} " }}$c2 = $m.EnumEveryConnection |? {{ $m.NetConnectionProps.Invoke($_).Name -eq " { from_shared_adapter} " }}# Get sharing configuration$config = $m.INetSharingConfigurationForINetConnection.Invoke($c)$config2 = $m.INetSharingConfigurationForINetConnection.Invoke($c2)# See if sharing is enabledWrite-Output $config.SharingEnabledWrite-Output $config2.SharingEnabled# See the role of connection in sharing# 0 - public, 1 - private# Only meaningful if SharingEnabled is TrueWrite-Output $config.SharingTypeWrite-Output $config2.SharingType$config.EnableSharing(0)$config2.EnableSharing(1)""" process = subprocess. Popen( [ 'powershell' , '-Command' , powershell_script] , stdout= subprocess. PIPE, stderr= subprocess. PIPE, text= True ) stdout, stderr = process. communicate( ) def close_share ( to_shared_adapter, from_shared_adapter) : """打开以太网的网络 共享:return: None""" powershell_script = f"""# Register the HNetCfg library (once)# regsvr32 hnetcfg.dll# Create a NetSharingManager object$m = New-Object -ComObject HNetCfg.HNetShare# List connections$m.EnumEveryConnection |% {{ $m.NetConnectionProps.Invoke($_) }}# Find connection$c = $m.EnumEveryConnection |? {{ $m.NetConnectionProps.Invoke($_).Name -eq " { to_shared_adapter} " }}$c2 = $m.EnumEveryConnection |? {{ $m.NetConnectionProps.Invoke($_).Name -eq " { from_shared_adapter} " }}# Get sharing configuration$config = $m.INetSharingConfigurationForINetConnection.Invoke($c)$config2 = $m.INetSharingConfigurationForINetConnection.Invoke($c2)# Enable sharing (0 - public, 1 - private)$config.DisableSharing()$config2.DisableSharing()""" process = subprocess. Popen( [ 'powershell' , '-Command' , powershell_script] , stdout= subprocess. PIPE, stderr= subprocess. PIPE, text= True ) stdout, stderr = process. communicate( ) if __name__ == '__main__' : to_shared_adapter = "以太网" from_shared_adapter = "以太网 7" open_share( to_shared_adapter, from_shared_adapter) close_share( to_shared_adapter, from_shared_adapter)