¿Hay alguna manera de iniciar/detener el uso compartido de Internet desde la línea de comandos o tal vez un script de Apple?
Lo que pasa es que me muevo con mi portátil entre casa y el trabajo. En un lugar obtengo Internet inalámbrico (y por lo tanto tengo que deshabilitar el uso compartido de Internet), y en el otro obtengo Internet a través de un cable Ethernet y configuro la computadora para compartir Internet con otros dispositivos mediante la creación de una pequeña red inalámbrica.
Pero se está volviendo un poco tedioso tener que ingresar a las Preferencias del sistema e iniciar/detener el uso compartido de Internet cada vez que cambio de ubicación, por lo que me gustaría tener un comando o script rápido para iniciar y hacer el cambio a pedido.
¿Alguna pista o idea?
Para iniciar Internet Sharing desde la CLI:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist
Para parar, cambie la carga para descargar .
Tenga en cuenta que si tiene el panel de preferencias abierto cuando ejecuta esto, no verá que el cambio surta efecto de inmediato (la interfaz de usuario no se actualizará), pero funciona.
unload
para poder hacer una de load
nuevo. Un buen comando de verificación es ps ax | egrep '[ /](PID|boo|nat)'
./System/Library/LaunchDaemons/com.apple.InternetSharing.plist: No such file or directory
unload
que no funciona a menos que se elimine SIP (nada que me gustaría hacer)...Una forma de hacerlo es mediante secuencias de comandos GUI: las Preferencias del sistema no son compatibles con Applescript de forma predeterminada.
tell application "System Preferences" to set current pane to pane "com.apple.preferences.sharing"
delay 1
tell application "System Events" to tell process "System Preferences"
click checkbox 1 of row 8 of table 1 of scroll area 1 of group 1 of window "Sharing" -- change to row 10 if you are using anything before Snow Leopard
delay 1
if (exists sheet 1 of window "Sharing") then
click button "Start" of sheet 1 of window "Sharing"
end if
end tell
ignoring application responses
tell application "System Preferences" to quit
end ignoring
System Events got an error: Can’t get button "Start" of sheet 1 of window "Sharing" of process "System Preferences".
Sin embargo, funciona bien cuando intento deshabilitarlo. Lo curioso es que, si las Preferencias del sistema están abiertas y trato de habilitarlas, funciona. ¿Tienes alguna idea de por qué sucedería eso?Obtuve resultados mucho mejores (para una configuración de uso compartido ya configurada) en 10.11.6 con las variaciones simples...
sudo launchctl
start
com.apple.NetworkSharing
y
sudo launchctl
stop
com.apple.NetworkSharing
respectivamente.
He encontrado un sistema que finalmente funciona y cuando, con menos frecuencia, se rompe el intercambio de wifi, logra recuperarlo automáticamente en un minuto.
La solución es un ~/Library/LaunchAgents/com.me.wifisharingup.plist
demonio con los siguientes contenidos:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.juanfal.wifisharingup</string>
<key>ProgramArguments</key>
<array>
<string>/Users/mi/bin/wifisharingup.sh</string>
</array>
<key>Nice</key>
<integer>1</integer>
<key>StartInterval</key>
<integer>60</integer>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/me/Library/Logs/wifisharingup.err</string>
<key>StandardOutPath</key>
<string>/Users/me/Library/Logs/wifisharingup.out</string>
</dict>
</plist>
Puede ver, cada minuto ejecuta el script simple que sigue. Tenga cuidado de hacer que la plist anterior sea propiedad de la raíz y ejecútela con:
sudo chown root com.me.wifisharingup.plist
sudo launchctl load /Users/me/Library/LaunchAgents/com.me.wifisharingup.plist
El script que lanza cada minuto (no olvides hacerlo ejecutable) es:
#!/bin/sh
if [[ ! `ipconfig getifaddr en1` ]]; then
/usr/sbin/networksetup -setairportpower en1 off
/usr/sbin/networksetup -setairportpower en1 on
echo `date` >> "/Users/me/Library/Logs/wifisharingup.err"
else
touch "/Users/me/Library/Logs/wifisharingup.out"
fi
Creo que la simple llamada periódica (cada minuto) ipconfig getifaddr en1
actualiza algo en lo que es el demonio para compartir wifi. Sea lo que sea, en cualquier momento que falla el uso compartido de wifi, pierde la dirección IP autoasignada y luego ipconfig getifaddr en1
falla, por lo que mi script restablece totalmente el wifi, lo que hace que reconstruya su estado anterior y recupere el uso compartido de wifi.
Ha estado funcionando durante días dentro de una MacMini sin teclado, mouse o monitor, pero solo conectado a Ethernet y dando acceso a mis dispositivos wifi al mundo.
Seguí el ejemplo de la respuesta de mankoff y la envolví en un AppleScript. Estoy usando este script de Automator para poder usarlo fácilmente como un servicio y darle un atajo de teclado.
Alternar Compartir Internet:
register_growl()
try
if isRunning("InternetSharing") then
do shell script "launchctl unload -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
if isRunning("InternetSharing") then
error "Internet Connection Sharing was Not Disabled"
else
my growlnote("Success", "Internet Connection Sharing Disabled")
end if
else
do shell script "launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
if isRunning("InternetSharing") then
my growlnote("Success", "Internet Connection Sharing Enabled")
else
error "Internet Connection Sharing was Not Enabled"
end if
end if
on error errMsg
my growlnote("Error", errMsg)
end try
on isRunning(processName)
try
return 0 < length of (do shell script "ps ax | grep -v grep | grep " & processName)
on error
return false
end try
end isRunning
on register_growl()
try
tell application "GrowlHelperApp"
set the notificationsList to {"Success", "Warning", "Error"}
register as application "Toggle Internet Connection Sharing" all notifications notificationsList default notifications notificationsList icon of application "Sharing"
end tell
end try
end register_growl
on growlnote(growltype, str)
try
tell application "GrowlHelperApp"
notify with name growltype title growltype description str application name "Toggle Internet Connection Sharing"
end tell
end try
end growlnote
Utilizo la siguiente secuencia de comandos para alternar el uso compartido de Internet en una MacBook Pro / 10.11.3 El Capitan de principios de 2011, por lo que con el hardware más nuevo puede salirse con la suya con demoras más cortas. Adopta ideas de varios scripts publicados para este propósito (localización, encender/apagar wifi usando networksetup
, cerrar System Preferences
cuando haya terminado).
tell application "System Preferences"
activate
reveal (pane id "com.apple.preferences.sharing")
set localized_window to the localized name of the current pane
end tell
tell application "System Events" to tell process "System Preferences"
delay 1
repeat with r in rows of table 1 of scroll area 1 of group 1 of window localized_window
if (value of static text of r as text) starts with "Internet" then
set sharingBool to value of checkbox of r as boolean
select r
if sharingBool is true
do shell script "/usr/sbin/networksetup -setairportpower en1 off"
else
do shell script "/usr/sbin/networksetup -setairportpower en1 on"
end if
click checkbox of r
end if
end repeat
delay 1
if (exists sheet 1 of window localized_window) then
click button "Start" of sheet 1 of window localized_window
end if
end tell
ignoring application responses
tell application "System Preferences" to quit
end ignoring
La manera realmente fácil de hacerlo es combinar la respuesta de @Philip con la aplicación NetworkLocation . NL puede saber dónde se encuentra y ejecutar automáticamente un AppleScript cuando detecta que ha cambiado de ubicación.
Creo que es un software requerido si tiene una computadora portátil; de lo contrario, es un PITA tener que restablecer siempre manualmente varias configuraciones cada vez que cambio de ubicación.
Ligeramente diferente al otro applescript publicado (creo que de una mejor manera pero...). Tener opciones a veces puede ayudar.
tell application "System Preferences"
activate
reveal (pane id "com.apple.preferences.sharing")
end tell
tell application "System Events"
tell process "System Preferences"
try
click checkbox of row 11 of table 1 of scroll area of group 1 of window "Sharing"
if checkbox of row 11 of table 1 of scroll area of group 1 of window "Sharing" is equal to 1 then
repeat until sheet of window 1 exists
delay 0.5
end repeat
end if
if (sheet of window 1 exists) then
click button "Start" of sheet of window 1
end if
tell application "System Preferences" to quit
activate (display dialog "Internet Sharing preferences sucessfully flipped")
on error
activate
display dialog "something went wrong in automation but you are probably in the right menu…"
return false
end try
end tell
end tell
Dado que la solución de secuencias de comandos GUI publicada anteriormente requiere que los usuarios internacionales ajusten los nombres de las ventanas y los botones, se me ocurrió una versión que funciona con cualquier idioma del sistema. También funciona para la otra opción de uso compartido y brinda comentarios localizados sobre el estado de uso compartido. Utilizo dos servicios de Automator diferentes basados en esto, uno para alternar el uso compartido de archivos y otro para alternar el uso compartido de Internet.
tell application "System Preferences"
set current pane to pane "com.apple.preferences.sharing"
set localized_window to the localized name of the current pane
set localized_app to (localized string "System Preferences")
set localized_ok to {localized string "OK"} -- File sharing
set localized_start to {localized string "START"} -- Internet sharing
end tell
delay 0.3
tell application "System Events"
tell process "System Preferences"
click checkbox 1 of row 8 of table 1 of scroll area 1 of group 1 of window localized_window
delay 0.2
select row 8 of table 1 of scroll area 1 of group 1 of window localized_window
-- change row numbers to the service you want toggled
if (exists sheet 1 of window localized_window) then
try
click button (localized_ok as string) of sheet 1 of window localized_window
on error
click button (localized_start as string) of sheet 1 of window localized_window
end try
end if
set sharing_state to the value of item 1 of static text of group 1 of window localized_window
end tell
tell application "System Preferences" to quit
display notification sharing_state with title localized_app
-- display notification exists since OS 10.9, for older systems use:
-- display dialog sharing_state buttons {localized_ok} default button 1 with title localized_app giving up after 1.5
end tell
Antes/después de cualquier configuración, la interfaz o las interfaces involucradas en el uso compartido deben apagarse/encenderse con:
networksetup -setairportpower en1 off
entonces encendido ( networksetup -setairportpower en1 on
)
Mi wifi figuraba como en1
, para buscar el tuyo networksetup -listnetworkserviceorder
. Más concretamente, al comenzar a compartir Internet, deberá agregar una funcionalidad NAT más detallada y luego simplemente configurar el bit habilitado.
NAT se enciende/apaga con bit: -int 0
= apagado -int 1
= encendido
Lo único que está escrito /Library/Preferences/SystemConfiguration/com.apple.nat.plist
con
defaults write /Library/Preferences/SystemConfiguration/com.apple.nat\
NAT -dict Enabled -int 0
es
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NAT</key>
<dict>
</dict>
<key>Enabled</key>
<integer>1</integer>
</dict>
</dict>
</plist>
Deberá cambiar su archivo plist para que tenga el siguiente aspecto:
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NAT</key>
<dict>
<key>AirPort</key>
<dict>
<key>40BitEncrypt</key>
<integer>1</integer>
<key>Channel</key>
<integer>0</integer>
<key>Enabled</key>
<integer>0</integer>
<key>NetworkName</key>
<string>FancyHostNome</string>
<key>NetworkPassword</key>
<data>
</data>
</dict>
<key>Enabled</key>
<integer>1</integer>
<key>NatPortMapDisabled</key>
<false/>
<key>PrimaryInterface</key>
<dict>
<key>Device</key>
<string>en4</string>
<key>Enabled</key>
<integer>0</integer>
<key>HardwareKey</key>
<string></string>
<key>PrimaryUserReadable</key>
<string>InfiniBand</string>
</dict>
<key>PrimaryService</key>
<string>XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX</string>
<key>SharingDevices</key>
<array>
<string>en1</string>
</array>
</dict>
</dict>
</plist>
Como puede ver, mi archivo plist NAT puede necesitar un poco de personalización para satisfacer sus necesidades.
Es posible que desee echar un vistazo a esta pregunta (posiblemente fuera de tema para Stack Overflow) y su respuesta: Cómo iniciar/detener el uso compartido de Internet usando AppleScript .
do shell script "/bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
Modificó uno de los scripts anteriores para alternar Internet Sharing en OSX MOJAVE (10.14), funciona:
tell application "System Preferences"
activate
reveal (pane id "com.apple.preferences.sharing")
delay 0.3
set current pane to pane "com.apple.preferences.sharing"
delay 0.3
set localized_window to the localized name of the current pane
set localized_app to (localized string "System Preferences")
set localized_ok to {localized string "OK"} -- File sharing
set localized_start to {localized string "START"} -- Internet sharing
end tell
delay 0.3
tell application "System Events"
tell process "System Preferences"
click checkbox 1 of row 7 of table 1 of scroll area 1 of group 1 of window localized_window
delay 0.2
select row 8 of table 1 of scroll area 1 of group 1 of window localized_window
-- change row numbers to the service you want toggled
if (exists sheet 1 of window localized_window) then
try
click button (localized_ok as string) of sheet 1 of window localized_window
on error
click button (localized_start as string) of sheet 1 of window localized_window
end try
end if
set sharing_state to the value of item 1 of static text of group 1 of window localized_window
end tell
tell application "System Preferences" to quit
display notification sharing_state with title localized_app
-- display notification exists since OS 10.9, for older systems use:
-- display dialog sharing_state buttons {localized_ok} default button 1 with title localized_app giving up after 1.5
end tell
/usr/bin/defaults write /Library/Preferences/SystemConfiguration/com.apple.nat NAT -dict Enabled -int 0
mikez
usuario588
usuario588
usuario588
mikez
mikez
Roberto Ciaccio