If you have a newer MacBook Pro, you may have gotten used to authenticating with Touch ID. But by default, Touch ID is not set up to authenticate sudo commands. These commands, which allow for a broader range of power in the command line, have to be authenticated by a password. If you’re a developer or power user on macOS, you might use sudo frequently. It can be extremely useful to authenticate sudo commands with Touch ID.
With a little bit of text file editing, we can access and edit the list of acceptable authentication methods for sudo. By adding a line of text, we’ll make Touch ID an acceptable method of authenticating sudo commands.
There is one potential downside to setting up this command. If you authenticate sudo commands with Touch ID, you might not be able to authenticate sudo over secure shell, or SSH. There’s talk about this getting fixed in a forthcoming version of macOS, maybe in an upcoming beta. If you use SSH frequently, make sure you test this functionality before you need it in a critical situation. For now, if you encounter that problem or bug, you’ll need to roll back the change by removing the text you added.
Authenticate sudo Commands with Touch ID
1. Open Terminal (found in “/Applications/Utilities”) and run the following command:
This will open the list of valid methods for authenticating at the sudo prompt. This is where we will add Touch ID as a valid method of authentication.
2. Create a new line underneath the line beginning with “#sudo” by pressing the down arrow key, then the Return key.
3. On the new line you just created, paste the following text:
You may notice that this text contains some spacing so it lines up cleanly with the existing entries. This isn’t strictly necessary, but it makes things easy to keep track of.
When you add this text, you’ll be adding a new way to authenticate sudo. This adds the Touch ID PAM (pluggable authentication method) to the list of methods that can “unlock” sudo. The other options on the list include account authentication, password authentication, and session authentication.
4. Press Ctrl + O and Enter to save the updated document.
5. Press Ctrl + X to quit the nano text editor.
6. The next time you need sudo, you’ll see the standard system dialog box prompting for the input. If it authenticates directly, you’ll have access to sudo.
If you’d prefer to authenticate via your password instead, click the “Use Password …” button and enter your password in the dialog box.
Conclusion
Once you’ve set up Touch ID to authenticate sudo commands, you’ll be able to authenticate sudo or the root user with just your fingerprint. You’ll also have the option to enter your password manually by clicking the “Use Password …” button. If you decide you want to reverse the change, just remove the line you added and save the settings file again. This will remove Touch ID from your MacBook Pro’s list of acceptable sudo authentication methods.
Our latest tutorials delivered straight to your inbox
Justin Pot has been writing about technology for over a decade, with work appearing in Digital Trends, The Next Web, Lifehacker, MakeUseOf, and the Zapier Blog. He also runs the Hillsboro Signal, a volunteer-driven local news outlet he founded. Read more.
Typing passwords is for suckers, which is why the best part of the latest MacBook Pro is Touch ID. Skipping the lock screen with a quick tap is easily my favorite feature. But there’s one place that still requires a password: the Terminal, if you want to use sudo.
Happily, a tweet by Cabel Sasser showed us how to use Touch ID there as well, and it only takes a minute to set up.
Basically, we need to edit the configuration file for sudo, /etc/pam.d/sudo , adding a single line to the beginning, auth sufficient pam_tid.so . If you know how to do that with your text editor of choice, get to it, but for everyone else, here’s a quick step-by-step tutorial using nano.
Head to the Terminal and run the following command:
You’ll have to enter your password but don’t worry: this will be the last time. The text editor will open. Create a new line near the top of the editor and paste in the following:
When everything looks like the screenshot, press Control+X to exit, then press Y followed by Enter to save your changes. You’re done!
From now on using sudo will trigger the Touch ID window…
…and the Touch ID prompt on the Touch Bar.
It’s a little gimmicky, sure, but if you’re got a long password this could save you time.
Just remember: sudo is powerful, so only set this up if you trust Touch ID to keep it locked down. Note also that setting this up makes it impossible for you to use sudo over SSH, so maybe don’t set this up on a Mac that you connect to remotely.
Here’s a tip from Cabel Sasser of Panic for those of you out there with Touch Bar MacBook Pros who use Terminal and the “sudo” command frequently.
Pro MacBook Pro Tip: have a Touch Bar with Touch ID? If you edit /etc/pam.d/sudo and add the following line to the top…
auth sufficient pam_tid.so
…you can now use your fingerprint to sudo!
Here’s the full step-by-step, for those who want to experiment. That said: sudo is an incredibly powerful command in the Terminal; we don’t recommend messing around with this trick if you don’t feel comfortable working in the Terminal app and changing system preference files.
Also worth noting, via Sasser:
(Important caveat/warning: if you SSH into that machine, you will NOT be able to sudo, as your fingerprint cannot travel through SSH. 😜)
How to enable Touch ID for sudo commands on your MacBook Pro with Touch Bar
In Safari, paste the following into the search bar: file:///etc/pam.d/sudo.
Alternatively, you can edit the file within the Terminal app itself using command-line text editors like emacs or nano; if you choose to do this, go to step 8, and skip steps 10-12.
Press Command-I with the sudo file highlighted to open up the information screen.
Change the privileges of all users to Read & Write.
Paste auth sufficient pam_tid.so on line 2 of the document (underneath the initial comment line)
Note: If you get a note about the document being locked, go back to step 2-5 and make sure you’ve enabled Read & Write privileges on the document.
Save the sudo file and close it.
Now, when you open Terminal and attempt a sudo command, you should be prompted with a Touch ID authentication in lieu of entering your administrator password.
Questions?
Let us know below.
We may earn a commission for purchases using our links. Learn more.
Apple has released macOS Monterey 12.5 beta for public beta testers
Are you ready to take the next version of macOS out for a spin? Here’s how to install the public beta of macOS Monterey on your computer.
Review: Is the Bowers & Wilkins Panorama 3 soundbar the one for you?
If you’re in the market for a new soundbar, it’s worth considering Bowers & Wilkins’ latest entrant, the Panorama 3.
Watch the stunning second trailer for Apple TV+ series ‘Prehistoric Planet’
Apple TV+ has today shared a second trailer for the upcoming dinosaur series ‘Prehistoric Planet,’ a five-night event that will feature Sir David Attenborough.
Need to print something from your iPhone? Check out these printers!
Printers are a reliable way of obtaining a physical copy of documents. Even if you’re mostly using your iPhone or iPad for everyday computing, AirPrint capable printers will keep you printing with no problems. Here are some of our favorites!
Home » SysAdmin » How to Use the sudo Command in Linux
Sudo stands for SuperUser DO and is used to access restricted files and operations. By default, Linux restricts access to certain parts of the system preventing sensitive files from being compromised.
The sudo command temporarily elevates privileges allowing users to complete sensitive tasks without logging in as the root user. In this tutorial, learn how to use the sudo command in Linux with examples.
- A system running Linux
- Access to a command line/terminal window (Activities > Search > Terminal)
- A user account with sudo or root privileges
How to use the sudo Command
sudo was developed as a way to temporarily grant a user administrative rights. To make it work, use sudo before a restricted command. The system will prompt for your password. Once provided, the system runs the command.
Syntax
To start using sudo , use the following syntax:
When the sudo command is used, a timestamp is entered in the system logs. The user can run commands with elevated privileges for a short time (default 15 minutes). If a non-sudo user tries to use the sudo command, it is logged as a security event.
Options
sudo can be used with additional options:
- -h – help; displays syntax and command options
- -V – version; displays the current version of the sudo application
- -v – validate; refresh the time limit on sudo without running a command
- -l – list; lists the user’s privileges, or checks a specific command
- -k – kill; end the current sudo privileges
Additional options can be found under the -h option.
Note: Staying logged in as an administrator compromises security. In the past, admins would use su (substitute user) to temporarily switch to an administrator account. However, the su command requires a second user account and password, which isn’t always feasible.
Granting sudo Privileges
For most modern Linux distributions, a user must be in the sudo, sudoers, or wheel group to use the sudo command. By default, a single-user system grants sudo privileges to its user. A system or server with multiple user accounts may exclude some users from sudo privileges.
We recommend to only grant privileges that are absolutely necessary for the user to perform daily tasks.
The following sections explain how to add a user to the sudoers group.
RedHat and CentOS
In Redhat/CentOS, the wheel group controls sudo users. Add a user to the wheel group with the following command:
Replace [username] with an actual username. You may need to log in as an administrator or use the su command.
Debian and Ubuntu
In Debian/Ubuntu, the sudo group controls sudo users. Add a user to the sudo group with the following command:
Replace [username] with an actual username. You may need to log in as an administrator or use the su command.
Using visudo and the sudoers Group
In some modern versions of Linux, users are added to the sudoers file to grant privileges. This is done using the visudo command.
1. Use the visudo command to edit the configuration file:
2. This will open /etc/sudoers for editing. To add a user and grant full sudo privileges, add the following line:
3. Save and exit the file.
Here’s a breakdown of the granted sudo privileges:
Note: It’s easier to simply add a user to the sudo or wheel group to grant sudo privileges. If you need to edit the configuration file, only do so using visudo. The visudo application prevents glitches, bugs, and misconfigurations that could break your operating system.
Examples of sudo in Linux
Basic Sudo Usage
1. Open a terminal window, and try the following command:
2. You should see an error message. You do not have the necessary permissions to run the command.
3. Try the same command with sudo :
4. Type your password when prompted. The system executes the command and updates the repositories.
Run Command as a Different User
1. To run a command as a different user, in the terminal, enter the following command:
2. The system should display your username. Next, run the following command:
3. Enter the password for [different_username] , and the whoami command will run and display the different user.
Switch to Root User
This command switches your command prompt to the BASH shell as a root user:
Your command line should change to:
The hostname value will be the network name of this system. The username will be the current logged-in username.
Execute Previous Commands with sudo
The Linux command line keeps a record of previously executed commands. These records can be accessed by pressing the up arrow. To repeat the last command with elevated privileges, use:
This also works with older commands. Specify the historical number as follows:
This example repeats the 6th entry in history with the sudo command.
To learn about how to efficiently use history command, check out our article on sudo history command with examples.
Run Multiple Commands in One Line
String multiple commands together, separated by a semicolon:
Add a String of Text to an Existing File
Adding a string of text to a file is often used to add the name of a software repository to the sources file, without opening the file for editing. Use the following syntax with echo, sudo and tee command:
Note: This would add the Nginx software repositories to your system.
You should now understand the sudo command, and how to use it. Next, learn the difference between the sudo and su command.
If you have a Touch Bar equipped MacBook Pro and you’re a frequent command line user, you may appreciate a trick that allows you to use Touch ID to authenticate sudo and su, rather than typing out your password in the Terminal like some kind of digital neanderthal.
One notable problem (or trade-off) is that if you use SSH to connect the Mac with this enabled, you won’t be able to use sudo since Touch ID will not transmit. There are mixed reports that may be changed in beta versions of High Sierra however.
Anyway, if you’re an advanced Mac user with a Touch Bar and Touch ID equipped Mac, here’s how you can enable Touch ID support for sudo authentication. This is really not going to be applicable to novice users or those who don’t spend a significant amount of time at the command line authenticating with sudo, and because this involves editing a system file it’s a good idea to backup your Mac before beginning this process.
How to Use Touch ID for sudo on Mac
Back up your Mac before beginning. From the Terminal (of course), you’ll want to edit /etc/pam.d/sudo by adding a new line to it. For our purposes here we’ll use nano but you’re free to use vim or emacs, or even a GUI app if you’re so inclined.
- Open Terminal app if you haven’t done so already, then enter the following command:
sudo nano /etc/pam.d/sudo
Hit Return and then add the following line to the top:
auth sufficient pam_tid.so
Save the edit with Control+O and then exit nano with Control+X
Now you’re ready to go, Touch ID will now authenticate sudo rather than having to enter a password at the command line. And yes of course you can still use your password too. Note that some users report needing to reboot or refresh their shell to get this to work.
Now the next time you run sudo or su to use root user or run commands as root, you’re able to authenticate by placing a finger onto Touch ID.
This is undeniably useful for Mac users with Touch ID machines, enough so that it should probably be a dedicated settings option somewhere rather than a command line modification. Another helpful trick is to change the sudo timeout for entering a password, which in this case would mean extending the timeout before having to authenticate with Touch ID again.
This tip comes to us from @cabel on Twitter where it has gained some popularity and was the first I’d heard of it, but it’s worth mentioning that using sudo with Touch ID had been discussed before by HamzaSood on Github and elsewhere on the web through various methods. For those Mac users with Touch ID equipped machines and who spend a lot of time in the Terminal, this may appeal to you, so try it out!
Oh and if you want to reverse this change, simply remove the “auth sufficient pam_tid.so” line from /etc/pam.d/sudo again.
Related
Enjoy this tip? Subscribe to our newsletter!
Get more of our great Apple tips, tricks, and important news delivered to your inbox with the OSXDaily newsletter.
Thank you!
You have successfully joined our subscriber list.
Related articles:
- How to Change Sudo Password Timeout in Mac OS X
- Run the Last Executed Command as Root with sudo !!
- 3D Touch Not Working on iPhone? How to Fix & Troubleshoot 3D Touch
- How to Disable Webcam / FaceTime Camera on Mac Completely
9 Comments
after adding that line exactly as instructed, i now get a GUI dialog with username and password when i try to run sudo command.
Hello,
After adding “auth sufficient pam_tid.so” to sudo file, sudo commands work as intended, still the stardard user is not part of sudoers, so I hoped this will also affect $su user_priv lets say. But when I try to change the stardard user to user_priv, touchid does not kick in, is still requiring password. I think changes are needed to /etc/pam.d/su file as well but I am not there yet, can you please help ?
If you want to explore sudo over SSH with TouchID, check this:
Sorry but touch id sounds like a security risk to me. Not for your Mac but your identity itself. Better off using a strong password.
Cool but I would rather have a real keyboard and Face ID I think. I don’t like touch bar.
Darn it. This makes me want a Touch ID equipped MacBook Pro even more. I have a mid-2015 model that works great, does everything I need it to do very fast, but having the ability to use Touch ID on my MacBook Pro would be awesome. I wonder how long it will take for Face ID to happen on Mac. Of course the people who cover up their camera would have to refrain from doing that if they wanted to use Face ID.
This is the first time I’ve seen something useful about Touch Bar on a Mac. But while Touch ID for sudo is interesting, I’d personally never give up a good MacBook Pro (2015) with so many great features just to get that capability and all the loss that comes with it.
The 2015 MacBook Pro is as good as it gets if you ask me, and Marco Arment (founder of Tumblr, prominent Apple writer and pundit) agrees and points out the obvious, calling it the “best laptop ever made” and I would agree with that thoroughly after seeing alternatives.
The 2018/2016/2017 Touch Bar MacBook Pro keyboard is pretty bad, so much so that there are parody songs about how bad the keyboard is and how easy it screws up from even just dust:
And many, many articles online discussing the dreadful keyboard
Or the terrible dongle USB-C situation
Also the Touch Bar itself is a mess and often crashes, it’s slow, and makes you look at your keys when you type which is what all of us were taught exactly NOT to do when learning how to type (remember when they put a box over your hands in typing class??). The lack of an escape key or function buttons makes everything slower and more cumbersome to use ESC or even change sound or brightness. Touch ID is iffy, sometimes OK, but sometimes doesn’t work, or sometimes is slower than typing a password.
Personally I specifically bought a 2015 MacBook Pro rather than a 2017, I like magsafe, the keyboard, escape key, ports, no need for dongles, etc. Cheaper too.
I hope Apple learns the harsh lesson and abandons the current MacBook Pro and starts from scratch, aiming it at real Pro users. A keyboard should not be an obstacle, and neither should ports, a bag of dongles should not be required, nor trying to figure out how to change brightness or use escape or anything else. That’s my 50 cents.
Good to know this. I have considered a laptop. I’ll wait until my Mac mini becomes nonfunctional.
I too find Touch ID oversold. It has never, not once, recognized me on the iPhone. iPad was hit and miss.
My brand new iPad Pro seems somewhat better.
I agree with what you and Marco are saying… yet it’s hard to believe that Apple will abandon a concept that has brought significant sales increases to the Mac line.
If you have the latest MacBook Pro, you may have used the Touch ID authentication feature. But by default, Touch ID is not set for sudo command authentication. These commands, which allow a wide range of control on the command line, must be authenticated with a password. If you are a developer or a user with an authority on the Mac, you may use sudo frequently. It can be very useful for authenticating sudo commands with Touch ID.
With a little editing of a text file, we can access it and edit the list of acceptable authentication methods for sudo. By adding a line of text, we’ll make Touch ID an acceptable way to verify sudo commands.
There is one possible aspect to creating this command. If you authenticate sudo commands with Touch ID, you may not be able to authenticate sudo on a secure shell or SSH. There is talk that this will be fixed in the upcoming Mac version XNUMX, possibly in the next beta. If you use SSH often, be sure to test this functionality before you need it in a critical situation. Currently, if you encounter this problem or error, you will need to undo the change by removing the text you added.
Authentication of sudo commands with Touch ID
This will open the list of valid methods that exist for authentication in the sudo prompt. This is where we will add Touch ID as a valid method of authentication.
2. Create a new line under the line starting with “#sudo” by pressing the down arrow key, then the return key.
3. On the new line you just created, paste the following text:
You may notice that this text has some spacing so that it lines up cleanly with the existing entries. This is not absolutely necessary, but it makes things easy to keep track of.
When you add this script, you’ll be able to add a new way to authenticate to sudo. This adds Touch ID (PAM) to the list of methods that enable sudo to be “unlocked”. Other options on the list include account authentication, password authentication, and session authentication.
4. Press Ctrl + O and Enter to save the updated document.
5. Press Ctrl + X to close the nano text editor.
6. The next time you need sudo, you will see the standard system dialog prompting for input. If the authentication is direct, you will have access to sudo.
If you prefer password authentication instead, click the “Use password. ” button and enter the password in the dialog box.
conclusion
After setting up Touch ID to authenticate sudo commands, you will be able to authenticate a sudo or root user only with your fingerprint. You will also have the option to enter the password manually by clicking on the “Use password…” button. If you decide you want to reverse the change, simply remove the line you added and save the settings file again. This will remove Touch ID from the MacBook Pro’s list of acceptable sudo authentication methods.
Does Touch ID for the MacBook Pro Touch Bar support elevating admin privileges in macOS?
Somewhat differently, can the Touch ID give sudo access in Terminal?
I wonder this because I’m considering getting a YubiKey which can do string input to password fields, but Touch ID for Macs may render it unnecessary.
10 Answers 10
TouchID does support elevating privileges, but as of now, it only seems to be supported in Apple’s own apps. My guess is that 3rd party apps will have to be updated to support it, unfortunately. I still end up typing in my password a lot.
See @conorgriffin’s answer for instructions to enable TouchID for sudo.
To allow TouchID on your Mac to authenticate you for sudo access instead of a password you need to do the following.
Switch to the root user with sudo su –
Edit the /etc/pam.d/sudo file with a command-line editor such as vim or nano
The contents of this file should look like one of the following examples:
You need to add an additional auth line to the top so it now looks like this:
Save the file. (Note: this file is normally read-only so saving your changes may require you to force the save, e.g. vim will require you to use wq! when saving)
Also note that pam_smartcard.so may not be present on older MacOS versions.
Exit from the root user or start a new terminal session.
Try to use sudo , and you should be prompted to authenticate with TouchID as shown below.
If you click ‘Cancel,’ you can just enter your password at the terminal prompt. If you click ‘Use Password’ you can enter your password in the dialog box.
If you SSH into your machine it will fall back to just use your password, since you can’t send your TouchID fingerprints over SSH.
Note: See answer by user Pierz below if you’re using iTerm, as there’s a setting you need to explicitly change to enable this feature.
Note: Recent MacOS updates may remove the entry. If TouchID stops working for sudo then check if the entry was removed and add it back in, following these instructions again.
If you’re using iTerm2 (v3.2.8+) you may have seen Touch ID failing to work with sudo in the terminal despite having made the pam_tid.so modification as above, and it working in previous versions. This is down to an advanced feature that seems to be now enabled by default – this needs to be turned off here: iTerm2->Preferences > Advanced > (Goto the Session heading) > Allow sessions to survive logging out and back in.
Alternatively you can use this pam_reattach module to retain the session feature and TouchID sudo at the same time.
You can use fingerprint for getting sudo access in the terminal or iTerm, just add auth sufficient pam_tid.so to the first line to your /etc/pam.d/sudo file.
I have created a simple script that enables sudo to use the TouchID PAM module exactly as conorgriffin explains. It does it in a single script that you can copy-paste to a terminal in it’s entirety or use the ” curl pipe bash ” shortcut:
curl -sL | bash
This script demonstrates a few cool patterns that I love to teach people who are new to bash or DevOps.
- Create a backup file that is numbered rather than simply .bak on the end. (It looks gnarly, but that pattern works with whatever is in $file and is reusable.
- To make it safe to do curl . | bash , wrap everything in a function and call it on the last line. That way if the download is interrupted, nothing is (partially) done.
- Put a call to sudo bash -eu in your script so that you don’t have tell the user to do it. ( -eu are short for errexit and nounset and you should be using them!)
- Single quoting bash heredoc ‘EOF’ to prevent premature shell expansion.
- Making inline awk more readable.
รหัสผ่านสำหรับการพิมพ์คือ suckers ซึ่งเป็นสาเหตุที่ส่วนที่ดีที่สุดของ MacBook Pro ล่าสุดคือ Touch ID การข้ามหน้าจอล็อคด้วยการแตะด่วนเป็นคุณสมบัติที่ฉันโปรดปรานได้อย่างง่ายดาย แต่มีที่เดียวที่ยังต้องใช้รหัสผ่าน: Terminal หากคุณต้องการใช้ sudo.
มีความสุขทวีตของ Cabel Sasser แสดงให้เราเห็นถึงวิธีการใช้ Touch ID ที่นั่นเช่นกันและใช้เวลาเพียงไม่กี่นาทีในการตั้งค่า.
โดยทั่วไปเราจำเป็นต้องแก้ไขไฟล์กำหนดค่าสำหรับ sudo, /etc/pam.d/sudo , เพิ่มบรรทัดเดียวไปยังจุดเริ่มต้น, รับรองความถูกต้องเพียงพอ pam_tid.so . หากคุณรู้วิธีการทำด้วยโปรแกรมแก้ไขข้อความที่คุณเลือกไปหา แต่สำหรับคนอื่น ๆ นี่คือการสอนแบบทีละขั้นตอนอย่างรวดเร็วโดยใช้ nano.
มุ่งหน้าไปยัง Terminal และเรียกใช้คำสั่งต่อไปนี้:
คุณจะต้องป้อนรหัสผ่าน แต่ไม่ต้องกังวล: นี่จะเป็นครั้งสุดท้าย เครื่องมือแก้ไขข้อความจะเปิดขึ้น สร้างบรรทัดใหม่ใกล้กับด้านบนสุดของตัวแก้ไขและวางต่อไปนี้:
เมื่อทุกอย่างดูเหมือนภาพหน้าจอให้กด Control + X เพื่อออกจากนั้นกด Y ตามด้วย Enter เพื่อบันทึกการเปลี่ยนแปลงของคุณ คุณทำเสร็จแล้ว!
นับจากนี้ไปการใช้ sudo จะทำให้หน้าต่าง Touch ID .
…และพรอมต์ Touch ID บน Touch Bar.
มันเป็นลูกเล่นเล็ก ๆ น้อย ๆ อย่างแน่นอน แต่ถ้าคุณมีรหัสผ่านที่ยาวสิ่งนี้อาจช่วยคุณประหยัดเวลาได้.
เพียงจำไว้ว่า: sudo นั้นทรงพลังดังนั้นให้ตั้งค่านี้เฉพาะเมื่อคุณเชื่อถือ Touch ID เพื่อล็อคมันไว้ โปรดทราบด้วยว่าการตั้งค่านี้ทำให้คุณไม่สามารถใช้ sudo ผ่าน SSH ได้ดังนั้นอาจไม่ตั้งค่านี้บน Mac ที่คุณเชื่อมต่อจากระยะไกล.
Įvesdami slaptažodžius, tai “pakrovėjai”, todėl geriausia naujausio “MacBook Pro” dalis yra “Touch ID”. Praleisti užrakto ekraną greitai spustelėti yra lengvai mano mėgstamiausia funkcija. Tačiau ten yra ta vieta, kur vis dar reikalingas slaptažodis: Terminalas, jei norite naudoti sudo.
Laimei, “Cabel Sasser” tweeter parodė mums, kaip ten naudoti ir “Touch ID”, ir jis nustato tik minutę
Iš esmės turime redaguoti sudo konfigūracijos failą, /etc/pam.d/sudo , pridėti vieną eilutę prie pradžios, auth sufficient pam_tid.so . Jei žinote, kaip tai padaryti naudodami pasirinktą teksto redaktorių, pasiekite jį, bet visiems kitiems, čia yra greitas žingsnis po žingsnio vadovaujantis “nano”.
Eikite į terminalą ir paleiskite šią komandą:
Jums reikės įvesti savo slaptažodį, bet nesijaudinkite: tai bus paskutinis kartas. Bus atidarytas teksto redaktorius. Kurti naują eilutę šalia redaktoriaus viršuje ir įklijuokite taip:
Kai viskas atrodys kaip ekrano nuotrauka, paspauskite “Control + X”, kad išeitumėte, tada paspauskite “Y”, po to “Enter”, kad išsaugotumėte savo pokyčiai. Jūs jau baigėte!
Nuo šiol naudojant sudo bus paspaudžiamas Touch ID langas .
. ir jutiklinio juostos jutiklio juostoje.
Tai šiek tiek gudrus, tikrai, bet jei jūs gaunate ilgas slaptažodis tai gali sutaupyti laiko.
Tiesiog nepamirškite: sudo yra galingas, todėl nustatykite tai tik tada, jei pasitikite “Touch ID”, kad ji būtų užrakinta. Atkreipkite dėmesį, kad nustatant šį parametrą negalima naudoti sudo per SSH, taigi galbūt nenustatykite to Mac, kad prisijungtumėte nuotoliniu būdu.
Ar jūs kada nors pametėte klaviatūrą, ar jūsų kompiuteris tiesiog atsisako priimti jo įvestį? Tai ypač varginantis, jei taip nutinka, kai kompiuteris išjungtas, nes negalite įvesite savo slaptažodžio, norėdami gauti prieigą prie “Windows”. Laimei, “Microsoft” įtraukė būdą, kaip pasiekti jūsų duomenis (ir, tikiuosi, išspręsti problemą) naudodamas tik pelę arba jutiklinį ekraną.
“Microsoft” ką tik pradėjo “Windows 10” versiją, kuri bus paleista mažos galios ARM aparatine įranga. Skirtingai nuo “Windows RT”, “Windows 8” versija, kuria naudojamas originalus “Surface” ir “Surface 2”, tai yra pilna “Windows 10” versija su emuliacijos lygiu, leidžiančiu jam paleisti tradicines darbalaukio programas ne “Windows” parduotuvėje.
Zadávání hesel je pro výstřely, což je důvod, proč nejlepší část nejnovějšího MacBooku Pro je Touch ID. Přeskočení obrazovky zámku rychlým klepnutím snadno představuje moje oblíbená funkce. Existuje však jedno místo, které stále vyžaduje heslo: Terminál, pokud chcete použít sudo.
Šťastně, tweet od Cabel Sasser nám ukázal, jak použít Touch ID tam také, a trvá to jen minutu, než je nastavit
V podstatě musíme upravit konfigurační soubor pro sudo, /etc/pam.d/sudo , přidáme na začátek jeden řádek, auth dostatečně pam_tid.so . Pokud víte, jak to udělat s volitelným textovým editorem, přejděte k němu, ale pro všechny ostatní, je zde stručný návod k použití nano.
Přejděte do Terminálu a spusťte následující příkaz:
Budete muset zadat své heslo, ale nebojte se: bude to naposledy. Otevře se textový editor. Vytvořte nový řádek v horní části editoru a vložte následující:
Když vše vypadá jako snímek obrazovky, stiskněte klávesu Control + X pro ukončení a poté stisknutím tlačítka Y a poté klávesou Enter uložte Změny. Už jste hotovo!
Od této chvíle pomocí sudo spustíte okno dotykového ID .
. a dotykový dotykový prvek na dotykovém panelu.
Je to trochu obtížné, ale pokud máte dlouhé heslo, které vám může ušetřit čas.
Nezapomeňte, že sudo je silný, nastavte jej pouze tehdy, pokud důvěřujete dotykovému ID, abyste ho udrželi uzamčeni. Uvědomte si také, že toto nastavení vám znemožňuje použít sudo přes SSH, takže možná nenastavujte toto nastavení na Mac, ke kterému se vzdáleně připojujete.
Pokud používáte počítač ve vlastnictví společnosti, pravděpodobně jste viděli, že se před přihlášením do systému Windows zobrazuje právní upozornění. Zde je návod, jak udělat to samé na vašem PC a zobrazit zprávu s libovolným textem, který chcete. Pokud jste ochotni se ponořit do registru Windows nebo Local Group Policy Editor, můžete udělat několik zajímavých věcí, které můžete udělat obklopující přihlašování k systému Windows.
“Pokaždé, když otevře iTunes na svém počítači Windows 10, zobrazí se pouze bílá obrazovka a zamrzne. ” ” iTunes už potřeboval pár hodin k synchronizaci, ale ještě nebyl dokončen. Co se s ním děje? ” ” Když se pokouším synchronizovat svůj iPhone s novým počítačem, iTunes říká, že pro tento počítač nemám oprávnění.
How would I run the following command in windows:
17 Answers 17
There is no sudo command in Windows. The nearest equivalent is “run as administrator.”
You can do this using the runas command with an administrator trust-level, or by right-clicking the program in the UI and choosing “run as administrator.”
All the answers explain how to elevate your command in a new console host. So, I wrote: gsudo to behave like Unix/Linux sudo , allowing to execute the command inside the current console.
gsudo
- Source Code, Documentation, and Releases available at:
Most relevant features:
- Elevates in the current console (no new window)
- Elevates cmd commands, but also PowerShell / WSL / Git-Bash / cygwin / Msys / commands natively.
- Optional: Credentials Cache (Elevate many times with only one UAC popup)
Installation
- Using scoop: scoop install gsudo
- Using Chocolatey: choco install gsudo
- Using Winget: winget install gerardog.gsudo
- Manually: Download the latest release, unzip, and add to path, from
Open notepad and paste this code:
Then, save the file as sudo.cmd . Copy this file and paste it at C:\Windows\System32 or add the path where sudo.cmd is to your PATH Environment Variable.
When you open command prompt, you can now run something like sudo start . .
If you want the admin command prompt window to stay open when you run the command, change the code in notepad to this:
powershell -Command runs a powershell command.
Start-Process is a powershell command that starts a process, in this case, command prompt.
-Verb RunAs runs the command as admin.
-Argument-List runs the command with arguments.
Our arguments are ‘/c cd /d %CD% && %*’ . %* means all arguments, so if you did sudo foo bar , it would run in command prompt foo bar because the parameters are foo and bar, and %* returns foo bar . cd /d %CD% is a command to go to the current directory. This will ensure that when you open the elevated window, the directory will be the same as the normal window. the && means that if the first command is successful, run the second command.
The /c is a cmd parameter for closing the window after the command is finished, and the /k is a cmd parameter for keeping the window open.
Credit to Adam Plocher for the staying in the current directory code.
Если Ваш Mac или клавиатура Magic Keyboard оснащены сенсором Touch ID, Вы можете использовать его для разблокировки Mac, авторизации покупок в iTunes Store, App Store и Apple Books, а также совершения покупок на веб-сайтах, поддерживающих Apple Pay. Можно также использовать Touch ID для входа в некоторые приложения сторонних разработчиков.
Настройка Touch ID
На Mac выберите пункт меню Apple
> «Системные настройки», затем нажмите «Touch ID» .
Нажмите «Добавить отпечаток», введите свой пароль и следуйте инструкциям на экране.
Если Ваш Mac или клавиатура Magic Keyboard оснащены сенсором Touch ID, он располагается в правом верхнем углу клавиатуры. В учетную запись можно добавить максимум три отпечатка пальцев (всего можно сохранить на Mac не более пяти отпечатков).
Установите нужные флажки, чтобы указать, для чего может использоваться Touch ID:
Разблокировка Mac. Используйте Touch ID для разблокировки Mac при выводе компьютера из режима сна.
Apple Pay. Используйте Touch ID для оплаты покупок, сделанных с этого Mac, с помощью Apple Pay.
iTunes Store, App Store и Apple Books. Используйте Touch ID для оплаты покупок в интернет-магазине Apple, сделанных с этого Mac.
Автозаполнение пароля. Используя Touch ID, можно автоматически заполнять имена пользователей и пароли, а также данные кредитных карт при их запросе в Safari и других приложениях.
Использовать сенсор Touch ID для быстрого переключения пользователей. Можно будет перейти в другую учетную запись на Mac при помощи Touch ID.
Переименование или удаление отпечатков пальцев
На Mac выберите пункт меню Apple
> «Системные настройки», затем нажмите «Touch ID» .
Выполните одно из следующих действий.
Переименование отпечатка. Нажмите текст под отпечатком и введите название.
Удаление отпечатка. Выберите отпечаток, введите пароль, нажмите «OK», затем нажмите «Удалить».
Использование Touch ID для разблокировки Mac, входа в систему или смены пользователя
Чтобы использовать Touch ID для выполнения этих задач, Вы должны предварительно войти в систему Mac, введя свой пароль.
Разблокировка Mac и некоторых объектов, защищенных паролем. Выводя Mac из режима сна или открывая объекты, защищенные паролем, просто приложите палец к сенсору Touch ID при появлении запроса.
Вход из окна входа в систему. Нажмите свое имя в окне входа, затем приложите палец к сенсору Touch ID.
При помощи Touch ID можно разблокировать только те учетные записи пользователей, в которых есть пароль. В учетных записях только для общего доступа и в гостевых учетных записях нельзя использовать Touch ID.
Переключение пользователей. Из меню быстрого переключения пользователей в строке меню выберите другого пользователя, затем приложите палец к сенсору Touch ID.
Чтобы Touch ID можно было использовать для смены пользователя, должно быть настроено быстрое переключение пользователей, а пользователь, которого Вы хотите выбрать, должен предварительно войти в систему Mac, используя свой пароль.
Использование Touch ID для совершения покупок
Войдите в систему Mac, введя пароль.
Совершите покупку с помощью Apple Pay или в одном из интернет-магазинов Apple.
Поместите палец на сенсор Touch ID, когда появится соответствующий запрос.
Если возникли проблемы с Touch ID
Если сенсор Touch ID не распознает отпечаток пальца. Убедитесь, что палец сухой и чистый, затем повторите попытку. Влага, следы крема, порезы, пересохшая кожа — все это может повлиять на распознавание отпечатка пальца.
Если Ваша клавиатура Magic Keyboard оснащена Touch ID. Если Вы не можете разблокировать Mac, зарегистрируйте отпечаток пальца или введите пароль при помощи Touch ID. См. статью службы поддержки Apple: Если Touch ID не работает на компьютере Mac.
Если все равно требуется вводить пароль. В целях безопасности нужно обязательно вводить пароль при запуске Mac. Бывают ситуации, когда для продолжения использования Touch ID необходимо ввести пароль. Например, каждый пользователь должен повторно вводить пароль каждые 48 часов, а также после пяти неуспешных попыток распознавания отпечатка пальца.
Примечание. В качестве дополнительной меры безопасности только пользователи, вошедшие в систему, могут получить доступ к своей информации Touch ID. Администратор не может менять ни настройки Touch ID, ни отпечатки пальцев для другого пользователя.
Skrivning af adgangskoder er til suckers. Derfor er den bedste del af den nyeste MacBook Pro Touch ID. At hoppe over låseskærmen med et hurtigt tryk er let min favorit funktion. Men der er et sted, der stadig kræver et kodeord: Terminal, hvis du vil bruge sudo.
Heldigvis viste en tweet af Cabel Sasser os, hvordan du bruger Touch ID der også, og det tager kun et minut at oprette .
Vi skal grundlæggende redigere konfigurationsfilen til sudo, /etc/pam.d/sudo , tilføje en enkelt linje til begyndelsen, auth tilstrækkelig pam_tid.so . Hvis du ved hvordan du gør det med din valgte tekstredigeringsprogram, skal du komme til det, men for alle andre er her en hurtig trin-for-trin vejledning ved hjælp af nano.
Gå til Terminal og kør følgende kommando:
Du bliver nødt til at indtaste dit kodeord, men rolig: det er sidste gang. Teksteditoren åbnes. Opret en ny linje nær toppen af editoren og indsæt følgende:
Når alt ser ud som skærmbilledet, tryk på Control + X for at afslutte, og tryk derefter på Y efterfulgt af Enter for at gemme din ændringer. Du er færdig!
Fra nu af bruger sudo udløser Touch ID vinduet .
. og Touch ID prompt på Touch Bar.
Det er lidt gimmicky, men hvis du har det en lang adgangskode dette kan spare dig tid.
Bare husk: sudo er kraftfuld, så kun indstille dette, hvis du har tillid til Touch ID for at holde den låst. Bemærk også, at opsætning af dette gør det umuligt for dig at bruge sudo over SSH, så måske ikke indstille det på en Mac, som du opretter forbindelse til eksternt.
Email er et kraftfuldt værktøj, som vi alle bruger, men det kan også være yderst irriterende at få underretninger for hver eneste besked, der rammer din indbakke. Med Gmail er der dog en række forskellige måder at holde tingene stille på, men alligevel kender de omgående de meddelelser, der er vigtige for dig.
Hvis nogen sender misbrugte meddelelser i en Facebook-gruppe, du administrerer, skal du fjerne den. Det er hurtigt og nemt at gøre, så her er hvordan. Klik på den nedadrettede pil ud for den offensive besked. Fra rullemenuen skal du vælge Slet post. Facebook vil bede dig om at bekræfte, så klik på Slet igen.
Среду командной строки можно использовать в интерактивном режиме, то есть вводить команду и ждать результат. Вы также можете составить shell-скрипт, который будет выполняться без Вашего непосредственного участия.
Выполнение команд в оболочке shell
В приложении «Терминал» на Mac введите полный путь к исполняемому файлу инструмента, затем введите все необходимые аргументы и нажмите клавишу Return.
Если команда находится в одной из известных папок shell, при вводе имени команды можно не указывать путь. Список известных папок хранится в переменной среды PATH оболочки shell и включает папки, содержащие большинство инструментов командной строки.
Например, чтобы выполнить команду ls в папке текущего пользователя, введите следующую команду в командной строке, затем нажмите Return:
Чтобы выполнить команду в папке текущего пользователя, введите перед командой спецификатор папки. Например, чтобы выполнить MyCommandLineProg , используйте следующую команду:
Чтобы открыть приложение, используйте команду open:
Если при вводе команды отображается сообщение command not found , проверьте правильность написания. Пример:
Прерывание команд
В приложении «Терминал» на Mac нажмите окно Терминала, где выполняется команда, которую Вы хотите завершить.
Нажмите сочетание клавиш Control-C.
Будет отправлен сигнал, который вызывает прерывание большинства команд.
Повтор ранее введенных команд
Введенные в текущем сеансе команды сохраняются, так что Вы можете повторить ранее использованную команду, не вводя ее снова.
В приложении «Терминал» на Mac нажмите клавишу со стрелкой вверх.
Последняя введенная команда отобразится в командной строке.
Продолжайте нажимать клавишу со стрелкой вверх, пока не появится нужная команда, затем нажмите клавишу Return.
Mac OS X Sudo Password Bypass
Description
This module gains a session with root permissions on versions of OS X with sudo binary vulnerable to CVE-2013-1775. Tested working on Mac OS 10.7-10.8.4, and possibly lower versions. If your session belongs to a user with Administrative Privileges (the user is in the sudoers file and is in the “admin group”), and the user has ever run the “sudo” command, it is possible to become the super user by running `sudo -k` and then resetting the system clock to 01-01-1970. This module will fail silently if the user is not an admin, if the user has never run the sudo command, or if the admin has locked the Date/Time preferences. Note: If the user has locked the Date/Time preferences, requests to overwrite the system clock will be ignored, and the module will silently fail. However, if the “Require an administrator password to access locked preferences” setting is not enabled, the Date/Time preferences are often unlocked every time the admin logs in, so you can install persistence and wait for a chance later.
Author(s)
- Todd C. Miller
- joev
- juan vazquez
Platform
Architectures
Development
- Source Code
- History
Module Options
To display the available options, load the module within the Metasploit console and run the commands ‘show options’ or ‘show advanced’:
- Collect and share all the information you need to conduct a successful and efficient penetration test
- Simulate complex attacks against your systems and users
- Test your defenses to make sure they’re ready
- Automate Every Step of Your Penetration Test
Free Metasploit Pro TrialView All Features
Time is precious, so I don’t want to do something manually that I can automate. Leveraging the Metasploit Framework when automating any task keeps us from having to re-create the wheel as we can use the existing libraries and focus our efforts where it matters.
– Jim O’Gorman | President, Offensive Security
Introduction –
Linux follows the very tough permission model. A root user can do anything but normal user has no permissions. To run any command, they need to ask for permissions from the superuser. The easy and common way to grant administrative privileges to non-root users is, a user can use su command and temporarily become the root but users must know the root’s password. In corporate world this is very dangerous because all the privileges of root are granted to any user, who can do anything. For Example –
It’s asking for the password of superuser.
To overcome above mentioned risk, sudo command comes in trend. It allows a user to run a command as a root or as any other user after providing the user’s own password for authentication. These information are defined in the /etc/sudoers file. Before describing “sudo” command I want to talk a bit about visudo
What is visudo –
visudo is a command to edit configuration file for sudo command located at /etc/sudoers.You should not edit this file directly with normal editor, always use visudo for safety and security. Editing /etc/sudoers file requires superuser’s privileges.
visudo command cannot allow to edit /etc/sudoers file simultaneously by just locking the file and if someone tries to access the same it will get a message to try later.
It also checks the syntax of edits and provide basic sanity checks which are very helpful. If it identifies any error, then visudo won’t allow to save the file with edits.
Set rules in sudoers file –
A common question arises in everyone’s mind, how we define the rules in sudoers file? So, before editing it’s better to understand the existing configuration which defines which users can run what software on which machines. Syntax of pre-defined rule is given below –
This allows root to run any command anywhere.Meaning of this line is –
ALL means, the user can run all commands on all hosts, as all users and groups. So, root has all the privileges to run any command as any user or group.
Let considered an example and provide ALL power to userA as root.
If you wish to use command without password then use PASSWD parameter –
In below example userA only start, stop and restart the “httpd” service
User can check whether the command is working or not. Then follow the below procedure to check –
Note – We can also use vim with visudo.
Using nano with visudo
Assign privileges to a group –
You can assign similar privileges to multiple users just by making a group them. There is one predefined group is in sudoers file. Members of this group can use sudo to run any commands as any user, including superuser. We can add users to this group. It is normally configured like –
Simple way to allow Mac Touch ID authentication in Command prompt.
Labbots
I am a software architect and a programming enthusiast. I am a passionate developer with a proven track record on translating complex business ideas into working implementations.
Labbots
Mac pro have fingerprint scanner (Touch ID) to simplify login process but this is not exposed in terminal. So each time you run commands with elevated privileges you need to type in your password. Following simple change would allow you to use Touch ID for authentication in Command prompt.
To use MacOS Touch ID in Terminal for sudo access instead of entering system password.
Edit this file /etc/pam.d/sudo with your favourite editor.
Add the following line to the top of the file.
To enable Touch ID access on Iterm2. You need to do the following.
Go to Prefs -> Advanced -> Allow sessions to survive logging out and back in and set value to no .
Restart Iterm2 and voilà touch ID authentication will work on Iterm2.
Terraform Google site verification
Automating google site verification using terraform
Measure CPU and GPU temperature of Raspberry PI
A simple bash script to measure the temperature of CPU and GPU of Raspberry Pi.
Native and reliable TouchID support for sudo
Try it out without installing
Now sudo is great, just like Safari — with your fingerprint in Terminal or whatever you’re on.
Don’t worry, you can also reverse it without installing
Please note: without full installation, TouchID for sudo will be disabled after the next macOS update.
- Fast
- Reliable
- Written in Bash — no dependencies!
- Include it to your automated system build — always working and up to date with major macOS upgrades!
curl is pre-installed in macOS
Performs automated “manual” installation.
The installation process:
- Makes the sudo-touchid command available.
- Makes it auto-run on every system launch (using a simple launchd daemon with RunAtLoad key set to true) , so that when a macOS update erases our custom sudo configuration, sudo-touchid fixes it again.
if not installed, can be used via curl bundled with macOS
macOS updates do reset /etc/pam.d/sudo , so previously users had to manually edit the file after each upgrade.
This tool was born to automate the process, allowing for TouchID sudo auth to be quickly enabled on a new/clean system.
Spreading the technology.
I bet half of you didn’t know.
It was there for a long time.
The script is small, doesn’t need any builds, doesn’t need XCode.
Code size comparison — previously favoured solution VS. the one you’re currently reading:
How does it work?
sudo-touchid.sh — the script:
Adds auth sufficient pam_tid.so to the top of /etc/pam.d/sudo file following @cabel’s advice
Creates a backup file named sudo.bak .
Has a –disable ( -d ) option that performs the opposite of the steps above.
com.user.sudo-touchid.plist — the property list (global daemon):
Runs sudo-touchid.sh on system reload
Needed because any following macOS updates just wipe out our custom sudo .
install.sh — the installer:
Saves sudo-touchid.sh as /usr/local/bin/sudo-touchid and gives it the permission to execute.
(yes, that also means you’re able to run sudo-touchid from Terminal)
Saves com.user.sudo-touchid.plist to /Library/LaunchDaemons/ so that it’s running on boot (requires root permission).
- Generally follow the steps provided by the installer in “Non-Homebrew files”
- If you need to, store sudo-touchid.sh anywhere else and replace /usr/local/bin in com.user.sudo-touchid.plist with the chosen path.
PRs and Issues are much welcome!
If you don’t like something — change it or inform the ones willing to help.
AppleInsider is supported by its audience and may earn commission as an Amazon Associate and affiliate partner on qualifying purchases. These affiliate partnerships do not influence our editorial content.
A vulnerability has been discovered in ‘Sudo,’ a powerful utility used in the macOS Terminal, one that could allow for users with restrictive privileges or malicious software to be able to run commands with administrative-level privileges, which could result in the loss or theft of user data in unpatched Macs.
Sudo is an important utility within macOS and other Unix-based systems, including Linux, with it typically used to run administrative commands with the security privileges of a superuser or “root.” It is a well-used element of system maintenance and configuration via the Terminal, and has the potential to cause havoc if misused.
Found by Apple security employee Joe Vennix, the vulnerability in sudo is a privilege escalation vulnerability, one that has been given the tracking code CVE-2019-18634. At its core, the vulnerability can allow a user that doesn’t typically have permissions to perform tasks that require administrative access to do just that.
For versions of sudo before 1.8.26, The Hacker News reports a stack-based buffer overflow issue is present, requiring the “pwfeedback” option to be enabled within the sudoers configuration file. The feature provides users with an asterisk when they input a password into Terminal.
Though it is not typically enabled by default in many packages if pwfeedback is enabled, the exploit itself can be performed by any user of a system, even without access to the sudo permissions.
According to sudo developer Todd C. Miller, the bug can be observed “by passing a large input to sudo via a pipe when it prompts for a password.” As the attacker has “complete control of the data used to overflow the buffer,” this means there is a “high likelihood of exploitability.”
Last week, Apple released a patch update for macOS High Sierra 10.13.6, macOS Mojave 10.14.6, and macOS Catalina 10.15.2 to fix the problem. Vennix reported the issue to the sudo maintainer team, which has released a patch fixing the problem, bringing sudo up to 1.8.31.
The issuance of the patches, as well as the unlikelihood of having pwfeedback enabled from the outset makes it improbable that most users will be affected by attacks using the vulnerability.
Even so, end users are able to check if their Mac is still affected by running the command “sudo -l” in the macOS Terminal, and seeing if pwfeedback is listed under “Matching Defaults entries.” In cases where it is enabled but macOS wasn’t patched, it can be disabled by changing “Defaults pwfeedback” to “Defaults !pwfeedback” within the sudoers configuration file.
This is not the first sudo issue Vennix has uncovered. In 2019, an exploit allowed bad actors to similarly run commands as root, by specifiying their user ID as “-1” or “4294967295.”
sudo (Super User DO) command in Linux is generally used as a prefix of some command that only superuser are allowed to run. If you prefix “sudo” with any command, it will run that command with elevated privileges or in other words allow a user with proper permissions to execute a command as another user, such as the superuser. This is the equivalent of “run as administrator” option in Windows. The option of sudo lets us have multiple administrators.
These users who can use the sudo command need to have an entry in the sudoers file located at “/etc/sudoers”. Remember that to edit or view the sudoers file you have to use sudo command. To edit the sudoers file it is recommended to use “visudo” command.
By default, sudo requires that users authenticate themselves with a password which is the user’s password, not the root password itself.
sudoers file:
Syntax:
sudo -V | -h | -l | -v | -k | -K | -s | [ -H ] [-P ] [-S ] [ -b ] |
[ -p prompt ] [ -c class|- ] [ -a auth_type ] [-r role ] [-t type ]
[ -u username|#uid ] commandsudo -V | -h | -l | -L | -v | -k | -K | -s | [ -H ] [-P ] [-S ] [ -b ] |
[ -p prompt ] [ -c class|- ] [ -a auth_type ] [-r role ] [-t type ]
[ -u username|#uid ] command
Options
1. -V: The -V (version) option causes sudo to print the version number and exit. If the invoking user is already root, the -V option will print out a list of the defaults sudo was compiled with.
2. -l: The -l (list) option will print out the commands allowed (and forbidden) the user on the current host.
This shows the current user can use all commands as sudo.
3. -h or –help: The -h (help) option causes sudo to print a usage message and exit.
4. -v: If, given the -v (validate) option, sudo will update the user’s timestamp, prompting for the user’s password if necessary. This extends the sudo timeout for another 5 minutes (or as given in sudoers) but does not run a command. This does not give any output.
5. -k: The -k (kill) option to sudo invalidates the user’s timestamp.So, the next time sudo is run a password will be required. This option does not require a password and was added to allow a user to revoke sudo permissions from a .logout file.
6. -K: Similar to the -k option, the -K (sure kill) option is used to remove the user’s timestamp entirely. Likewise, this option does not require a password.
7. -b: The -b (background) option tells sudo to run the given command in the background. Note that if you use the -b option you cannot use shell job control to manipulate the process.
8. -p:The -p (prompt) option allows you to override the default password prompt and use a custom one. The following percent (‘%’) escapes are supported:
%u is expanded to the invoking user’s login name;
%U is expanded to the login name of the user the command will be run as (which defaults to root);
%h is expanded to the local hostname without the domain name;
%H is expanded to the local hostname including the domain name (only if the machine’s hostname is fully qualified or the “fqdn” sudoers option is set);
%% (two consecutive % characters) are collapsed into a single % character.
Normally we get this for a sudo command:
Using sudo -p we get,
9. -n: Use -n option as shown below, which will execute the command without prompting for the password. This is very helpful when we want to run some of the sudo commands as background jobs (or in a shell script), where we don’t want sudo to ask for the password. -n option stands for non-interactive.
10. -u: The -u (user) option causes sudo to run the specified command as a user other than root. To specify a uid instead of a username, use #uid.
11. -s: The -s (shell) option runs the shell specified by the SHELL environment variable if it is set or the shell as specified in the file passwd.
12. -H: The -H (HOME) option sets the HOME environment variable to the home directory of the target user (root by default) as specified in passwd. By default, sudo does not modify HOME.
13. -S: The -S (stdin) option causes sudo to read the password from standard input instead of the terminal device.
14. -a: The -a (authentication type) option causes sudo to use the specified authentication type when validating the user, as allowed by /etc/login.conf. The system administrator may specify a list of sudo-specific authentication methods by adding an “auth-sudo” entry in /etc/login.conf.
15. –: The — flag indicates that sudo should stop processing command line arguments. It is most useful in conjunction with the -s flag.
With Xcode running on your Mac, you can check whether Git is also available by prompting for the Git version:
Install Git Using Homebrew
Another way to install Git is with Homebrew, the package management system for Mac.
Run the following brew command in the terminal:
Then, check the Git version to verify the installation:
Install Git Using MacPorts
If you are using MacPorts to manage your packages on the system, you can use the port command to set up Git.
Start by updating MacPorts with the command:
Search for and install the newest Git ports and variants by running the following two commands:
Then, install Git with:
Configure Git
The next step is to configure Git by adding your credentials to the system. This is important as it helps keep track of which user is committing changes to a project.
Open the terminal and configure your GitHub username:
Then, add your email:
Track and Commit Changes
To demonstrate how to work with files on local Git repositories, we are going to create a demo folder and file to work with.
#First, open the terminal and create a new folder named NewFolder.
#Then, move into that directory. The path may differ according to the location where you created the new folder.
#As we want to keep track of changes inside this folder, we need to create a local Git repository for it. Running the git init command initializes an empty git repository in this particular location. Therefore, run the command:
# While in the directory NewFolder, type the following command:
This shows the state of the working directory and displays if any changes made inside the directory.
Since the folder we created doesn’t have any files in it, the output responds with: nothing to commit.
#Add some files inside NewFolder and see how the git status changes:
#Check the status again:
The output tells you there are untracked files inside the directory and lists file1.txt. Git is tracking the folder in which the file was added, and notifies you that the changes are not being tracked.
#Prompt Git to track the new file by running:
If you recheck the git status now, you would see that the file is now being tracked (as it changed from red to green). However, you still need to commit this change.
# Commit all changes and add a message that describes the commit:
There are a lot of different ways to use Git. There are the original command-line tools, and there are many graphical user interfaces of varying capabilities.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| #! /bin/sh |
| # A shell script to enable sudo by “Touch ID” on macOS |
| # tested on macOS 11.6 Big Sur |
| TARGET_FILE=/etc/pam.d/sudo |
| # skip if it is not run on macOS |
| if [ ‘ Darwin ‘ != ` uname ` ] ; then |
| echo ” not on macOS platform. exit. “ |
| exit 0 |
| fi |
| # check target file |
| grep ” auth sufficient pam_tid.so ” $TARGET_FILE > /dev/null |
| if [ $? -ne 1 ] ; then |
| echo ” already has pam_tid.so line in $ |
| exit 0 |
| fi |
| # edit file with sed command. |
| # with -i option, sed creates backup file on the same directory. |
| sudo chmod +w $ |
| sudo sed -i ‘ .bak ‘ -e ‘ 2 i\ |
| auth sufficient pam_tid.so ‘ $ |
| if [ $? -ne 0 ] ; then |
| echo ” an error occured. exit. “ |
| exit 0 |
| fi |
| sudo chmod -w $ |
| echo ” succeeds. see $ |
| cat $ |
© 2022 GitHub, Inc.
- Terms
- Privacy
- Security
- Status
- Docs
- Contact GitHub
- Pricing
- API
- Training
- Blog
- About
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Your cheat sheet to boosting Mac productivity
:max_bytes(150000):strip_icc()/DawnaRoberts-225850-ad25a4ced0c64b5e958561d52adf85d3.jpg)
- Tweet
- Share
- Tweet
- Share
In This Article
Jump to a Section
If you are looking to get the most power out of your Mac, you need to embrace the Mac’s terminal and learn some helpful terminal commands. Most users are fine using menus and the mouse to control settings, files, and folders, but if you want to get down under the hood of macOS, terminal can get you there quickly and get the job done.
What Is Mac Terminal?
Mac terminal is an included program on macOS that allows you to use Unix commands (think DOS) to perform dozens of functions quickly and easily without any interference from the operating system. The technical term for it is a command-line interface (CLI). Using the terminal can be very powerful and efficient, but also dangerous.
Be very careful when using terminal commands. If misused, you could end up deleting files and folders faster than you can react (to the point where you might need to restore it from a backup.)
Terminal is sometimes compared to Windows command prompt program. They are similar; however terminal uses Unix commands to function. Windows uses its own command prompt language.
Some users (think IT administrators and developers) use the terminal because it can be faster than the graphical interface most of us use and, the real kicker, it allows access to functions not available through the regular macOS interface.
When using terminal commands, precision matters (including capitalization), so be careful of every character, even spaces.
How to Open Terminal (Command Prompt) on Mac
You can use terminal by opening Finder > Applications > Utilities > Terminal. A window will open, and you will see a command prompt ending with a $. The command line shown is ComputerName:CurrentDirectory
Username$. At the top of the window, you will see the word Bash; it stands for ‘Bourne again shell.’ Bash is the language used for terminal on a Mac.
You are ready to start typing commands.
After every command, press the Return key to execute it. You can also copy and paste into the terminal window.
Keyboard Shortcuts to Use With Terminal
| Tab | Auto-completes files and folder names |
| Ctrl + A | Moves to the beginning of the line you are typing on |
| Ctrl + E | Moves to the end of the line you are typing on |
| Ctrl + W | Deletes the word before the cursor |
| Ctrl + T | Swaps the last two characters before the cursor |
| Esc + T | Swaps the last two words before the cursor |
| Ctrl + L | Clears the screen |
| Ctrl + C | Kills the current process |
| Ctrl + R | Search through previously used commands |
| Option + → | Move the cursor one word forward |
| Option + ← | Move the cursor one word backward |
| Ctrl + F | Move the cursor one character forward |
| Ctrl + B | Move the cursor one character backward |
| Ctrl + Y | Paste whatever was cut by the last command |
| Ctrl + _ | Undo the last command |
| Ctrl + D | Exit the current shell |
Working With Files and Folders
| cd | Shows your home directory |
| cd | Change to a specific directory |
| cd |
Special Commands
| sudo | Run a command with the security privileges of super user |
| nano | Opens the Terminal editor |
| open | Opens a file |
| -h | Show help about a command |
| man | Show the help manual of the command |
Control Permissions
| ls -ld | Display the default permission for a home directory |
| ls -ld/ | Display the read, write, and access permission of a particular folder |
| chmod 755 | Change the permission of a file to 755 |
| chmod -R 600 | Change the permission of a folder (and its contents) to 600 |
| chown : | Change the ownership of a file to user and group. Add -R to include folder contents |
Network and Server Commands
| ping | Ping a host and display its status |
| whois | Output WHOIS information about a domain |
| curl -O | Download a file via HTTP, HTTPS, or FTP |
| ssh @ | Establish an SSH connection to with user |
| scp @ :/remote/path | Copy a to a remote |
The Most Popular Mac Terminal Commands
As a bonus to our terminal cheat sheet, here are some of the most popular terminal commands to get the most out of your Mac.
Show/Hide Hidden Files and Folders
There are times when you need to view hidden files and folders on a Mac, and there is a command for that.
To reverse the command above, change TRUE to FALSE.
Download Files From the Internet
To quickly download a file from the internet use the command below.
Change the Default Location for Screen Shots
Not everyone wants their screenshots saved to the Desktop. With a single command, you can change where they go.
Press Return.
Press Return.
Change the Default File Type for Screenshots
If you want to change the default file type of screenshots, use the following command.
Press Return.
Press Return.
Delete All Files in a Folder
You can easily delete all files in a folder using a single command. However, be warned there is no undo button, once you press Return, the files are gone.
You must include the entire path for the folder name.
Read the Manual
Bash has a complete manual built-in, and you can access the pages through terminal using the “man” command.
For example, if you wanted to know how to use the cd command, you would type in:
You can scroll through pages of the manual by pressing the spacebar.
These are the most common commands, but there are thousands (you can even combine them into one series of commands) you can try in terminal to make your Mac experience more powerful and more enjoyable. But remember, there’s a lot of power in these commands so make sure you type them in correctly.
Linux: ubuntu 14.04.3 LTS
sshpass -f /tmp/passfile parallel-ssh -I -A -h hostlist.txt “sudo -S ls -l /root”
and the method described here in google discussion groups.google outputs the error as:
in the remote server I’m trying to connect its /var/log/auth.log has below message
5 Answers 5
To provide the password as securely, as possible, try this version ( pssh on CentOS, Fedora and parallel-ssh on Ubuntu, Debian):
stty -echo; printf “Password: “; read PASS; stty echo; echo “$
Update (thanks @chutz):
read -s -p “Password: “; echo “$
and then adapt it to pssh like this (updated accordingly):
read -s -p “Password: “; echo “$
I use the same for ad-hoc collection of dumps from multiple servers. Stop it using Ctrl + C as usual. It will show [FAILURE] Interrupted , but that is just because tcpdump would otherwise run infinitely – the output is still in the usual location. The -t 0 option is so the connection doesn’t time out. I could also use tmux or screen and collect the dumps later.
read -s -p “Password: “; echo “$
Make sure to include the correct ssh user and that you connected to those servers before. Testing things locally usually prevents taking down the entire fleet of servers. You can use the 127.0.0.X addresses instead of localhost to approximate multiple hosts.
have you tried running this via echoing the password in the shell?
echo “echo ‘yourpassword’; sudo -S -c ‘ls -l /root'”|pssh -I -H hostlist.txt
I would like to recommend my simple tool “spssh.sh” ( ) , which is simple (only 36 sloc) but useful enough. Unlike parallel-ssh, spssh.sh is interactive, and supports parallel/separate cmd executing. Hope it helps!
Using GNU Parallel you can do something like:
This avoids putting the password on the command line (e.g. echo $PASS ) which can be intercepted by an attacker by running ps aux .
I agree with @satch_boogie comment above – use ansible when you need SUDO and use pssh when you don’t – its cleaner to SUDO in ansible IMO although initial setup is more involved.
Short answer: Example updating and upgrading package with apt :
ansible myservers -a “sudo apt -y update” –become -K
ansible myservers -a “sudo apt -y upgrade” –become -K
Long answer and setup: For my situation, I was using MacOS locally to manage my remote Linux machines. I did the following which may vary slightly if your using Linux:
- make sure you have the same user created locally and on all target machines: sudo adduser username
- add the user to the SUDO group on each target machine: usermod -aG sudo username
- (maybe optional) Setup passwordless ssh though I’m unclear if this is needed but my environment was already setup with this. Try steps below first as it might not be necessary for passwordless ssh.
- Install ansible on your local machine: brew install ansible (or linux sudo apt install ansible )
- create the default hosts file for ansible on your local machine: sudo mkdir /etc/ansible && sudo touch /etc/ansible/hosts
- edit the file sudo nano /etc/ansible/hosts
- Add the target machines under a group (ip or machine name):
- (Optional) I had a second user in the SUDO group on all target machines so I had to temporarily remove this user from the SUDO group to avoid a prompt (like when using sudo systemctl it asks to pick a SUDO user): ansible myservers -a “sudo deluser otheruser sudo” –become -K
- Now run the actual SUDO command you want. Example: ansible myservers -a “sudo apt -y update” –become -K
- (Optional) re-add the otheruser back to the SUDO group: ansible myservers -a “sudo adduser otheruser sudo” –become -K
Now every time I need to run a SUDO command across machines, I simply repeat steps 8-10.
When using sudo to allow edits to files, I regularly get ‘permission denied’.
For example, my mouse is jittery and sluggish, so I want to disable polling:
I’m prompted for a password, and then get:
So I tried to do a temporary change to disable polling by using:
Yet again the system responded with:
7 Answers 7
Output redirection (via the > operator) is done by the shell, not by echo. You have to login as root
Then you can use redirection
Otherwise you can run bash string with sudo
$ sudo echo “Hi” [sudo] password for saji: Hi
The output redirection is done by the shell from which the command has been invoked. So, breaking everything into bits, here what is happening*:
shell invokes sudo echo “options drm_kms_helper poll=N” , which executes sudo command with echo “options drm_kms_helper poll=N” command line
sudo asks for a password, opens superuser shell and invokes echo “options drm_kms_helper poll=N” , which runs echo command passing it “options drm_kms_helper poll=N”
echo, running with root privileges, prints the string to its standard output.
echo command terminates, superuser shell exits, sudo terminates
the shell from which the command has been invoked collects the output and tries to redirect it to /etc/modprobe.d/local.conf , which is writeable only by root. It gets “permission denied” error.
For the ways to fix this see @shantanu answer.
(*) – while the above sequence helps to understand why the command fails, in reality things happen somewhat out-of-order: the original shell notices the redirection and tries to open the file for writing before invoking the sudo . command. When opening the file fails the shell doesn’t even invoke the command which was supposed to write to the file (thanks to @PanosRontogiannis for pointing this out).
Apparently, Debian installer doesn’t install or activate sudo by default. This means that sudo command is not found the only privilege escalation method available is becoming root via su command. Since I like and use sudo daily, I decided to install and setup it on Debian VM.
Install sudo package in Debian
That’s the very first step you’ll need to do: use apt to install sudo. You need to become root before you do it, of course (so you must know root user password for your Debian install):
Configure /etc/sudoers File
/etc/sudoers is the main configuration file for sudo command. It contains list of users and groups that are allowed to become root (or become other users by invoking su command as root).
Here’s the default file in Debian 10 Buster:
I’ve highlighted the 3 most important elements of this file at this early stage:
This is the line that allows you to debug sudo commands as root user.
At this means that any user that belongs to group sudo will also be allowed to use sudo commands:
Finally, this part includes additional configuration files from /etc/sudoers.d directory:
… this means you don’t have to edit /etc/sudoers file but instead can create a specific file in /etc/sudoers.d and name it self-descriptively, like:
meaning, that this file will contain usernames and privileges required by web-server admins (usually commands like stopping/starting Apache or nginx webserver).
Since this is a very basic tutorial, we don’t have to edit the file at all – just need to add our user (mine is greys, as you remember) to the sudo group and check.
Add user to sudo group
Step 1: let’s make sure sudo is not accessible before we begin
This needs to be run as your regular user, not as root:
Let’s check my groups just to be sure there’s no sudo among them:
Step 2: add user to sudo group
Excellent, now it’s time to add user greys to the group sudo (we must become root again to run usermod command)
As you can see, I’m now a member of the sudo group!
Step 3: Log out and log back in for group membership to be recognised
Now you need to disconnect from your server or desktop session and log in again, so that your group membersip is recognised. One reconnected, check your groups with id command and try sudo again:
so yes, we’re a member of sudo group now… This is the moment of truth! Let’s try to become root:
In this guide, you are going to learn how to run only specific commands with sudo in Linux.
Our previous guide covered how to add user to sudo group to enable them to execute the commands with elevated privileges.
So it is possible to enable a user to run only specific commands with sudo in Linux. This can be done by modifying the /etc/sudoers file or by adding user specific sudoers configuration file under the /etc/sudoers.d directory.
For example, to allow a user called john to restart Network Manager as user root on all hosts, edit the sudoers file and add the line below.
To edit sudoers file, you need to be root user or have sudo privileges.
Next, add the line below;
To run specific commands with sudo as any target user, for example to allow user john to restart only Apache service using sudo;
Note that while adding sudo privileges for the user, it is more safer to put the user specific sudo configuration under the /etc/sudoers.d directory for example;
To allow a specific user to run multiple specific commands with sudo;
Replace /path/to/command with the full path of the commands to run and the arguments (if any).
You can find the full path of the command using which command. For example to locate the full path of the command, command1;
You can then run these commands by prefixing them with sudo as in;
For all these commands, you will be prompted to the password for user with which you run these commands as.
Want to run some commands sudo without being prompted for password?
Run sudo Commands Without a Password
sudo has an option called NOPASSWD that can be used to specify commands that can be run as sudo without being prompted for the password.
For example, to enable user called john to restart Network Manager on an Ubuntu system as any user without being prompted for password, at the line below to sudoers file.
To restart NetworkManager as any target user and group, add the line below to sudoers file.
You can simply put this line to user specific sudoers file as follows;
To restart the Network Manager with sudo;
To run all sudo commands without password prompt as any user,group on all hosts, enter the line below in sudoers file.
In this guide, you have learnt how to;
- run only specific commands with sudo in Linux
- run sudo commands without a password
sudo is a powerful command line tool that enables a “permitted user” to run a command as another user (the superuser by default), as defined by a security policy. On most if not all Linux systems, the security policy is driven by the /etc/sudoers file.
Therefore, to run a shell script or program as root, you need to use sudo command. However, sudo only recognizes and runs commands that exist in directories specified in the secure_path in the /etc/sudoers, unless a command is present in the secure_path, you’ll counter an error such as the one below.
This will happen even if the script exists in a directory in the PATH environmental variable, because when a user invokes sudo, PATH is replaced with secure_path.
Sudo Error While Running Script
In the above scenario, the directory /home/aaronkilik/bin is in the PATH environment variable and we are trying to run the script /home/aaronkilik/bin/proconport.sh (finds process listening on a port) with root privileges.
Then we encountered the error “sudo: proconport.sh: command not found”, since /home/aaronkilik/bin is not in the sudo secure_path as shown in next screenshot.
Check Sudo Secure Path
To fix this, we need to add the directory containing our scripts in the sudo secure_path by using the visudo command by editing /etc/sudoers file as follows.
Attention: This method has serious security implications especially on servers running on the Internet. This way, we risk exposing our systems to various attacks, because an attacker who manages to gain access to an unsecure (without superuser privileges) directory that has been added to secure_path, can run a malicious script/program with sudo command.
For security reason, do check out the following article from the sudo website explains a vulnerability relating to secure_path:
Preferably, we can provide the absolute path to a script while running it with sudo:
Run Script Using Sudo Command
That’s It! You may follow list of articles about sudo command:
If you have any questions or thoughts concerning this article, share with us via the comment form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
I have a program that should behave differently if it is being run under “sudo”. Is there a way it can find out if it was run under sudo?
Update: Someone asked why would I want to do this. In this case, on a Mac using MacPorts there is output that tells you to cut-and-paste a particular command. If the MacPorts command was run with “sudo”, it should include sudo in the sample command:
7 Answers 7
Yes, there are 4 environment variables set when a program is running under sudo:
Note that these can be faked by simply setting them. Don’t trust them for anything critical.
For example: In this program we need to tell the user to run some other program. If the current one was run with sudo, the other one will be too.
Note that it only tests for a SUDO_* variable if it can first prove that it is running as root. Even then it only uses it to change some helpful text.
This does not answer the question directly but I do not think the right question is being asked here. It appears to me the asker wants a program which will act different presumably if it has certain permissions or not, however I would argue checking for sudo is not the way to do that. Firstly many systems may not implement a “sudo”, it is by no means required on Linux or many Unixes.
For example a user may be logged in as root already, making the sudo nonsensical or perhaps the system has non root users who still have capabilities to perform the administrative task that the program may wish to do. Finally perhaps the system has no root or sudo at all and instead uses a mandatory access control system with different capabilities and no catch all superuser to sudo into. Or the user could be sudoed, but into an account that has -less- permissions than their own account for security reasons (I often run untrusted code with a temporary unprivileged user who can only write to ramdisks in order to drop, not raise my permissions). It is overall a bad idea to assume a specific permissions model like sudo or the existence of root or to assume a sudoed user has any particular privileges.
If you want to find out if you have permissions to perform an operation the best way is usually to simply try and do it then check errno for permissions issues if it fails or if it is a multi stage operation that must either all fail or all succeed you can check if an operation will work with functions like the POSIX access function (beware of possible race conditions here if permissions are actively being changed)
If in addition you need to know the real user behind the sudo you can use getlogin function which should work for any interactive session with an underlying terminal and would allow you for example to find who is ‘really’ running the command for auditing or find the home directory of the real user to save logs.
Finally if what you really want is to find out if a user has root access (Still a bad idea but less implementation specific) you can use getuid to check for a uid of 0 and thus root.
KB ID 0001247
Problem
Every time I go to a networking event theres a sea of MacBooks in the audience, If techs like MacBooks so much why is there such a lack of decent TFTP software?
Solution
The thing is, I’m looking at the problem with my ‘Windows User’ head on. When I have a task to perform I’m geared towards looking for a program do do that for me. OS X is Linux (There I said it!) Linux in a pretty dress, I’ll grant you, but scratch the surface a little bit and there it is.
Why is that important? Well your already holding a running TFTP server on your hand, your MAC is already running a TFTP server, you just need to learn how to use it.
MAC OS X Native TFTP Server
As I said it’s probably running anyway, but to check, open a Terminal window and issue the following command;
If it’s not running you can manually start and stop the TFTP server with the following commands;
sudo launchctl load -F /System/Library/LaunchDaemons/tftp.plist
Stop TFTP
sudo launchctl unload -F /System/Library/LaunchDaemons/tftp.plist
Note: In macOS Catalina, it’s disabled by default, so if you don’t manually start it, you will see errors like;
It would normally go without saying, but If I don’t say it, the post will fill up with comments! Make sure your Mac is physically connected to the same network as the network device, and has an IP address in the same range.
And make sure the device, and the Mac can ‘ping’ each other.
Use Mac OS X TFTP Deamon To Copy a File To a Network Device
I’ve got a Cisco ASA 5505, but whatever the device is, does not really matter. You will have a file that you have downloaded, and you want to ‘send’ that file to a device. This file will probably be in your ‘downloads’ folder, the TFTP deamon uses the /private/tftpboot folder so we are going to copy the file there. Then set the correct permissions on the file.
Note: You can also use;
sudo chmod 777 /private/tftpboot
sudo chmod 777 /private/tftpboot/*
To set permissions on ALL files in this directory.
You can then execute the command on your device to copy the file across;
Use Mac OS X TFTP Deamon To Copy a File From a Network Device
There is a gotcha with the TFTP daemon, which is you cant copy a file to the TFTP daemon if that file does not already exist there. Which at first glance sort of defeats the object, but what it really means id you have to have a file there with the same name and the correct permissions on it. In Linux you can create a file with the ‘Touch’ command.
You can then sent the file to your Mac from the device;
I Want Mac OS X TFTP Software!
Well you have a limited choice, if you don’t like using the Mac TFTP Daemon. You can install and use a GUI front end that uses the built in TFTP software.
But if you want a ‘stand-alone’ piece of software then the only other one I’ve found is PumpKIN, you will need to disable the built in TFTP daemon or it will throw an error.
Learn how to find and fix issues if Profile Manager doesn’t work the way you expect.
If you can’t access the administration page
Profile Manager’s basic setup is in Server app. You must use Safari to access Profile Manager’s /mydevices webpage and the administration webpage.
Only server administrators can access your administration page. The URL format for your administration page is:
- our_server’s_fully_qualified_domain_name/profilemanager
Example:
To enroll an iPhone, iPad, iPod touch, or a Mac, go to:
- https://your_server’s_fully_qualified_domain_name/mydevices
Example:
If you can’t access the administration page with a web browser other than Safari, try with Safari. If you can’t access it with Safari, check your DNS server. DNS settings are important when you’re managing a Profile Manager deployment. If Profile Manager doesn’t open, make sure your server points to a reliable DNS server.
If you can’t push profiles or apps to clients
If you experience issues when you push profiles or apps to client systems, check the system log file in Console. If it reports that your server can’t reach Apple’s APNs servers, check your network’s configuration. Make sure that all needed ports are open.
For more information, turn on APNS debug logging with these Terminal commands:
You can view the logs in the Console app by filtering on the com.apple.apsd and com.apple.apspd subsystems.
After your APNS transactions are logged, use these Terminal commands to turn off debug logging:
If you get other issues with Profile Manager
Profile Manager logs can help you fix issues with Profile Manager. You can find a symbolic link named “devicemgr” at /var/log. This file points to /Library/Logs/ProfileManager, where you can find these logs:
This log can provide helpful information related to the web server:
- /var/log/apache2/service_proxy_error.log
The following terminal command can provide you with additional information:
About transaction “failures”
Some of these logs might list transaction “failures” or retries. Most of these entries are expected and don’t indicate an issue. These logged events are conflicts between attempts to modify the underlying PostgreSQL database at the same time. These kinds of failures retry until they succeed.
You can identify transaction conflicts when you see any of these notes in your log files:
- Canceled on conflict out to pivot
- could not serialize access due to concurrent update
- @@@ Retry #X
- @@@ Retry X
Check the apspd CFPrefs file
Navigate to /Library/Preferences/ApplePushServiceProvider, select com.apple.apspd.plist, then choose File > Get Info. If the file is larger than 5KB, remove it and restart the apspd process with the following Terminal command:
Use verbose logging to find more info
More information on how to fix an issue is sometimes available if you increase the log level. To gather the information you need, reproduce the issue after you increase the logging level.
When you’re finished, revert to the original logging level. If you leave the logging level at a higher setting, it decreases the available space on your startup drive.
Turn on verbose logging
To increase the level of logging, use this Terminal command:
This automatically restarts Profile Manager Service.
Turn off verbose logging
To revert the logging level back to its original setting, use this Terminal command:
This automatically restarts Profile Manager Service.
I am running Ubuntu 16.04 on a Sony Vaio laptop, which features a keyboard backlight. I can enter this command into the terminal, putting a “0” in place of *value* to turn the backlight off, and a “2” to turn it on.
When I went to the settings app to create a custom keyboard shortcut and bind it to a simple ctrl keybinding, it doesn’t work.
1 Answer 1
You have three options. Pick the one of them which you like best:
Install the gksu package if not done already and use gksudo to get a GUI password entry dialog pop-up instead of being asked on the terminal console like sudo does (which is not present when you run it as keyboard shortcut and therefore does not work).
The command you need to bind to your shortcut would be this:
Use pkexec instead of sudo . It works similar to gksudo and should be preinstalled, but it only works for terminal commands, if you wanted to run a GUI application as root with it, it needed special configuration. But for your command it would be sufficient.
The command you need to bind to your shortcut would be this:
Write a short script to change the brightness and then configure sudo ‘s NOPASSWD option so that you can run it as root without getting asked for a password.
Here’s what you need to do in your specific case:
Write a script file that contains all commands necessary to achieve what you want which will then be run as root:
The script above takes an integer number greater than zero as command-line argument and writes it to the backlight control file after performing a basic sanity check. You could also modify the check to only allow the values 0 and 2 if you want, but I’ll leave that up to you.
Additionally, it checks as which user it is running and tries to elevate its privileges to root by executing itself with sudo if necessary. That means you can even omit the sudo when running it.
Save this script as /usr/local/bin/set-kbd-backlight (you may pick a different file name, but the directory should stay the same ; note that writing to this location requires sudo )
Make sure your script file has correct ownership and permission settings. You’re going to be able to run this script as root without password, so we must make sure it can be executed by everyone, but not be edited by non-root users!
Now you can configure sudo to allow running this script as root without password:
Edit your sudo configuration file /etc/sudoers by running the command below (not any other way!):
Now append the following line right before the line containing includedir /etc/sudoers.d near the end of the file, replacing USERNAME with the correct username which you will grant the passwordless execution as root:
Exit the visudo editor by pressing Ctrl + X , then Y (or whatever key represents “Yes” in your locale) and then Enter .
Verify it is working by first running sudo -k to revoke your cached password, just in case you entered it within the last 15 minutes in the current shell session. This is not needed for the script to work, it is just to test whether you configured NOPASSWD correctly.
Then run the commands below to turn the backlight on and off, without sudo . You should not be requested for your password.
Bind the commands ( set-kbd-backlight 0 to switch the light off, set-kbd-backlight 2 to switch it on) to the respective keyboard shortcuts.
I made a stupid mistake this morning by leaving a typo in the pluggable authentication modules file. Restarting the shell then revealed errors my typo caused. The solution was luckily not far away.
I accidentally ended up with the typo ∑∑wpam_tid.so instead of pam_tid.so in /etc/pam.d/sudo . The correct and new line ( auth sufficient pam_tid.so ) will trigger the Touch ID fingerprint prompt whenever sudo is being executed in the Terminal. This comes in handy if you work a lot with temporary sudo sessions.
This is how the /etc/pam.d/sudo file should look like:
After restarting the shell with exec $SHELL I executed a command that requires sudo and I got to see the error sudo error: unable to initialize PAM: No such file or directory . I checked the /etc/pam.d/sudo file and noticed the typo. I also noticed that macOS, apparently, revoked the write permissions for all users for this file and after the file content was updated once.
Luckily, there’s a relatively simple fix for the problem by running macOS in single-user mode (Terminal only, no UI) or the Recovery Mode and editing the /etc/pam.d/sudo file via Terminal.
If you have an older Mac, you can boot into single-user mode and directly into the command line mode of macOS by skipping the UI and everything:
- Start the Mac and press and hold down COMMAND + S keys until you see commands being executed in the Terminal.
- Continue with Terminal and restart .
On modern Macs, there’s no single-user mode available, so you have to do the following.
- Boot into recovery mode by pressing and holding the power button on your Mac until you see Loading startup options.
- Click Options, then Continue.
- If you’re asked for your administrator account password, enter it, and if everything goes well, you will land on the macOS Utilities screen.
- Go to Disk Utility and check if the Macintosh — Data partition was mounted; otherwise, mount the data partition by selecting the Macintosh — Data partition on the left and clicking the mount button on the top right corner. (The partition name can differ with your Mac setup!).
- Close Disk Utility and get back to macOS Utilities.
- Access the Terminal via the menu from the top of the screen.
- Continue with Terminal and restart .