Tuesday, 27 August 2013

OSX Guest account "Shakes" and won't log on after power failure

I have been borrowing a friends mac lately only for a couple of weeks while they are away. They have set up the guest account for me to log into. This is a great idea, it allows me to pretty much do what I like without any risk of damaging the computer (or so Apple will have you think). This assumption is almost correct, but as anyone with a little unix knowledge could tell you, "if you have physical access to the console and are able to reboot it, you can boot into single user mode". This means you can get root access :)

The problem is that this is a iMac, and there is a design flaw with it. The power cable goes into the monitor, this is the only power cable for the whole thing so if it comes out, your computer dies. Now Apple saw fit to put a highly reflective display on this thing so it needs constant adjustment to stop reflections, this means the power cable can work itself loose. Normally this might not be catastrophic since you could just plug back in and boot it up. Sure you might loose some work but since its an apple its unlikely your doing anything important. (Yes I am inferring that if you are a mac user you are probably just playing Facebook games or some sort or art, and yes thats not really important).

Now, rant over, if you are logged in as Guest when this power failure happens you will not be allowed to log back in. You will be faced with the login box, with the guest account, but instead of logging in you get an INFURIATING shaking box with no error message. So what does this mean? Who bloddy knows, the result though is you can't use the computer.

Where to now? Well Apple are no help here, so after a LOT of googleing I found a series of different blog posts that sort of related that I could string together into a solution. Here goes...

  1. Boot into single user mode: Reboot the mac and hold cmd+s you will end up at a terminal prompt as the root user... sort of. 
  2. Type:
    fsck -fy
    mount -uw /
    This will mount the root writable and give you root access to the machine.
  3. Type:
    passwd root  Enter a new root password.
  4. Type:
    dsenableroot -u root
    Enter the root password you just set three times and the root account will be enabled
  5. Type exit to boot up normally
  6. Log in as the root user by clicking other and entering root as the username and the password you set.
  7. Open System Preferences > Accounts  and disable the Guest account by deselecting both check boxes. Close the preferences window.
  8. This alone will not actually disable the account so open a terminal and enter:
    dscl . delete /Users/Guest
  9. Now go back to Accounts and re-enable the Guest user.
  10. Log out of the root account and you should be able to log in as guest now.
  11. OPTIONAL:



  12. If you don't want anyone to know you enabled the root account, you will want to disable it. Log on as root.
  13. Go back to Accounts > click Login Options
  14. Click the Join box next to Network Account Server
  15. Click Open Directory Utility
  16. Choose Edit(top menu) > Disable Root User

    So thanks Apple, that was a right pain in the arse. Fix this bug with the guest account please.

Sunday, 25 August 2013

VMware consolidating disks fails with file lock error

Recently I came across an issue where I had a VM with lots of snapshot and delta disks but when you look in the snapshot manager there are no snapshots.

There is a nice little message in the vSphere client pointing to the issue.

When I attempted to consolidate the disks I got a horrible error, one of those VMware mystery errors.

"Unable to access file since its locked"

Super! Thanks VMware.

A bit of googleing around led me to a stack of articles talking about backup VM's having the disk mounted causing a file lock. I knew this was not the problem since this is a lab environment and there is no snapshot backup tool.

It did lead me to look on the array for file locks though. This is on a NetApp array so I ssh'd in and had a poke around.  I checked for locks on all of the files in the VM's directory and no matter what I entered I kept getting 'No Locks'


OK, so its not an array level file lock, what next?

I turned on SSH on a host that has access to the files, CD'd to the VMs directory to have a look around. The first thing I noticed that struck me as odd was 2 files starting with .lck-.

Since the VM was powered off these should not be there. So I rm'd both files and tried the consolidate again. HUZZAH!! its working.



Friday, 2 August 2013

PowerShell one liners for Active Directory

Just like my PowerCLI one liners post, I am hoping that this one will improve and expand over time.

Get the user "Luke"
Get-ADUser -Filter {SamAccountName -Like 'Luke'}

Get all users with the Surname "Jones"
Get-ADUser -Filter {Surname -like 'Jones'}


Get all disabled users
Get-ADUser -Filter {Enabled -eq 'False'}

Enable a user account
Set-ADUser -Enabled $True -Identity "Luke"

Get members of a group
Get-ADGroupMember esxadmin | Select-Object SamAccountName, Name


Thursday, 1 August 2013

PowerCLI one liners for VMware

Hopefully this will be a living post that I will update on a regular basis as I come across more little things I want to do.

Get a list of all VM names fast
Get-View -ViewType VirtualMachine -Property Name | Select Name

Get a list of all Host names fast
Get-View -ViewType HostSystem -Property Name | Select Name

Get a list of all VM's and their IP address (only works for powered on VM's)
Get-View -ViewType VirtualMachine -Property Name, Guest.IpAddress | Foreach-Object {Add-Member -InputObject $_ -MemberType NoteProperty -Name IpAddress -Value $($_.Guest.IpAddress) -Pa
ssThru} | Select Name, IpAddress


Get a list of all snapshots that are more than 2 days old and display its age in days
Get-Snapshot -VM $(Get-View -ViewType VirtualMachine -Property Name,Config.Template -Filter @{"Config.Template"="False"} | foreach { $_.name }) | Where-Object {$_.Created -lt $(Get-Date).AddDays(-2)} | ForEach-Object {Add-Member -MemberType NoteProperty -InputObject $_ -PassThru -Name Age -Value $((Get-Date) - ($_.Created)).Days} | Select-Object Name, Description, Created, Age


List any VM's that have CD drives attached (might stop vMotion working)
Get-Vm | Foreach-Object {$CD = Get-CdDrive -Vm $_; If ($CD.IsoPath -or $CD.HostDevice){$_ | Select-Object Name}}


Detach CD drives from all VM's
Get-Vm | Foreach-Object {$CD = Get-CdDrive -Vm $_; If ($CD.IsoPath -or $CD.HostDevice){$Null = Set-CdDrive -CD $CD -NoMedia -Confirm:$False}}


Turn on SSH for all hosts
Get-VMHost | Foreach-Object {  Start-VMHostService -Confirm:$False -HostService ($_ | Get-VMHostService | Where { $_.Key -eq "TSM-SSH"} )}

Turn off SSH for all hosts
Get-VMHost | Foreach-Object {  Stop-VMHostService -Confirm:$False -HostService ($_ | Get-VMHostService | Where { $_.Key -eq "TSM-SSH"} )}


Get a list of all VMs (including templates) with their vmx location, current host and folder and export to XML

get-view -viewtype virtualmachine -property name, config.files.vmpathname, parent, Runtime.Host | select name, @{n="vmxFilePath"; e={$_.config.files.vmpathname}}, parent, @{n="host"; e={$_.runtime.host}} | Export-Clixml -Path ./vms.xml


Import the list and add the VMs to inventory

Import-Clixml .\vms.xml | foreach { New-VM -VMFilePath $_.vmxfilepath -VMHost (Get-VIObjectByVIView $_.host.toString()) -Location (Get-VIObjectByVIView $_.parent.toString()) -RunAsync}


Get a list of all VMs and their configured OS 

Get-View -ViewType virtualmachine -property name, config.guestid, config.guestFullName | select name, @{N='guestid'; E={$_.config.guestid}}, @{N='guestFullName'; E={$_.config.guestFullName}} | sort guestid | Export-Csv -NoTypeInformation -Path ./vmguests.csv

Get report about host CPU, Network and Storage usage (real-time stats)
get-vmhost | foreach { 
$CPU = Get-Stat -Entity $_ -Stat cpu.usagemhz.average -Realtime | measure -Average -Maximum value
$net = get-stat -Entity $_ -Realtime -stat net.usage.average | where {$_.instance -eq ""} | measure -Average -Maximum value
$storage = get-stat -Entity $_  -stat storageAdapter.write.average -realtime | measure -average -maximum value
$_ | select @{N='Cluster';E={$_.parent.name}}, name, @{N='CPU MHz Usage Average';E={$CPU.average}}, @{N='CPU MHz Usage Average Max';E={$CPU.Maximum}}, @{N='Net KBps Usage Average';E={$Net.average}}, @{N='Net KBps Usage Average Max';E={$Net.Maximum}}, @{N='Storage KBps Usage Average';E={$CPU.average}}, @{N='Storage KBps Usage Average Max';E={$CPU.Maximum}}
} | Export-Csv -NoTypeInformation -Path ./Host_Usage.csv

Upload and download files over SSH

This is fairly easy to do if you are used to unix CLI and you are using unix/OSX. For windows as always there is a little more to it.

OSX/Unix

Open up a terminal. For mac users press cmd+space then type "terminal" hit enter, in Ubuntu press ctrl+alt+t, for any other unix I assume you know how to do this.

Navigate to the file that you want to upload or the location that you want to download the file to using the cd command. eg. cd ~ (this will take you to your home folder)

Now you need to use the scp command to copy your files. it is used like this:
scp <file to copy> <destination> 

If you are using a non standard port (not port 22) for SSH they you will need to specify the port with the -P flag. If you want to copy a folder then you need to specify the -r (recursive copy) flag. 
scp -P 443 -r <file to copy> <destination> 

Your remote file path needs to specify your username, server and file path. For example if I wanted to copy example.txt from my home folder to my home folder on my SSH server I would type:
scp -P 443 /home/luke/example.txt  luke@icitd.com:/home/luke/
If I wanted to copy the same file from my SSH server to my local machine I could type:
scp -P 443 luke@icitd.com:/home/luke/example.txt  /home/luke/txt/

If I wanted to copy the whole txt folder from my home directory to my SSH server I would type:
scp -P 443 -r /home/luke/txt  luke@icitd.com:/home/luke/
remember the -r to recurse the directory!

There are GUI based tools available for OSX and linux if you like, examples are:
Ubuntu - Search the app store, or Filezilla is available

Large files

If you want to copy a large file, a lot of files, or you regularly want to back up a directory then rsync is the tool for you. It is used in a similar way to scp but it only copies the changes to files so if you have a large amount of data that doesn't change much this can save you a lot of time.

Windows

WinSCP is a GUI file transfer program for windows, it has a midnight commander type interface or a standard interface. I find the midnight commander interface to be much more useful.

Download and install WinSCP, open WinSCP.

You can use either SFTP or SCP for the file protocol, I have not noticed any major differences but SFTP is supposed to be the better protocol. 
In the Host name box enter the IP or hostname of your SSH server, enter the port number you are using (default is 22)
Enter your user name and password, click Login.

Agree to saving the fingerprint when prompted, this will open up the file navigator. From here you can drag and drop files from your client to server or server to client. Your local machines files are on the left and the remote machine is on the right.

Socks proxy over SSH OR Safely browse the Internet

This one comes in handy for me in three different scenarios. The first is when I am travelling and relying on free internet hotspots (eg. airports, Mc Donalds, hotels) and I want to safely do banking. Another is when I want to look at a website that is blocked by the network I am attached to. Finally, so that I can look like I am at home when I am not to a website that uses location data based on an IP address.


What you will NEED

  1. A working SSH server that you have remote access to. If you don't then have a look here.
  2. Firefox (you can do this without firefox if you install third party add-ons or are not using windows)

How to do it

Mac

Open a SSH session and create a dynamic port forward using the -D flag, you can also add the -C flag to compress the session, this probably wont help much since most web servers already compress the response. eg. ssh luke@icitd.com -C -D 6666

Windows

Open Putty, enter your server details eg. ssh luke@icitd.com
Click SSH, Check 'Enable compression' 

Expand SSH and click Tunnels
Enter 6666 in the source port and select 'Dynamic'
Click Add
(Optional) Click back on 'Session', enter a name for the session and click save

Click Open, Click Yes to accept the key if this is the first time you are connecting
Enter your password (there will be no feedback when typing the password)
You should get a black screen that says <username>@<hostmane>:~$ 

Install Firefox, start it up then go to the settings page. These example screen shots are for windows but the process is very similar for mac or linux.

  1. Click on the firefox menu on the top left, click options, click options
  2. This will open the Options dialogue box
    click the advanced icon at the top, click the network tab below the icons, click the settings box under Connection.
  3. In the Connection settings box click Manual proxy Configuration, in the SOCKS host box type localhost, in the port box beside type a high order port (eg. 6666), click OK to close the Connections settings box, then again to close the options box.

  4. OPTIONAL: Firefox will still do the DNS lookups on your local network even though it then tunnels the web page over the SSH session. If you are paranoid and don't want your DNS lookups known then you can tell Firefox to do remote DNS lookups.
    1. In Firefox, enter about:config in the url bar, click I'll be careful...

    2. In the search bar type socks, double click network.proxy.socks_remote_dns to change the value to true.
      here
    3. Now Firefox will do remote DNS queries.
Thats all there is to it, now all your web traffic is encrypted between you and your home network. To external sites the traffic will seem to come from your home IP address. 
Happy browsing!

Mount NTFS as read/write in OSX Mountain Lion

I hate Apple.  Okay, I don't wholly hate them, but I hate how otherwise simple tasks in Linux or Windows become pains in the neck on OSX.  I also hate how Apple deliberately and unabashedly devote their development and UI design to ensure that you, the consumer, are locked into the Apple ecosystem forever and ever, amen.

Case in point? Something as simple as mounting NTFS devices as read/write.  Apple should be absolutely and utterly ashamed that OSX didn't support this natively until only recently (OSX Mountain Lion), as basically any other respectable OS (Linux, BSD, Unix, Windows) could do so back in the year 2000.  How Apple made it this far without being publicly humiliated for this simple lack of functionality, I don't know.  But the good news is although its not supported via the GUI, we can now do so via a simple mount command.

First, eject the NTFS disk(s) that appear in finder by clicking the eject button next to the partition/disk:



Then open a terminal windows and run the following command:

sudo mount -t ntfs -o force,rw,nobrowse /dev/disk3s2 /media

Where /dev/disk3s2 is the disk partition you're trying to mount and /media is the mount location.  I just created /media using sudo mkdir /media since this directory does not exist inherently on OSX.  Note that the force command and nobrowse commands are the key differentiators to mounting an NTFS disk in Linux.



And then you're laughing.  A super simple command, but it can save hours of headache.

More to come later for OSX tips to allow you to actually use your Apple computer as a computer, and not as an Apple revenue generation machine.