Mac os run as user

Включение учетной записи пользователя root на компьютере Mac или изменение пароля root

Администраторы компьютеров Mac могут использовать учетную запись пользователя root для выполнения задач, требующих доступа к расширенному списку областей системы.

Пользователь root — это суперпользователь с привилегиями чтения и записи в дополнительных областях системы, включая файлы в учетных записях других пользователей macOS. По умолчанию пользователь root отключен. Если не удается войти в систему компьютера Mac с учетной записью администратора, включите пользователя root и выполните вход как пользователь root, чтобы выполнить свою задачу.

Учетная запись пользователя root не предназначена для повседневной работы. Ее привилегии позволяют вносить изменения в файлы, необходимые для работы компьютера Mac. Для отмены таких изменений может потребоваться переустановка системного ПО. После выполнения задачи пользователя root следует отключить.

Безопаснее использовать команду sudo в программе «Терминал» вместо включения пользователя root. Чтобы узнать о команде sudo , откройте программу «Терминал» и введите man sudo .

Включение и отключение учетной записи пользователя root

  1. Перейдите в меню Apple () > «Системные настройки» и откройте вкладку «Пользователи и группы» (или «Учетные записи»).
  2. Щелкните , затем введите имя и пароль администратора.
  3. Нажмите «Параметры входа».
  4. Нажмите «Подключить» (или «Изменить»).
  5. Нажмите «Открыть Службу каталогов».
  6. Щелкните в окне «Служба каталогов», затем введите имя и пароль администратора.
  7. Выполните следующие действия в строке меню «Службы каталогов»:
    • Выберите «Правка» > «Включить корневого пользователя» и введите пароль для пользователя root.
    • Или выберите «Правка» > «Отключить корневого пользователя».

Вход в систему в качестве пользователя root

Если пользователь root включен, его привилегии доступны только после входа в систему в качестве пользователя root.

  1. Перейдите в меню Apple > «Завершить сеанс», чтобы выйти из текущей учетной записи пользователя.
  2. В окне входа введите имя пользователя root и пароль, созданный для пользователя root.
    Если в окне входа отображается список пользователей, нажмите кнопку «Другой» и выполните вход.

Не забудьте отключить учетную запись пользователя root после выполнения задачи.

Источник

Running a Command as another User

This post is an update to an older post on the same topic . macOS has changed and I had a few things to add. Rather than keep modifying the older post, I decided to make this new one.

As MacAdmins, most of the scripts we write will use tools that require administrator or super user/root privileges. The good news here that many of the management tools we can use to run scripts on clients already run with root privileges. The pre – and postinstall scripts in installation packages (pkgs), the agent for your management system, and scripts executed as LaunchDaemons all run with root privileges.

However, some commands need to be run not as root, but as the user.

For example, the defaults command can be used to read or set a specific setting for a user. When your script, executed by your management system, is running as root and contains this command:

Then it will write this preference into root ’s home directory in /var/root/Library/Preferences/com.apple.dock.plist . This is probably not what you intended to do.

Читайте также:  Linux find examples in the

Get the Current User

To get the correct behavior, you need to run the command as a user. Then the problem is as which user you want to run as. In many cases the answer is the user that is currently logged in.

I have written a few posts about how to determine the currently logged in user from shell scripts and will use the solution from those:

This will return the currently logged in user or loginwindow when there is none. This is the Posix sh compatible syntax, which will also run with bash or zsh.

Running as User

There are two ways to run a command as the current user. The first is with sudo :

The second is with launchctl asuser .

The launchctl command uses the numerical user ID instead of the user’s shortname so we need generate that first.

It used to be that the sudo solution would not work in all contexts, but the launchctl asuser solution would. This changed at some point during the Mojave release time.

Now, the lauchctl asuser works and is required when you want to load and unload LaunchAgents (which run as the user), but it does not seem to work in other contexts any more.

So, for most use cases, you want to use the sudo solution but in some you need the launchctl form. The good news here is, that you can play it safe and use both at the same time:

This works for all commands in all contexts. This is, however, a lot to type and memorize. I built a small shell function that I use in many of my scripts. Paste this at the beginning of your scripts:

and then you can use the function like this:

Note: the function, as written above, will simply do nothing when the Mac is sitting at the login window with no user logged in. You can uncomment the exit 1 line to make the script exit with an error in that case. In your script, you should generally check whether a user is logged in and handle that situation before you use the runAsUser function. For example you could use:

Insert this at the beginning of your code (but after the declaration of the currentUser variable) and you can assume that a user is logged in and safely use the $currentUser variable and the runAsUser function afterwards. The exact detail on when and how you should check for a logged in user depends on the workflow of your script. In general, earlier is better.

When to Run as User

Generally, you should run as the user when the command interacts with the user interface, user processes and applications, or user data. As MacAdmins these are common commands you should run as the user;

  • defaults , when reading or changing a user’s preferences
  • osascript
  • open
  • launchctl load|unload for Launch Agents (not Launch Daemons)

This is not a complete list. Third party configuration scripts may need to be run as root or user. You will need to refer to documentation or, in many cases, just determine the correct action by trial and error.

Sample Script

I have put together a script that combines the above code into a working example.

Источник

Set up users, guests and groups on Mac

If your Mac has multiple users, you should set up an account for each person so each can personalise settings and options without affecting the others. You can let occasional users log in as guests without access to other users’ files or settings. You can also create groups. You must be an administrator of your Mac to perform these tasks.

Читайте также:  Как убрать chkdsk при загрузке windows

Add a user

On your Mac, choose Apple menu

> System Preferences, then click Users & Groups.

If the lock at the bottom left is locked , click it to unlock the preference pane.

Click the Add button below the list of users.

Click the New Account pop-up menu, then choose a type of user.

Administrator: An administrator can add and manage other users, install apps and change settings. The new user you create when you first set up your Mac is an administrator. Your Mac can have multiple administrators. You can create new ones, and convert standard users to administrators. Don’t set up automatic login for an administrator. If you do, someone could simply restart your Mac and gain access with administrator privileges. To keep your Mac secure, don’t share administrator names and passwords.

Standard: Standard users are set up by an administrator. Standard users can install apps and change their own settings, but can’t add other users or change other users’ settings.

Sharing Only: Sharing-only users can access shared files remotely, but can’t log in to or change settings on the computer. To give the user permission to access your shared files or screen, you may need to change settings in the File Sharing, Screen Sharing or Remote Management pane of Sharing preferences. See Set up file sharing and Share the screen of another Mac.

For more information about the options for each type of user, click the Help button in the lower-left corner of the dialogue.

Enter a full name for the new user. An account name is generated automatically. To use a different account name, enter it now — you can’t change it later.

Enter a password for the user, then enter it again to verify. Enter a password hint to help the user remember their password.

Click Create User.

Depending on the type of user you create, you can also do any of the following:

For an administrator, select “Allow user to administer this computer”.

For an administrator, select “Allow user to reset a password using Apple ID”.

Use Sharing preferences to specify whether the user can share your files and share your screen.

For information about Apple’s privacy policy, see the Apple Privacy Policy website.

If your Mac or Magic Keyboard has Touch ID, a new user can add a fingerprint after logging in to the Mac.

Create a group

A group allows multiple users to have the same access privileges. For example, you can grant a group specific access privileges for a folder or a file, and all members of the group have access. You can also assign a group specific access privileges for each of your shared folders.

On your Mac, choose Apple menu

> System Preferences, then click Users & Groups.

If the lock at the bottom left is locked , click it to unlock the preference pane.

Click the Add button below the list of users.

Click the New Account pop-up menu, then choose Group.

Читайте также:  Шрифт по умолчанию линукс минт

Give the group a name, then click Create Group.

Select each user and group you want to add to the new group.

Use Sharing preferences to specify whether the group members can share your files and share your screen.

Convert a standard user to an administrator

On your Mac, choose Apple menu

> System Preferences, then click Users & Groups.

If the lock at the bottom left is locked , click it to unlock the preference pane.

Select a standard user or managed user in the list of users, then select “Allow user to administer this computer”.

Let occasional users log in as guests

You can let other people use your Mac temporarily as guest users without adding them as individual users.

Guests don’t need a password to log in.

Guests can’t change user or computer settings.

Guests can’t log in remotely when remote login is turned on in Sharing preferences.

Files created by a guest are stored in a temporary folder, but that folder and its contents are deleted when the guest logs out.

Guest access works with the Find My app to help you find your Mac if you lose it. You can locate your Mac if someone finds it, logs in as a guest, and then uses Safari to access the internet. See Set up the Find My app to locate a missing Mac.

Note: If FileVault is turned on, guests can access Safari but can’t access your encrypted disk or create files.

On your Mac, choose Apple menu

> System Preferences, then click Users & Groups.

If the lock at the bottom left is locked , click it to unlock the preference pane.

Select Guest User in the list of users.

Select “Allow guests to log in to this computer”.

If you like, select “Limit Adult Websites” to prevent the guest from accessing adult websites.

To let guests use your shared folders from another computer on the network, select “Allow guest users to connect to shared folders”.

Customise the login experience

If you are an administrator, you can specify how the login window looks to all the other users.

On your Mac, choose Apple menu

> System Preferences, click Users & Groups, then click Login Options.

If the lock at the bottom left is locked , click it to unlock the preference pane.

Click the “Automatic login” pop-up menu, then choose a user or choose Off.

If you choose a user, then whenever the Mac starts up, that user is automatically logged in. If you choose Off, then at startup the Mac opens a login window showing all the users. Automatic login takes effect the next time you restart the Mac.

Note: Automatic login allows anyone to access your Mac simply by restarting it. If automatic login is enabled, make sure your Mac doesn’t automatically log in an administrator. When FileVault is turned on, automatic login is disabled.

Select the options you want. If you have any questions, click the Help button for detailed information.

To permit new users to access your shared files or screen, you may need to change settings in the File Sharing, Screen Sharing or Remote Management pane of Sharing preferences. See Set up file sharing and Share the screen of another Mac.

To open Sharing preferences, choose Apple menu

Источник

Оцените статью