【macOS】开机自动连接SMB

Posted by 西维蜀黍 on 2021-12-28, Last Modified on 2023-04-03

Approach 1 - Configure your Mac to automatically mount an SMB share at Login

Approach 2 - Connect via VPN

tell application "Viscosity"
    set connectionState to "dunno"
    repeat until (connectionState = "Connected")
        if connectionState = "Disconnected" then
            connect "VPN_CONNECTION1"
            connect "VPN_CONNECTION2"
        end if
        set connectionState to state of connections where name is equal to "VPN_CONNECTION1"
        set connectionState to connectionState as string
    end repeat
    tell application "Finder"
        activate
        if (count of windows) is 0 then
            mount volume "smb://username:password@IP_address/share"
            mount volume "smb://username:password@IP_address/share"
        end if
    end tell
end tell

The above apple script will automatically startup my Viscosity VPN and upon a succesfull connection it will start to connect to my SMB servers. If you export the code to an application and then put it into your login items it will automatically connect everytime you startup.

Approach 3 - Auto Connect Without Popup

  1. 打开 Automator

  2. 创建一个“应用程序”

  3. 点击“Run AppleScript”这个action,拖动到右侧面板

  4. 输入待运行命令,比如

    do shell script "sudo whatevercommandyouwanttorun" with administrator privileges
    
    # run a apple script
    osascript /Users/shiwei/SW/auto_smb_connect.scpt
    
  5. 保存这个“应用程序”

  6. 尝试打开这个应用程序,测试他的可用性

  7. 在系统偏好设置——用户与群组——登录项中,添加刚保存的application

Reference