8/16/2018

MacOS Tweaking 101

Is your beloved hunk of Cupertino silicon underperforming?  Wish your Mac had a little more zip?  Then you'll love these tips on squeezing the most performance out of your MacOS computer!

The Basics (Freshman Year Level Tasks)

Reboot

No seriously; to quote my favorite IT alter ego, "Have you tried turning it off and then no again?"  You'd be surprised how many nagging temporary issues go away after you restart.  And if you're under the impression closing your laptop lid and then reopening it *is* rebooting, no.  Save all your work, then click that fruit-shaped logo in the upper-left, and then click "Restart"
After your computer starts again, log in and see if the computer is back to its old vim and vigor.  If so, congrats!  You can probably go about your merry way.  If not (or if you want to learn some more tricks) keep reading.

Upgrade Your OS

Let's just get it out there: there are some users who cannot or should not upgrade to the latest version of MacOS.  But chances are those users are VERY few and far between.  If you hardware supports the latest MacOS, then unless you have a REALLY good reason not to, install the latest version!

Not only will you be getting the latest features, but you'll also be applying as many security fixes as possible.  The internet is a terrible place filled with savage thieves and crooks - don't make their job any easier by using an old OS with known security problems.

To check for updates, click the Apple logo in the task bar, then select "About This Mac" and click the Software Update button in the window that pops up.

Quit Unused Applications

If your system runs fine when you first start, but slows down as the day goes on, you may have fallen into the Windows-convert sinkhole.  I shudder to think of how many end-users I have supported who thought clicking the X in the title bar worked like they thought.  Alas, it only closes the active window while leaving the application running.  You want a full-bore QUIT with Command+Q here.  Die, application, DIE!

Tame Auto-Start Applications

What's better than quitting an unused application to free up resources?  Making sure applications you don't regularly use are not starting automatically.  Some applications like to set themselves to start every time you log in, often at the expense of performance for other applications.  It's a good idea to prune your list of items that start at login to only those you need and to review the list periodically to look for any surprise additions.

Open "System Preferences" application and select Users & Groups.  Click on your user account in the left pane, and then click the Login Items tab on the right.  To remove an application from auto-start, select it from the list and click the minus-sign button at the bottom of the page.

Uninstall Unused Applications

While you're thinking about which applications you actively use, consider uninstalling your unused applications.  It will not only free up disk space, but will eliminate potential performance issues caused by the application AND will remove any (heaven forbit!) security risks introduced by the application.

Getting Your Feet Wet (Sophomore Year Level Tasks)

Check Activity Monitor

The most common causes of poor performance is a computer that's not able to keep up with the demand of its currently running applications.  Specifically, the CPU, memory, or disk are being stretched beyond their limits.  It's not always obvious from the computer's GUI that this is happening, but MacOS's built-in tool Activity Monitor can shed some light on what's happening behind the scenes. 

Open Finder and navigate to Applications > Utilities and launch "Activity Monitor" (or just press the Command and Space keys to open Spotlight Search and type in Activity Monitor)

The monitor presents current system load, separated into tabs across the top for various components (CPU, Memory, etc)  You can click on each column header to sort by its values.  What you are looking for is an application that is using an greedy portion of any system resources.  Some applications are inherently resource intensive, so if you see something consuming a ton of CPU, memory, or any other component (  (¬_¬) I'm looking at you, Adobe) then you may have found your culprit.  If you're actively using that application, then you're stuck with the performance hit.  If not, consider quitting it to free up resources.

Pro Tip #1 - Web browsers use a surprising amount of memory, ESPECIALLY if you share my personal tech bad habit of having a billion tabs open at once.  See how Chrome is hammering my CPU?  Time to perform a little browser cleanup by closing my un-needed tabs.  And while we're at it, it's a good idea to uninstall any browser plugins you don't REALLY NEED, for security's sake as well as performance.


Pro Tip #2 - If you right click on the header bar, there are quite a few more columns that can be added for more information.

Pro Tip #3 - Use with caution, as the Command-Q from within the application's interface is a safer option.  But if you feel brave and want to kill a particularly resource-greedy application from within Activity Monitor, click on it in the list to highlight it then click the X button in the tool bar.

Free Up Disk Space

While rarely a direct cause of a performance issue, having an overly-stuff hard drive can have a slight impact on system responsiveness, especially if you have a spinning platter hard drive or a hybrid drive (aka: not SSD) - this is especially noticeable during search operations, which your operating system may be doing "behind your back" in order to index files.

If you've got a ton of unused files and data on your hard drive, consider making a backup and then removing it from your primary hard drive.  And while we're on the subject of backups - you are backing up your computer, right?  RIIIIIIIGHT?

Swimming Laps (Junior Year Level Tasks)

Tweak Finder's New Windows Setting

Finder's default settings show an aggressively large list of files for all new windows, which would call upon the index mentioned above often resulting in a noticeable lag.  Pretty much the first change I make on every MacOS system I use is to set the New Finder Windows Show in Preferences to something less insane (usually my user's home directory.)

Open Finder's preferences by clicking Finder in the taskbar and the Preferences (or by hitting the Command key & comma at the same time) and open the General tab.  Under the New Finder Windows Show... section, select your desired directory from the list (or select Other...) for more folder options.

Tweak Finder's Search Setting

In Finder Preferences, select the Advanced tab and check the "When Performing A Search" setting.  If this is set to "Search This Mac" then any search operation in Finder will crawl ALL the computer's files.  While this is thorough, it's also a resource hog.  Consider changing this setting to "Search The Current Folder."

Reset SMC

An Apple computer's SMC contains a variety of low-level tasks and settings for the hardware.  If your computer is behaving in weird ways, resetting the SMC to factory defaults can often cure phantom problems.  For more information on the SMC, see this Apple Support article (https://support.apple.com/en-us/HT201295)

To reset the SMC on a laptop with non-removable battery:

  • Power off the computer
  • Press the Shift, Control, Option keys & the Power button simultaneously
  • Hold down these keys for 10 seconds
  • Release all of the keys
  • Power on the computer

To Reset SMC On Non-laptop Computers

  • Power off the computer
  • Unplug the power cord
  • Wait 15 seconds
  • Plug the power cord back in
  • Wait 10 seconds
  • Turn on your computer

Reset NVRAM

Needing to reset the NVRAM is less common, but may be needed if your computer experiences odd behavior during boot such as taking a long time to determine which hard drive to boot from, etc.

For more information on NVRAM, see this Apple Support article (https://support.apple.com/en-us/HT204063)

To Reset NVRAM
  • Shut down your computer
  • Turn on your computer & immediately press these four keys together:
    • Option
    • Command
    • P
    • R
  • You can release the keys after about 20 seconds, during which your Mac might appear to restart.

On Mac computers that play a startup sound, you can release the keys after the second startup sound.   On Mac computers that have the Apple T2 chip, you can release the keys after the Apple logo appears and disappears for the second time. 

Using The High-Dive (Senior Year Level Tasks)

Run Disk First Aid

Every file in MacOS has permissions applied to it which controls how users, services, and applications are allowed to use the file.  Occasionally these permissions may become corrupt resulting in an application performing poorly if not crashing outright.  To repair these permissions, open Disk Utility, select your disk, and click the "First Aid" button.  Repeat this process for any additional disks you may have, then reboot.

Clean Out Cached Files

Your computer tries its hardest to get you information as fast as possible by creating caches which can sometimes grow quite large, and this may have an adverse impact on performance.

Note: deleting the cache files may mean that any corresponding application will attempt to recreate the cache again, resulting in a longer load/open time the next time you run the application.

To delete your user account's cache files, open Finder and select Go > Go to Folder, then type in ~/Library/Caches and press Enter.   Open each folder within the Caches directory and delete its contents.  Note:  It’s not recommended to remove the folders themselves, but only the files within.

Next, we will delete System caches. Repeat the process above, but using the path /Library/Caches (notice the lack of a ~ tilde sign this time.)

After you are done, empty your trash and reboot.

Seek Professional Help

If you are still having issues, all hope is not lost.  There are a variety of additional steps you can take, but they all vary based upon what your root cause is.

If you're feeling super adventurous, there are many additional tools (Onyx, TinkerTool, Cocktail, Secrets, MacPilot, CCleaner, etc) that can be used to clean and/or tweak other MacOS settings, but some can also *seriously* screw up your system if used incorrectly.

Your best bet is to seek professional help, either by visiting your closest Apple Store Genius Bar, finding a trusted local repair shop (look for one certified by Apple to diagnose and repair Apple hardware if at all possible) or to roll the dice with any of the glut of applications that promise a performance miracle for a small (or in some cases not-so-small) fee.

6/14/2018

Seeking to improve on last year's post on colorizing & customizing the Bash prompt, I wanted the settings to be easier to tweak.  As such, I now enter the settings below into a custom shell script which is executed with every bash invocation.

First, we create a set of variables that can set foreground colors, background colors, and perform various text formatting operations. Note: the script doesn't use all of these variables, but they're included for completeness.
# Set tput color aliases
FGBLACK=$(tput setaf 0)
FGRED=$(tput setaf 1)
FGGREEN=$(tput setaf 2)
FGYELLOW=$(tput setaf 3)
FGBLUE=$(tput setaf 4)
FGMAGENTA=$(tput setaf 5)
FGCYAN=$(tput setaf 6)
FGWHITE=$(tput setaf 7)
BGBLACK=$(tput setab 0)
BGRED=$(tput setab 1)
BGGREEN=$(tput setab 2)
BGYELLOW=$(tput setab 3)
BGBLUE=$(tput setab 4)
BGMAGENTA=$(tput setab 5)
BGCYAN=$(tput setab 6)
BGWHITE=$(tput setab 7)
TPBLINK=$(tput blink)
TPDIM=$(tput dim)
TPRMSO=$(tput rmso)
TPSO=$(tput smso)
TPBOLD=$(tput bold)
TPCLEAR=$(tput sgr0)

Next, we create a bash function called 'setprompt' that will check the current user's EUID and set a $FGUSER variable to set a custom prompt color for root and non-root users (in this example root user color is red, non-root user color is green.)  Then it will export the custom PS1 prompt using various color/formatting variables and bash's built-in special characters for date, time, username, hostname, current path, & prompt.  (Hint: run 'man bash' or visit this article to view the available special character options.)

setprompt()
{
    # Set root/user options
    if (( EUID == 0 )); then
        # Set foreground=red
        FGUSER=$(tput setaf 1)
    else
        # Set foreground=red
        FGUSER=$(tput setaf 2)
    fi

    export PS1="\[$TPBOLD$FGCYAN$BGBLACK\]\D{%Y/%m/%d}\[$TPCLEAR\] \[$TPBOLD$FGYELLOW$BGBLACK\]\@\[$TPCLEAR\] \[$TPBOLD$FGUSER$TPSO\]\u@\h:\[$TPRMSO\] \w\[$TPCLEAR\] \\$ "
}

Lastly, we invoke the 'setprompt' function.

setprompt

Create a shell script in the /etc/profile.d/ directory,  set execute permissions, and enjoy your beautiful new prompt!

Nerd minutia:  the functions above utilize the 'tput' format/color settings, which can illicit rage if your terminal does not properly support tput or renders the format/color incorrectly.  Feel free to use the hard-coded ASCII values in your variables instead - see here for a jumping-off point.

5/01/2018

Find Inactive Computers In Active Directory

Looking to identify stale/inactive computer accounts within Active Directory?  Using the 'Search-ADAccount' Powershell commandlet with the 'AccountInactive' & 'ComputersOnly' parameters will help you find just what you're looking for.

Import-Module ActiveDirectory
$DaysInactive = 90
$InactiveDate = (Get-Date).Adddays(-($DaysInactive))
$inactiveComputers = Search-ADAccount -AccountInactive -DateTime $InactiveDate -ComputersOnly

12/19/2017

Test LDAP Bind With Powershell


Ever wanted to test LDAP binding with Powershell?  It's possible with the code below.
$LdapServer = "ldap.server.fqdn"
$Connection=New-Object System.DirectoryServices.Protocols.LDAPConnection("$($LdapServer):636")
$Options=$Connection.SessionOptions;
$Options.ProtocolVersion = 3
$Options.SecureSocketLayer = $true
$Connection.AuthType = "Basic"
$Credential = Get-Credential -Message "Enter User Account To Test LDAP Bind"
$Connection.Credential = $credential
try{
    $Connection.Bind();
    Write-Host "Account '$($Credential.UserName)' bind using SSL successful." -ForegroundColor Green
    Write-Host "`nLDAP Options" -ForegroundColor Green
    Write-Host ($Options | Format-List | Out-String).Trim() -ForegroundColor Gray
    if($Options.SecureSocketLayer){
        Write-Host "`nLDAP SSL Information" -ForegroundColor Green
        Write-Host ($options.sslinformation | Format-List | Out-String).Trim() -ForegroundColor Gray
    }
}
catch{
    $_
}

7/12/2017

Query Windows Logons With Powershell

Want to quickly get a list of logon/logoff events for a Windows computer?  It's pretty easy with a quick PowerShell query!  The query below can either be run directly from PowerShell if you're looking for local computer logon/logoff events, or saved as a PS1 script and then pass the "-ComputerName" parameter.

4/23/2017

Musicbrainz Picard On Ubuntu

Music nerds love music.  Music nerds with OCD and a large MP3 collection love when those music files that are perfectly organized.  Luckily, the people behind the MusicBrainz database have also released a very good MP3 tagging tool called Picard.

While the Picard developers do provide a PPA for software installation, it currently officially supports versions up to Xenial Xerus (Ubuntu 16.04) and contains an older version of Picard.  To install the latest Picard on newer versions of Ubuntu, we can install from source.

Prerequisites

First, check which version of Python is installed - you will need 2.7 or higher, but not Python 3 (which doesn't work with Picard.)
python -V
Next, we'll install the Picard dependencies.
sudo aptitude install python-libdiscid python-pyqt5 python-qt4-dev python-mutagen build-essential gettext fpcalc libpicard-java med-cloud med-bio libpicard-java libpicard-java libhtsjdk-java ffmpeg
Download the latest version of Picard's source code from https://picard.musicbrainz.org/downloads/.  In this example, I have downloaded the TAR file for version 1.4.1.  Now, navigate to the directory containing the download and extract its contents.
tar zxvf picard-1.4.1.tar.gz

Installation 

Lastly, navigate into the newly created directory and run the setup/install script.
cd picard-release-1.4.1 && sudo python setup.py install

Links & Info

Picard Download: https://picard.musicbrainz.org/downloads/
Additional Picard Plugins: https://picard.musicbrainz.org/plugins/
Official Ubuntu Repo: https://launchpad.net/~musicbrainz-developers/+archive/ubuntu/stable
Manually Updating Cover Art: https://superuser.com/questions/918550/musicbrainz-picard-how-to-manually-set-a-cover

3/16/2017

Bash Customization - Colorizing Prompt

Spending extended periods of time with any tool usually makes me want to tweak it to fit my particular quirky desires, and the Linux terminal is no exception.  Having cut my teeth on "normal" distributions, I had grown accustomed to the bland and colorless user@hostname shell session and was perfectly happy, mainly because I didn't know what I was missing.  Until, that is, I stumbled upon one of Linux Mint's early releases that included a colorized bash prompt and a funny little quote (courtesy of fortunes.)

I spent countless hours searching forums for "terminal customization" tips, and pasted more than a few random settings into config files without knowing the impact.  And we won't mention the time I destroyed my system badly enough to require a rebuild.

And then I found the Bash RC Generator site (http://bashrcgenerator.com) which provides a WYSIWYG editor for building custom terminal prompts.  Simply drag the available elements into the "your selection" sandbox and a preview of the changes - double clicking on an element in the sandbox allows you to set foreground and background color values!  Once you have found a customization you like, simple copy the code and add it to your .bashrc file - the site even includes how-to steps for updating your config files and the references for bash customization.

By adding the code snippet below, the terminal prompt on my Ubuntu Zesty testbox went from this:
...to this:

Custom PS1 code added to .bashrc config file
export PS1="[\[$(tput sgr0)\]\[\033[38;5;10m\]\d\[$(tput sgr0)\]\[\033[38;5;15m\] \[$(tput sgr0)\]\[\033[38;5;10m\]-\[$(tput sgr0)\]\[\033[38;5;15m\] \[$(tput sgr0)\]\[\033[38;5;10m\]\t\[$(tput sgr0)\]\[\033[38;5;15m\]] \[$(tput sgr0)\]\[\033[38;5;14m\]\u@\H\[$(tput sgr0)\]\[\033[38;5;11m\]:\W\[$(tput sgr0)\]\[\033[38;5;15m\] \\$\[$(tput sgr0)\]"
Note, most of that code is used for the colorization of the variables. If you'd prefer the same text uncolored, the code block would be this:
export PS1="[\d - \T] \u@\H:\W \\$\[$(tput sgr0)\]"

1/18/2017

Preparing CentOS/RHEL For Clone

When deploying CentOS/RHEL virtual machines for a clone, you will want to remove host-specific information from the clone source - the commands below streamline this process by cleaning out the SSH host, interface, & history information.
touch /.unconfigured
rm -f /etc/ssh/ssh_host_*
ifdown <interfacename>
sed -i '/^HWADDR=.*$/d' /etc/sysconfig/network-scripts/ifcfg-<interfacename>
ifup <interfacename>
rm -f /etc/udev/rules.d/70-persistent-net.rules
history -c
shutdown -h now
Note: to find your interface name(s), run the ifconfig command; if the system does not have it installed, determine which package includes the command via yum provides ifconfig (in this case, we would install net-tools.)

8/03/2016

My Basic Ubuntu Post-Install Tasks

A large part of the beauty of Linux is the freedom to customize the desktop to your liking.  While each distribution does its best to tweak the experience to suit its users, there are always (at least) a few things that I change on almost every installation.  This is a quick list of the common changes I perform to make myself at home.

Note: I use Ubuntu and Ubuntu-based distributions most of the time, so for the most part the directions below will include software included in Ubuntu software repositories or directions for how to install/configure using Ubuntu commands and tools.  Also, these directions are for Gnome or Gnome-based desktop environments.  I'll add a KDE-based article (at some point...)

Daily Workflow

First, we'll install some basic tools I use every day:  aptitude (a command-line package manager alternative to apt-get,) vim (command-line text editor on steroids,) curl (a command-line downloading tool,) build-essential (a meta-package of many tools required to compile software from source,) and some of my favorite monitoring tools (htop/atop/iotop.)
sudo apt-get install aptitude vim curl build-essential htop atop iotop

Internet & Graphics

Next we'll add some internet, graphics, and audio/video tools: Chromium (an internet browser similar to Google Chrome,) megatools (command-line tools to interact with the Mega.nz file-hosting service,) VLC (a stellar cross-platform media player,) and some extra media plugins.
sudo aptitude install chromium-browser megatools vlc ffmpeg libav-tools rtmpdump
If you'd prefer the "real" Google Chrome instead of the open-source Chromium browser installed above, run these commands:
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo gdebi google-chrome-stable_current_amd64.deb
If you want to download videos from the world's most popular site, download Youtube-DL (official site) with curl and mark the script as executable.
sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl
sudo chmod a+rx /usr/local/bin/youtube-dl
Tired of the built-in wallpapers included with your distribution?  Then Peter Levi's Variety Wallpaper Changer is a must-have.  It grabs high-quality wallpapers from a variety (see what I did there?) of online sources, supports adding your own sources including Flickr keywords, can display a customized embeded random quote and/or clock, and you can create a free account to sync your favorites between computers.  Simply add the PPA, then update your sources and install.
sudo add-apt-repository ppa:peterlevi/ppa -y
sudo apt-get update && sudo apt-get install variety variety-slideshow

Faenza & Faience Icon Themes

One of the easiest ways to change the appearance of your Linux workstation is to change the icon themes.  My current favorite icon themes are Faenza & Faience.  Ubuntu includes Faenza in their default repositories, so installing is as simple as this:
sudo aptitude install faenza-icon-theme
However, Faience needs to be downloaded and installed separately.  I have created an archive of the theme at Mega.nz, so we'll use the megatools downloaded above to grab it, then unzip and install it using these commands:
megadl 'https://mega.co.nz/#!XJ5m0TgC!xYfhZZZdr1uEuzCQ-sBZTZE55Yeu1hN4_nr-3sXdWmE' --path=$HOME/Downloads
unzip ~/Downloads/faience-icon-theme_0.5.zip -d ~/Downloads/faience-icon-theme
sudo ~/Downloads/faience-icon-theme/INSTALL

Numix Themes

Another great visual update is the Numix Project, which includes not just an icon theme, but also a Gnome GTK theme and a series of wallpapers.  The project includes a PPA which makes installing and updating the various Numix software packages super easy.
sudo add-apt-repository ppa:numix/ppa -y
sudo aptitude update && sudo aptitude install numix-?
After installing the themes, use your distribution's theme-picking tool to select your new favorite and enjoy!

Games

The Gnome project includes a variety of simple yet fun games that can be used to burn a few minutes of your free time.  Alas, few distributions include them by default.  Just install the "Gnome-Games" meta-package and then enjoy the nostalgia of 80s arcades and the best OS Redmond offered in 1995.
sudo aptitude install gnome-games

4/22/2016

Setting Screen Resolution In Linux

While Linux distros these days usually provide a graphical tool to manage screen resolution, there are times where the settings need to be set manually.  This can occur if the GUI tool fails to apply settings or cannot probe the monitor's resolution, if you want to use a non-standard resolution, or if you wanted to set the resolution via a script.

I often have to resort to this method when launching Ubuntu in VMware Workstation because the virtual machine library list on the left of my panel results in a funky max resolution for my VMs of 1712x935.  The example below will use this resolution.

To set the resolution, we'll be using the X11 tools xrandr and cvt.  First, we'll need to determine the name for our display, using xrandr's query flag.
xrandr -q
Output of xrandr's query, showing the display (monitor) name.


We will also need to get the modeline settings for our desired resolution and refresh rate.  In the command below, the numbers are the screen's desired horizontal pixel count, vertical pixel count, and refresh rate.  Finding my preferred resolution was the lengthiest portion of this entire process for me, mainly due to my OCD requiring multiple tests to find the "perfect" setting.  Do not get discouraged, trial and error is your friend on this step.
cvt 1712 935 60
cvt 1712 935 60
Copy the Modeline value starting at the first double quote, you'll need this for the next step.

Make note of the output from the cvt command above.  Copy the modeline values, starting with the double quoted resolution/refresh rate to the end of the line, and use it to create a newmode in xrandr.
xrandr --newmode "1712x935_60.00" 132.00 1712 1816 1992 2272 935 938 948 971 -hsync +vsync
Lastly, add the newly created mode to the screen using the name from the first command, then set this screen to use this same output mode.
xrandr --addmode Virtual1 1712x935_60.00
xrandr --output Virtual1 --mode 1712x935_60.00


4/21/2016

UpdateDB & Locate On Windows

Do you love the "locate" tool on Linux and wish your Windows box had the same capabilities?  If so, check out Invoke-Locate, a PowerShell script written by Chrissy LeMaire.  It builds a SQLlite database (can use a MSSQL DB if you prefer) of files on all local disks, can index mounted drives (careful with that option in a corporate environment), and includes an option to "install" which creates a scheduled task to update the DB every 6 hours.



I would recommend the install option if you can spare the CPU cycles, as manually running the updatedb command takes a few minutes; but subsequent searching using the locate command are lightning quick (far faster than Windows' built-in search even with indexing enabled.)  As always, check the help and example sections of the script for details and a slew of options.

Links:
Chrissy's blog entry announcing the script.
ScriptCenter download page.

MacOS Tweaking 101

Is your beloved hunk of Cupertino silicon underperforming?  Wish your Mac had a little more zip?  Then you'll love these tips on squeez...