10 полезных команд для Терминала в Mac
Терминал — это мощный инструмент OS X. Вы даете своему компьютеру команды, и операционная система их покорно выполняет. С помощью терминала вы можете выполнить действия, которые значительно сложнее или невозможно выполнить, используя графический пользовательский интерфейс. Однако терминал нельзя назвать дружелюбным инструментом для простых пользователей. Многие его остерегаются в страхе дать неправильную команду и столкнуться с непредвиденными последствиями. В этой статье вы найдете подборку простых и даже забавных команд, с которых можно начать знакомство с терминалом.
Как пинговать сайт
Команда Ping позволяет проверить вам доступность домена или IP-адреса. Вы также сможете увидеть, насколько быстро будет дан ответ от сервера. Попробуйте проверить, насколько быстро вы получите ответ от «www.appleinisder.ru». Для этого существует очень простая команда:
Отключение тени на скриншотах
Если вы делаете скриншот окна в OS X, по умолчанию он создается с тенью. Вы можете отключить тень на скриншотах простой командой:
defaults write com.apple.screencapture disable-shadow -bool TRUE
После нее наберите:
Эта команда заставит изменения вступить в силу. Если захотите снова включить тени на скриншотах, просто проделайте ту же операцию, заменив в команде «TRUE» на «FALSE».
Показать скрытые файлы в Finder
Для того чтобы в Finder начали отображаться все скрытые файлы, просто наберите в терминале:
defaults write com.apple.finder AppleShowAllFiles -bool TRUE
Для применения изменений потребуется перезапустить Finder. Для этого вы можете использовать команду:
Все скрытые файлы будут показаны. Хотите снова скрыть их? Проделайте те же действия, заменив в команде «TRUE» на «FALSE».
Как научить Mac говорить
Простой командой вы можете заставить свой компьютер произнести любую фразу. Попробуйте набрать:
Mac засыпает — что делать
Если вам нужно избежать засыпания вашего компьютера, это очень просто сделать с помощью терминала. Введите:
Вы также можете указать время, которое Mac должен работать без сна в секундах:
Вы можете досрочно отменить выполнение команды комбинацией Ctrl+C.
Как посмотреть историю команд — Terminal
Для того чтобы вспомнить все, что вы доверили терминалу, введите:
Хотите очистить историю команд? Введите:
Стресс-тест компьютера Mac
Стресс-тест создаст процесс «yes» и направит на его выполнение все силы процессора. Мы как то обсуждали пользу этой команды. Сделать стресс-тест просто:
Завершить процесс можно командой:
Включить звук зарядки на Mac
Обычно Mac молчит при подключении зарядного устройства. Если хотите, можете включить звук на это действие, подобный тому, что издает ваш iPhone. Он включается следующей командой:
defaults write com.apple.PowerChime ChimeOnAllHardware -bool TRUE; open /System/Library/CoreServices/PowerChime.app &
Для отключения этого звука используйте команду:
defaults write com.apple.PowerChime ChimeOnAllHardware -bool FALSE; killall PowerChime
Проверить обновления на Mac чаще
Ваш компьютер сам проверяет наличие обновления системы. Если вы хотите проверять чаще, чем это делает он, можете проверить вручную, а можете просто попросить OS X проверять наличие обновлений чаще с помощью терминала. Хотите вместо еженедельной проверки включить ежедневную? Для этого есть следующая команда:
defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 1
Как вы можете догадаться, для того чтобы вернуться к еженедельной проверке, стоит использовать команду:
defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 7
Как поставить заставку на обои
Если вы в каком-то странном настроении и оно настолько необычно, что вы хотите временно использовать заставку вместо обоев на вашем Mac, попробуйте команду:
Как только вы закроете Терминал или нажмете Ctrl+C, к вам вернутся ваши обычные обои.
Предлагаем подписаться на наш канал в «Яндекс.Дзен». Там вы сможете найти эксклюзивные материалы, которых нет на сайте.
Наши соцсети
Новости, статьи и анонсы публикаций
Свободное общение и обсуждение материалов
Лонгриды для вас
Если ваших игр для компьютера нет в App Store или в сервисах облачного гейминга, вы все равно можете запустить их на смартфоне. Объясняем, как бесплатно играть в любые ПК игры на Айфоне через MTS Remote Play и удобно ли это
В будущем обновлении Ватсап наконец появятся короткие имена: с помощью ников вы будете быстрее находить пользователей, даже не зная номера телефона. При этом найти человека в Ватсапе удобными способами можно даже сейчас! Скорее читайте, как это сделать
Приложение Retrato нарисует вам несколько фотосессий в стиле реализм. Достаточно просто загрузить в него 15-20 своих снимков и дать ему подумать. На выходе вы получите 72 фотографии и еще более 600 — за дополнительную плату
Mac SystemUIServer: Why Installer Wants Access to Control It
Summary: This post introduces everything about SystemUIServer, including what the SystemUIServer is, why SystemUIServer takes high CPU usage, why some app installers want access to control SystemUIServer when installing them, and how to fix SystemUIServer not responding. — From iBoysoft
Maybe, the first time you see «SystemUIServer» is from some checks in Activity Monitor or getting a message saying «Installer wants access to control SystemUIServer» when trying to install a certain app installer.
Or, some of you encounter it when fixing issues like the menu bar icons disappearing. If you are curious about what the SystemUIServer is and some common problems with it, follow this article to get answers.
What is SystemUIServer?
SystemUIServer is a process in macOS that is responsible for managing and displaying various system-related user interface elements in the menu bar and other parts of the graphical user interface (GUI). It’s a background process that runs continuously to handle the visual components that provide information and control to the user.
SystemUIServer controls the display of various system-related elements, including Apple Menu Bar, Notifications, Control Center, Spotlight Search, Status Icons, and Accessibility.
Click to share the explanation of SystemUIServer with more people.
Why does SystemUIServer cause high CPU usage?
You go to Activity Monitor on your Mac to explore why your Apple menu bar or other system UI-related programs perform improperly and notice that SystemUIServer takes up to 30% or more CPU. While the normal usage is less than 10%.
Why? It’s because of the UI server’s constant work. Maybe a third-party software that contains a menu item is stuck in a loop, or you run multiple menu-included widgets or apps at the same time, causing it to keep using the UI server. Moreover, the system bug can also make the UI server run all the time.
Hence, to reduce the SystemUIServer’s high CPU usage, you can close the UI-related apps you are running and leave only one working. Or, you can force quit SystemUIServer in Activity Monitor (Launchpad > Other).
What’s the message «Installer wants access to control SystemUIServer»?
The message «Installer wants access to control SystemUIServer» always shows up when you install certain apps on your Mac. It means that these apps will show menus on the Apple menu bar. To achieve that, these apps need to control SystemUIServer — the process that manages and maintains the system-related UI elements in the Apple menu bar.
And as SystemUIServer is a process in the operating system, this message pop-ups to ask for your (the administrator’s) permission. You can choose the Allow or Not Allow option on the dialogue window. If you don’t allow that, this app will always fail to be installed.
SystemUIServer not responding, why & how to fix it?
You find that the menu of some of the system widgets on the menu bar are freezing, like the clock, Wi-Fi, Bluetooth, battery, Spotlight Search, etc. And then go to Activity Monitor for a check but notice that the SystemUIServer process is not responding and is labeled in red.
This could be because the specific third-party software you installed that needs to control the SystemUIServer process to display its menu on the Apple menu bar isn’t fully compatible with the macOS you’re using or it has some bugs.
To fix the SystemUIServer not responding issue, a simple force quit it in Activity Monitor or a Mac restart is just a temporary solution. Instead, you need to find out the problematic app and uninstall it.
Share this post about SystemUIServer with others if you think it is meaningful.
Connie Yang is the primary columnist in the computer field at iBoysoft. She is enthusiastic about sharing tech tutorials on data recovery and operating system-related problems resolution. Over the years, Connie has published many computer-related guides and introductory articles.
Jessica Shee is a senior tech editor at iBoysoft. Throughout her 4 years of experience, Jessica has written many informative and instructional articles in data recovery, data security, and disk management to help a lot of readers secure their important documents and take the best advantage of their devices.
Моя борьба с PTPCamera или увлекательная история о реверсинге для самых маленьких
Почти все продвинутые зеркальные камеры, а также некоторые правильные мыльницы, позволяют управлять собой с компьютера. Программное управление камерой дает интересные возможности, например: съемка time lapse video, сопряжение камеры с микроскопом, эксперименты в области компьютерного зрения. Для управления камерой вендоры предоставляют свои проприетарные SDK, которые обычно работают исключительно под Windows и поддерживают камеры только в рамках определенной линейки (например у Canon есть аж 4 несовместимых между собой SDK). Какое счастье, что есть достойная открытая альтернатива — проект gphoto.
Прямо сейчас gphoto поддерживает 1598 моделей камер и список постоянно растет. Проект собирается под все UNIX-like ОС, включая Linux и Mac OS X. Съемкой можно управлять как при помощи command line утилиты, так и из своей собственной программы, используя библиотеку libgphoto. Доступны биндинги для разных языковых платформ, включая node.js.
В современных ОС присутствуют встроенные средства для работы с цифровыми камерами — как правило под «работой» подразумевается только выгрузка фото из камеры. Эти встроенные механизмы препятствуют работе gphoto, так как захватывают USB устройство в эксклюзивном режиме. Особенно интересно дела в этом плане обстоят в Mac OS X — ОС не предоставляет никаких штатных возможностей для отключения, но при этом система поддержки цифровых камер легко поддается реверс инжинирингу.
Скрипты для блокировки запуска PTPCamera на github.
PTPCamera
Интернет советует выполнить команду killall -9 PTPCamera (убить процесс PTPCamera) после подключение фотоаппарата для нормальной работы gphoto. Это в самом деле помогает, однако каждый раз при подключении камеры процедуру приходится повторять заново. Разумеется, программу PTPCamera можно просто удалить, но мне хотелось обойтись менее радикальным решением.
В общем, требовалось понять механизм запуска PTPCamera, и максимально корректно отключить эту функцию.
О захвате изображений в Mac OS X
Согласно имеющимся источникам [1,2], инфраструктура захвата изображений в Mac OS X устроена следующим образом.
На вершине стека расположены приложения, с которыми непосредственно взаимодействует пользователь (ex: iPhoto).
В самом низу расположены приложения для управления устройствами, к числу последних относится PTPCamera. Приложения для управления устройствами ( MassStorageCamera.app , PTPCamera.app , TWAINBridge.app и тд.) живут в системных папках /System/Library/Image Capture/Devices и /Library/Image Capture/Devices .
Посередине находится коммуникационный слой, который организует связь между верхним и нижним уровнями. Любопытно, что несколько пользовательских приложений могут использовать одно устройство совместно, а также возможна прозрачная работа с устройствами по локальной сети.
Кто же запускает PTPCamera?
Попробуем определить механизм запуска PTPCamera, и для начала определим родительский процесс.
$ pgrep PTPCamera 29045 $ ps -O ppid -p 29045 PID PPID TT STAT TIME COMMAND 29045 202 ?? S 0:00.10 /System/Library/Image Capture/Devices/PTPCamer $ ps -p 202 PID TTY TIME CMD 202 ?? 0:16.75 /sbin/launchd
Итак, мы видим что PTPCamera запущен процессом launchd. В Mac OS X launchd — это универсальная запускалка для системных и пользовательских демонов. В системе запущено по экземпляру launchd для каждого активного пользователя. Launchd пользователя root выполняет те же функции, что init в традиционных UNIX системах.
$ ps -A -O user | grep /sbin/launchd 1 root ?? Ss 3:06.80 /sbin/launchd 172 _windowserver ?? Ss 0:00.06 /sbin/launchd 202 nickz ?? Ss 0:16.76 /sbin/launchd 206 _spotlight ?? Ss 0:00.27 /sbin/launchd 28919 _cvmsroot ?? Ss 0:00.01 /sbin/launchd 28937 _securityagent ?? Ss 0:00.01 /sbin/launchd
Кроме демонов, laucnhd также запускает графические приложения по команде других программ. PTPCamera — это именно последний случай, как можно убедиться по ID задачи в launchd, об этом нам говорит [префикс].
$ launchctl list | grep PTPCamera 29045 - [0x0-0x457457].com.apple.PTPCamera
Итак, мы знаем что PTPCamera был запущен процессом launchd, по команде некого приложения X.
Включим логирование launchd ( launchctl log level debug ), и спровоцируем повторный запуск PTPCamera.
По умолчанию, на каждый процесс в системе выделена квота в 500 записей в логе в секунду. Сообщения, не уложившиеся в лимит, отбрасываются. Настроим отдельную сборку отладочных сообщений для обхода лимита.
Добавляем в файл /etc/syslog.conf строку
*.debug /var/log/debug.log
и информируем демон syslogd о необходимости перечитать настройки
sudo killall -HUP syslogd
Анализируем полученный файл debug.log . Находим искомое:
([0x0-0x2d92d9].com.apple.PTPCamera[24472]): Spawned by PID 240: com.apple.SystemUIServer.agent
Запрашиваем у launchd информацию о com.apple.SystemUIServer.agent :
$ launchctl list com.apple.SystemUIServer.agent < "Program" = "/System/Library/CoreServices/SystemUIServer.app/Contents/MacOS/SystemUIServer"; >;
Теперь мы знаем, что «виновник» запуска PTPCamera — это SystemUIServer , ни много ни мало.
Ковыряем SystemUIServer
Имеется подозрение, что искомый функционал находится не в самом SystemUIServer , а в одном из прилинкованных фреймворков:
$ otool -L /System/Library/CoreServices/SystemUIServer.app/Contents/MacOS/SystemUIServer /System/Library/CoreServices/SystemUIServer.app/Contents/MacOS/SystemUIServer: /System/Library/PrivateFrameworks/CoreUI.framework/Versions/A/CoreUI /System/Library/PrivateFrameworks/Admin.framework/Versions/A/Admin /System/Library/Frameworks/Carbon.framework/Versions/A/Carbon /System/Library/PrivateFrameworks/SystemUIPlugin.framework/Versions/A/SystemUIPlugin /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit /System/Library/Frameworks/Security.framework/Versions/A/Security /System/Library/PrivateFrameworks/ICANotifications.framework/Versions/A/ICANotifications /System/Library/PrivateFrameworks/iPod.framework/Versions/A/iPod .
В этом списке главный подозреваемый — ICANotifications.framework . ICA — это сокращение от image capture, тот же акроним используется в публичных фреймворках для захвата изображений.
Изучаем ICANotifications.framework
Лирическое отступление. Исполняемый файл состоит из кода и неизменяемых статических данных (разные константы, таблицы, и тп.) Особый интерес представляют строковые константы. Извлечь их можно при помощи команды strings .
Запускаем strings /System/Library/PrivateFrameworks/ICANotifications.framework/Versions/A/ICANotifications , и наслаждаемся результатами:
. /Library/Caches/com.apple.ImageCaptureNotifications.DeviceDiscoveryDatabase.%d . CREATE TABLE DBVersion (ID integer primary key not null, typeID integer, value integer) CREATE TABLE SourceFile (ID integer primary key not null, typeID integer, bundleID varchar(256), bundleVersion integer, bundlePath varchar(256), deviceDiscoveryPath varchar(256), deviceDiscoveryModDate varchar(20), readDate varchar(20), iTWAINDS integer) CREATE TABLE IOUSBDevice (ID integer primary key not null, typeID integer, idVendor integer, idProduct integer) CREATE TABLE IOUSBInterface (ID integer primary key not null, typeID integer, bInterfaceClass integer, bInterfaceSubClass integer, bInterfaceProtocol integer) .
Итак, рабочая гипотеза — библиотека работает с SQLite базой данных, наиболее вероятно, что это файл com.apple.ImageCaptureNotifications.DeviceDiscoveryDatabase в /Library/Caches .
$ ls /Library/Caches/com.apple.ImageCaptureNotifications.DeviceDiscoveryDatabase.* /Library/Caches/com.apple.ImageCaptureNotifications.DeviceDiscoveryDatabase.501 $ sqlite3 /Library/Caches/com.apple.ImageCaptureNotifications.DeviceDiscoveryDatabase.501 sqlite> .schema CREATE TABLE DBVersion (ID integer primary key not null, typeID integer, value integer); CREATE TABLE IOUSBDevice (ID integer primary key not null, typeID integer, idVendor integer, idProduct integer); CREATE TABLE IOUSBInterface (ID integer primary key not null, typeID integer, bInterfaceClass integer, bInterfaceSubClass integer, bInterfaceProtocol integer); .
Видно, что в конец имени ( com.apple.ImageCaptureNotifications.DeviceDiscoveryDatabase.501 ) дописывается ID пользователя, для каждого пользователя поддерживается собственный файл. Из содержимого понятно, что база задает список соответствий класса устройств и управляющей программы, которую нужно запускать при обнаружении устройства.
Редактирую базу данных, мы отключаем запуск PTPCamera для любого выбранного пользователя, это однозначный успех!
При необходимости вернуть все обратно, откатываем изменения, или просто удаляем файл бд (название папки /Library/Caches сообщает нам, что ОС при необходимости может перегенерировать содержимое).
Факультативные материалы
- Amit Singh Mac OS X Internals: A Systems Approach [amazon]
- Репозиторий проекта
WHAT IS SYSTEMUISERVER?
Can someone give me a basic quick rundown of what exactly «SystemUIServer» is and what it’s controlling?
I have just now come across this while going through my security and privacy preferences. I have ZERO knowledge of my MacBook pro’s software.I only basic programs.
I am shrewd and clever for most topics of interest, but I’ll be the first to admit that even after spending 30 minutes researching the «SystemUIServer» ([I don’t have enough basic knowledge to understand the IN DEPTH information that I’ve read])
I would appreciate any help that could be explained as if I know nothing of the subject.
Even the most basic of understandings would help me. thanks a lot and I hope someone out there can dumb this down for me!
Show more Less
MacBook Pro 13″, macOS 11.2
Posted on Mar 9, 2021 6:46 AM
Me too (78) Me too Me too (78) Me too Reply
Similar questions
Advanced Mac Tutorial Can anyone point me in the direction of an advanced Mac tutorial? Ideally videos tutorials as I find them easier to follow than pages of text. I want to understand how to use more advanced tools such as Activity Monitor, Console, Keychain Access, Script Editor, Xcode, etc. I can run these applications and investigate them but want to understand better how I can usitlize them. For example, Console tells me: default 21:41:38.340816+0000 WindowServer [HID] [MT] dispatchEvent Dispatching event with 2 children, _eventMask=0x2 _childEventMask=0x2 Cancel=0 Touching=1 inRange=1 .. but what does that mean? How can I find out? Keychain Access tells me about Web Form Passwords, Application passwords, System keychains, etc., but what use can I make of them? What’s safe to delete. Or edit? Can I fix system problems with it? I’m just interested to learn more about the inner workings of Mac system software. Most tutorials seem to show you how to run the software and how to select filters, search for specified text, etc., without revealing what use you can make of it.
System Extension Updated. You must approve it in the Security & Privacy System Preferences. Yesterday my M1 Macbook Air running macOS Monterey 12.1 popped up a dialog window titled System Extension Updated, with a message that said something like «A program has updated system extension(s). To finish the update, you must approve it in the Security & Privacy System Preferences», and two buttons, OK and Open Security Preferences. I clicked Open Security Preferences (without first taking a screenshot of the dialog window which then disappeared, so I can’t be sure of the message exactly) thinking that System Preferences would show which application/extension has been updated. But all that System Preferences > Security & Privacy > General says is that «Your current security settings prevent the installation of system extensions» and a button titled Enable system extensions. I don’t want to enable system extensions without first knowing which system extension and which app this all has to do with. I can tell that none of the installed apps or extensions have been updated recently by looking at the Last Modified dates in System Information > Applications and System Information > Extensions respectively. Also, System Information > Legacy Software says «No information found.» I’ve scanned my computer using Bitdefender Virus Scanner and Malwarebytes and they didn’t find anything. But I’m a bit worried because I’ve never seen such a dialog message before.
iMac security and privacy What should I activate to maximise security and privacy on my iMac. Currently, FileVault is off as the warning makes me anxious ! Firewall is on, and the only options checked are: ‘Automatically allow built-in software to receive incoming connections’ and ‘Automatically allow download signed software to receive incoming connections . . allows software signed by a valid certificate authority to provide services accessed from the network’ (whatever all that means) None of the ‘Advanced’ options are checked. In Privacy, the only checked items are ‘Siri and Dictation’, ‘Maps, and ‘Safari’. In ‘System Services . . Details’, all boxes are checked except for ‘Show location icon in menu bar when System Services request your location’. Any advice very welcome.