Binary Nature where the analog and digital bits of nature connect

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Saturday, 21 August 2010

Enable sudo for RHEL and CentOS

Posted on 20:09 by Unknown
Sudo is an arguably safer alternative to logging in (or using the su command) to the root account. Sudo allows you to partition and delegate superuser commands (functions) without giving a user total "root" power on the system. Here are a few other advantages:
  • Privileged commands are logged. It is a simple way to audit who did what at what point in time.
  • It is more efficient to use sudo over su, or to log in as root, in reference to keystrokes.
  • You don't have to change the root password when an administrator has his root functions revoked, leaves the company, changes roles, etc. The change part is easy, but coordinating the new password with every other administrator can be a hassle.

# Is sudo installed?
Login with the root user.

Let's first determine if the sudo package is installed.

# rpm -q sudo

If the package is not installed, we can retrieve/install it with the following command:
# yum install sudo

# Create a normal user
Create the user and add to the wheel group. The wheel group is usually predefined as the container for administrator accounts.
# useradd -G wheel -c "Test User" testNew

Create a password for the user.
# passwd testNew
Changing password for user testNew.
New UNIX password: P@$$w0rd
Retype new UNIX password: P@$$w0rd
passwd: all authentication tokens updated successfully.

# Or modify an existing user
Add an existing user (the user testMod in my example) to the wheel group.
# usermod -aG wheel testMod

# Modify the sudoers file
Use the visudo command to safely modify the sudoers file.
# visudo

Search for the Allows people in group wheel to run all commands directive and uncomment the second line to enable the wheel group to run all commands.

## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
Save the file.

# Test with a privileged command (logged in as a normal user)
We will first attempt to run the visudo command with our normal user account. As expected, the operation will fail.
$ /usr/sbin/visudo
visudo: /etc/sudoers: Permission denied

Now we will run the command within the context of sudo to temporarily elevate the privileges of our normal user.
$ sudo -i visudo
[sudo] password for test: P@$$w0rd

# Verify the command is logged
Check the secure log to verify the event is recorded.
$ sudo grep visudo /var/log/secure
...
Aug 21 20:01:20 centos sudo: test : TTY=pts/0 ; PWD=/home/test ; USER=root ; COMMAND=/bin/bash -c visudo
...

This is just a single use case of how to implement sudo. I encourage you to check out the man pages and other documentation to see how you can tailor it to your specific environment.

Read More
Posted in Linux | No comments

Sunday, 11 July 2010

Install and configure GNS3 with TunTap on the Mac

Posted on 15:08 by Unknown
[10/30/2013: Post has been updated to reflect configuration with GNS3 v0.8.6 and Mac OS X 10.9 (Mavericks)]

A virtual network has many great uses. It can be indispensable when testing device configurations before applying to your production network, and it also can be beneficial for training purposes when studying for the Cisco and Juniper certification exams.

GNS3 is a graphical network simulator. It's an impressive tool that ties together the Dynamips, VirtualBox, and QEMU hypervisors abstracted to the user as a modular and flexible graphical user interface for network design and testing.
Download the Software
You can grab the components needed for this tutorial from their respective websites:
  • GNS3
  • TunTap
  • Cisco IOS image

Install the Software
# TunTap
The TunTap package will provide us with a collection of virtual network interfaces for the Mac operating system. The TAP drivers allow us to bridge our GNS3 virtual network with the physical Mac host. Unpack and install the downloaded TunTap package.

Verify the TunTap package installed successfully. Run this command from Terminal.app:
$ ls -l /dev | grep tap

You should see the device files listed (tap0 - tap15).

crw-rw---- 1 root wheel 33, 0 Oct 5 07:27 tap0
crw-rw---- 1 root wheel 33, 1 Oct 5 07:27 tap1
crw-rw---- 1 root wheel 33, 10 Oct 5 07:27 tap10
crw-rw---- 1 root wheel 33, 11 Oct 5 07:27 tap11
crw-rw---- 1 root wheel 33, 12 Oct 5 07:27 tap12
crw-rw---- 1 root wheel 33, 13 Oct 5 07:27 tap13
crw-rw---- 1 root wheel 33, 14 Oct 5 07:27 tap14
crw-rw---- 1 root wheel 33, 15 Oct 5 07:27 tap15
crw-rw---- 1 root wheel 33, 2 Oct 5 07:27 tap2
crw-rw---- 1 root wheel 33, 3 Oct 5 07:27 tap3
crw-rw---- 1 root wheel 33, 4 Oct 5 07:27 tap4
crw-rw---- 1 root wheel 33, 5 Oct 5 07:27 tap5
crw-rw---- 1 root wheel 33, 6 Oct 5 07:27 tap6
crw-rw---- 1 root wheel 33, 7 Oct 5 07:27 tap7
crw-rw---- 1 root wheel 33, 8 Oct 5 07:27 tap8
crw-rw---- 1 root wheel 33, 9 Oct 5 07:27 tap9

A reboot of the computer may be required if the virtual devices are not listed in the output.

# GNS3
Open the GNS3 DMG image file, and move the GNS3.app to the Applications folder.

We also need to change the ownership and permissions for the Dynamips binary file(s). The Dynamips process will need to run with elevated privileges (root) to "attach" the TAP devices.

Change the ownership of the Dynamips binary file(s) to the root user. Run this command from Terminal.app:
$ sudo chown root /Applications/GNS3.app/Contents/Resources/dynamips*.bin

Modify the setuid attribute for the Dynamips binary file(s). Run this command from Terminal.app:
$ sudo chmod 4755 /Applications/GNS3.app/Contents/Resources/dynamips*.bin

Verify the new configuration. Run this command from Terminal.app:

$ ls -oh /Applications/GNS3.app/Contents/Resources/dynamips*.bin
-rwsr-xr-x@ 1 root 1.0M Sep 9 21:01 /Applications/GNS3.app/Contents/Resources/dynamips-0.2.10-OSX.intel64.bin
-rwsr-xr-x@ 1 root 958K Sep 9 21:01 /Applications/GNS3.app/Contents/Resources/dynamips-0.2.8-RC3-community-OSX.intel64.bin

Note: Recent versions of GNS3 include multiple versions of the Dynamips binary file.

GNS3 Base Configuration
# Create the GNS3 Folders
Create the main GNS3 folder as well as the GNS3/Projects, GNS3/Images, and GNS3/Tmp subfolders in your Documents folder. Feel free to use the Finder, but I will use the command line method in my example.

Create the main GNS3 folder and subfolders. Run this command from Terminal.app:
$ mkdir -p $HOME/Documents/GNS3/{Projects,Images,Tmp}
# Cisco IOS Image File
Let's now unpack the image file and move it to the Images folder. I will be using the c3725-adventerprisek9-mz.124-15.T10.bin image file in my example. I will first navigate to the directory where I have it saved (/Users/marc/Downloads/Labs), so I would run this command from Terminal.app:

$ cd $HOME/Downloads/Labs

Now uncompress the IOS image. Run this command from Terminal.app:

$ unzip c3725-adventerprisek9-mz.124-15.T10.bin
Archive: c3725-adventerprisek9-mz.124-15.T10.bin
warning [c3725-adventerprisek9-mz.124-15.T10.bin]: 28328 extra bytes at beginning or within zipfile
(attempting to process anyway)
inflating: C3725-AD.BIN
You can safely ignore the warning message. It should have uncompressed successfully.

From the output, you will notice the unpacked IOS image filename is C3725-AD.BIN. Rename it back to original filename substituting the extension with .image (e.g. c3725-adventerprisek9-mz.124-15.T10.bin -> c3725-adventerprisek9-mz.124-15.T10.image). Run this command from Terminal.app:
$ mv C3725-AD.BIN c3725-adventerprisek9-mz.124-15.T10.image

Then move the c3725-adventerprisek9-mz.124-15.T10.image file to the GNS3 Images folder. Run this command from Terminal.app:
$ mv c3725-adventerprisek9-mz.124-15.T10.image $HOME/Documents/GNS3/Images

We will now map the GNS3 settings with the new folders we just created.

# GNS3 Preferences (General)
  • Open the GNS3 Preferences. [Command-, (Command key plus the comma key)]
  • Select the General node on the left.
  • Select the General Settings tab.
  • Set the directory path for both Projects and OS images.
  • Click the Apply button to save the settings.

# GNS3 Preferences (Dynamips)
  • Select the Dynamips node on the left.
  • Select the Dynamips tab.
  • Set the directory path for both Executable path to Dynamips and Working directory for Dynamips.

What value should we enter in the Executable path to Dynamips field? As stated previously, GNS3 now includes multiple versions of the Dynamips binary file. Run the following command from Terminal.app to see our options:

$ ls /Applications/GNS3.app/Contents/Resources/dynamips*.bin
/Applications/GNS3.app/Contents/Resources/dynamips-0.2.10-OSX.intel64.bin
/Applications/GNS3.app/Contents/Resources/dynamips-0.2.8-RC3-community-OSX.intel64.bin

I decide to use the latest version, so I would enter the value /Applications/GNS3.app/Contents/Resources/dynamips-0.2.10-OSX.intel64.bin in the Executable path to Dynamips field.
  • Click the Apply button to save the settings.
  • Then click the Test Settings button to verify the configuration is valid.
  • Click the OK button to close the window.

# IOS images and hypervisors
  • Open the IOS images and hypervisors settings window. [Shift-Command-I]
  • Select the IOS Images tab.
  • Set the directory path for the Image file.
  • Verify the Platform and Model fields coincide with the Cisco IOS image file.
  • Verify/Set the Default RAM value for the image.
  • Click the Auto calculation button to start the operation to retrieve the IDLE PC value for the image.
  • Click the Close button in the foreground window after the message Working Idle PC value found. is displayed.
  • Click the Save button.
  • Then click the Close button to close the window.

Basic Lab Setup
Our sample lab will consist of a Router, an Ethernet Switch, and a Cloud node type. Drag the objects from the Node Types dock onto the Workspace window. It should look similar to this once we get everything configured:
We need to configure the Cloud object before we wire it to the switch. The object will be using a TAP virtual network interface.
  1. Right-click the Cloud object.
  2. Select Configure.
  3. Select the subnode (ex. C1).
  4. Select NIO TAP.
  5. Enter /dev/tap0 into the top field.
  6. Select the Add button to add the interface.
  7. Select the Apply button to save the setting.
  8. Then select the OK button to close the window.

Connect all objects with Fast Ethernet links.
  • Start the router. [Right-click (or Control-click) -> Start] on the router object.
  • Find the console port for the virtual router by entering the list command in the Dynagen management console.

Emulate a console connection to the router by establishing a telnet session. Run this command from Terminal.app:
$ telnet localhost 2103

Let the router load until it presents the prompt. Take note you may need to press the return key multiple times to "capture" the prompt in the terminal window.

# Save the Project
I prefer to save the GNS3 project at this point before I continue with the rest of the configuration.
File -> Save project as...

# Configure IOS for the Router
Set the IP configuration for the network interface that is connected to the switch.

R1# conf t
R1(config)# int fa0/0
R1(config-if)# ip address 10.11.1.1 255.255.255.0
R1(config-if)# no shut
R1(config-if)# end

Let's verify the configuration of the interfaces by executing the following commands:

R1# sh run int fa0/0
Building configuration...

Current configuration : 94 bytes
!
interface FastEthernet0/0
ip address 10.11.1.1 255.255.255.0
duplex auto
speed auto
end


R1# sh ip int br
Interface IP-Address OK? Method Status Protocol
FastEthernet0/0 10.11.1.1 YES manual up up
FastEthernet0/1 unassigned YES unset administratively down down

Copy the current running configuration to the startup configuration in the "virtual" NVRAM, so we don't have to repeat the preceding steps the next time we start this lab in GNS3.

R1# copy run start
Destination filename [startup-config]? <enter>
Building configuration...
[OK]

# TAP Interface
By linking the Cloud with the switch, it should have brought up the TAP network interface on the physical Mac host. Let's check. Run the following command from Terminal.app:

$ ifconfig tap0
tap0: flags=8842<BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether ce:d1:be:72:33:67
open (pid 34415)

Set the IP configuration for the tap0 interface. The IP address will need to be in the same subnet as the one we configured for the network interface on the router. You will be requested for your user account password because modifying the logical network configuration for a network interface requires superuser privilege. Run this command from Terminal.app:

$ sudo ifconfig tap0 inet 10.11.1.254/24 up

Verify the IP configuration on the interface. Run this command from Terminal.app:
$ ifconfig tap0
tap0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether ce:d1:be:72:33:67
inet 10.11.1.254 netmask 0xffffff00 broadcast 10.11.1.255
open (pid 34415)

Test the Connectivity
Ping from our Mac (tap0) to the virtual router. Run this command from Terminal.app:
$ ping -c 3 10.11.1.1
PING 10.11.1.1 (10.11.1.1): 56 data bytes
64 bytes from 10.11.1.1: icmp_seq=0 ttl=255 time=3.223 ms
64 bytes from 10.11.1.1: icmp_seq=1 ttl=255 time=1.316 ms
64 bytes from 10.11.1.1: icmp_seq=2 ttl=255 time=1.328 ms

Ping from the virtual router to our Mac (tap0).

R1# ping 10.11.1.254

Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 10.11.1.254, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 8/10/16 ms

Automate
I don't want to manually configure the TAP interface(s) every time I load a GNS3 project, so I created a simple script to take care of this.

001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
#!/usr/bin/env bash # Topology file located in GNS3/Projects directoryTOPFILE=$HOME/Documents/GNS3/Projects/test/topology.net # tap0 interface IP configurationTAP0IP=10.11.1.254/24 # Open GNS3 with topology file/Applications/GNS3.app/Contents/MacOS/GNS3 "$TOPFILE" & # Number of seconds to wait before assigning IP configuration to tap0sleep 5 # Set the IP configuration for the the tap0 interfacesudo ifconfig tap0 inet $TAP0IP up

Copy and paste the text into your preferred text editor, then save the file as launch-gns3-with-test-project.sh.

Give the file the execute permission. Run this command from Terminal.app:
$ chmod u+x launch-gns3-with-test-project.sh

Run the script. You will be requested for your user account password because modifying the logical network configuration for a network interface requires superuser privilege via the sudo command. Run this command from Terminal.app:
$ ./launch-gns3-with-test-project.sh

Read More
Posted in Cisco, GNS3, Mac | No comments

Saturday, 12 June 2010

Convert AC3 audio to MP3 for XviD files with FFmpeg

Posted on 17:15 by Unknown
I recently ran into an issue where I wanted to play a movie on one of my portable devices, but the file's audio stream was encoded in the AC3 (Dolby Digital) format. Of course the device doesn't support AC3, so I would need to convert it to a compatible format. MP3 was supported.

Handbrake is usually my "go-to" tool for a media file conversion, but it no longer supports output to XviD (or more specifically, the AVI container). I could convert the whole file, but I was looking for a way to just transcode the audio and leave the XviD video stream intact. This is ideal because transcoding video is the most time consuming operation of the media file conversion process. Knowing that Handbrake leverages FFmpeg, I decided to do some research to see if it could solve my problem. It looks like I found a solution considering the title of this post. :-) Alright, let's get started.

Get and Install FFmpeg
# Mac OS X
Install MacPorts if needed. Visit http://www.macports.org for all the details.

Sync your local ports tree with the global MacPorts ports repository to be sure you have the latest and greatest. Run this command from Terminal.app:
$ sudo port -d selfupdate

Now let's grab the FFmpeg port source and compile. This will also grab the required dependency packages like LAME, XviD, x264, etc. if you don't already have them installed. Run this command from Terminal.app:
$ sudo port -v install ffmpeg

# Ubuntu
The FFmpeg package included in the default repository is somewhat restricted, so we will grab our FFmpeg package from the Medibuntu repository.

Refer to Compile FFmpeg on Ubuntu, Debian, or Mint for the latest information of how to install FFmpeg on Ubuntu. 

# Fedora
Fedora does not include the FFmpeg package in the default repositories. Like Ubuntu, we will have to configure a third party repo for our distribution. I will use the ATrpms repository in this example.

Import the ATrpms' public signing key. We will need to execute the following instructions under the root account. Run this command from the terminal:
$ su -
# rpm --import http://packages.atrpms.net/RPM-GPG-KEY.atrpms

Create and add the atrpms.repo file to the /etc/yum.repos.d directory. Run this command from the terminal:
# vim /etc/yum.repos.d/atrpms.repo

Add the following information to the file:
[atrpms]
name=Fedora Core $releasever - $basearch - ATrpms
baseurl=http://dl.atrpms.net/f$releasever-$basearch/atrpms/stable
gpgkey=http://ATrpms.net/RPM-GPG-KEY.atrpms
gpgcheck=1

Save the file and exit Vim.
:wq

We are finally ready to grab FFmpeg and the dependency packages. Run this command from the terminal:
# yum install ffmpeg

Unleash FFmpeg
This is a snapshot of the original file's attributes before conversion.
We will now execute the FFmpeg command with all the required options and arguments.
$ ffmpeg -i "/Users/marc/Movies/example_101.avi" -vcodec copy \
-acodec libmp3lame -ab 160k -ac 2 -af volume=2.0 \
"/Users/marc/Movies/example_101_mod.avi"

Dissection of our FFmpeg command syntax:

OptionValueDescription
-i"/Users/marc/Movies/example_101.avi"The absolute path for the input file
-vcodeccopyForce video codec to copy our original XviD stream
-acodeclibmp3lameUse the LAME MP3 encoder for the audio stream
-ab160kThe bitrate of our MP3 audio stream
-ac2The number of audio channels
-afvolume=2.0The volume of the audio stream
"/Users/marc/Movies/example_101_mod.avi"The absolute path for the output file

This is how it should look if FFmpeg was able to successfully convert the file.
Let's take this a step further and automate the conversion process for a directory of files. I created a shell script that takes a source directory and target directory as arguments.

001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019
#!/usr/bin/env bash# convert-xvid-audio - Converts AC3 audio stream to MP3 for XviD files # Set a value for the audio quality and volumeBITRATE=160 # 128,160,192,224,256,320VOLUME='volume=2.0' # The default is 1.0 (examples: 0.5,1.5,2.0) if [ -d "$1" ] && [ -d "$2" ]; then find "$1" -type f -maxdepth 1 -iname '*.avi' | sed 's:.*/::' | while read FN do ffmpeg -i "$1"/"$FN" -vcodec copy -acodec libmp3lame \ -ab ${BITRATE}k -ac 2 -af $VOLUME \ "$2"/"${FN%.*}_mod.avi" < /dev/null; done exit 0else echo "usage: $(basename $0) source_directory target_directory" >&2 exit 1fi

Save the script as convert-xvid-audio.sh.

Give the script the execute permission.
$ chmod u+x convert-xvid-audio.sh

Run the script. The following command will process all the orignal XviD files in FolderY and output them to FolderZ after the conversion.
$ ./convert-xvid-audio.sh ~/Movies/FolderY ~/Movies/FolderZ
Read More
Posted in FFmpeg, Linux, Mac | No comments

Saturday, 22 May 2010

PowerShell version of the uptime command

Posted on 21:48 by Unknown
I created a PowerShell advanced function that emulates the uptime command in Unix-like operating systems.

The uptime command displays the current time, the length of time the system has been up, the number of users, and the load average of the system over the last 1, 5, and 15 minutes.

$ uptime
21:33 up 7 days, 11:10, 2 users, load averages: 0.05 0.08 0.08

My function will return a custom PowerShell object, so we have the option to pass it to the pipeline for further processing and/or formatting.
PS> Get-Uptime | Get-Member

TypeName: BN.Uptime

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Computer NoteProperty System.String Computer=DC01
Days NoteProperty System.Int32 Days=9
Hours NoteProperty System.Int32 Hours=12
Minutes NoteProperty System.Int32 Minutes=46
Seconds NoteProperty System.Int32 Seconds=16

Here is the function:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
function Get-Uptime
{
    [CmdletBinding()]
    
param
    (
        [Parameter(ValueFromPipeline
=$true,
                   ValueFromPipelineByPropertyName
=$true)]
        [Alias(
'hostname')]
        [Alias(
'cn')]
        [
string[]]$ComputerName = $env:COMPUTERNAME
    )

    
BEGIN {}

    
PROCESS
    {
        
foreach ($computer in $ComputerName)
        {
            
try
            {
                
$os = Get-WmiObject -Class Win32_OperatingSystem `
                
-ComputerName $computer -ErrorAction Stop
                
$time = $os.ConvertToDateTime($os.LocalDateTime) - `
                        
$os.ConvertToDateTime($os.LastBootUpTime)

                
# Create property hash table for custom PS object
                
$props = @{'Computer'=$os.CSName;
                           
'Days'=$time.Days;
                           
'Hours'=$time.Hours;
                           
'Minutes'=$time.Minutes;
                           
'Seconds'=$time.Seconds;}

                
# Create custom PS object and apply type
                $uptime = New-Object -TypeName PSObject -Property $props
                
$uptime.PSObject.TypeNames.Insert(0,'BN.Uptime')

                
Write-Output $uptime
            }
            
catch
            {
                
# Check for common DCOM errors and display "friendly" output
                switch ($_)
                {
                    {
$_.Exception.ErrorCode -eq 0x800706ba } `
                        {
$err = 'Unavailable (Host Offline or Firewall)' }
                    {
$_.CategoryInfo.Reason -eq 'UnauthorizedAccessException' } `
                        {
$err = 'Access denied (Check User Permissions)' }
                    
default { $err = $_.Exception.Message }
                }
                
Write-Warning "$computer - $err"
            }
        }
    }

    
END {}

}

Usage
The following are just a few examples of sample usage for the function.

# Get Uptime Information for Multiple Computers (Method 1)

PS> 'dc01','db01','sp01' | Get-Uptime | ft -auto comp*,days,hours,min*,sec*

Computer Days Hours Minutes Seconds
-------- ---- ----- ------- -------
DC01 17 7 3 58
DB01 17 4 4 52
SP01 17 3 55 04

# Get Uptime Information for Multiple Computers (Method 2)

PS> ipmo ActiveDirectory
PS> Get-Uptime -cn (Get-ADComputer -f * | select -expand name) | ft -auto comp*,days,hours,min*,sec*

Computer Days Hours Minutes Seconds
-------- ---- ----- ------- -------
DC01 17 7 3 58
DB01 17 4 4 52
SP01 17 3 55 04

# Get Uptime Information for Local Computer in Unix-like Format

PS> function uptime
>> {
>> $time = [System.DateTime]::Now.ToShortTimeString()
>> $uptime = Get-Uptime
>> Write-Host $time " up" $uptime.days "day(s)," $uptime.hours "hour(s)," $uptime.minutes "min(s)"
>> }
>>
PS> uptime
4:53 PM up 9 day(s), 23 hour(s), 30 min(s)

Read More
Posted in PowerShell, Windows | No comments

Thursday, 8 April 2010

PowerShell version of the df command

Posted on 12:09 by Unknown
I use the df command quite a bit with Unix-like operating systems and desired for a similar solution while working in Windows PowerShell. The df utility displays statistics about the amount of free disk space on the specified filesystem. I created a PowerShell function that encapsulates the core functionality of the command for the Windows platform.

Just for reference, this is example output from the df command on Linux:

$ df -ahT
Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/vg_rt-lv_root
ext4 37G 1.1G 35G 3% /
proc proc 0 0 0 - /proc
sysfs sysfs 0 0 0 - /sys
devpts devpts 0 0 0 - /dev/pts
tmpfs tmpfs 495M 0 495M 0% /dev/shm
/dev/sda1 ext4 485M 52M 408M 12% /boot
none binfmt_misc 0 0 0 - /proc/sys/fs/binfmt_misc

Basically, in a nutshell, the PowerShell function queries the removable disk, local disk, network, CD/DVD, and ram disk drive types and creates a custom PowerShell object for output. In addition to the default output of the "raw" PS object, I also implemented a -Format option for "human friendly" output.

001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
function Get-DiskFree{ [CmdletBinding()] param ( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias('hostname')] [Alias('cn')] [string[]]$ComputerName = $env:COMPUTERNAME, [Parameter(Position=1, Mandatory=$false)] [Alias('runas')] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [Parameter(Position=2)] [switch]$Format ) BEGIN { function Format-HumanReadable { param ($size) switch ($size) { {$_ -ge 1PB}{"{0:#.#'P'}" -f ($size / 1PB); break} {$_ -ge 1TB}{"{0:#.#'T'}" -f ($size / 1TB); break} {$_ -ge 1GB}{"{0:#.#'G'}" -f ($size / 1GB); break} {$_ -ge 1MB}{"{0:#.#'M'}" -f ($size / 1MB); break} {$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break} default {"{0}" -f ($size) + "B"} } } $wmiq = 'SELECT * FROM Win32_LogicalDisk WHERE Size != Null AND DriveType >= 2' } PROCESS { foreach ($computer in $ComputerName) { try { if ($computer -eq $env:COMPUTERNAME) { $disks = Get-WmiObject -Query $wmiq ` -ComputerName $computer -ErrorAction Stop } else { $disks = Get-WmiObject -Query $wmiq ` -ComputerName $computer -Credential $Credential ` -ErrorAction Stop } if ($Format) { # Create array for $disk objects and then populate $diskarray = @() $disks | ForEach-Object { $diskarray += $_ } $diskarray | Select-Object @{n='Name';e={$_.SystemName}}, @{n='Vol';e={$_.DeviceID}}, @{n='Size';e={Format-HumanReadable $_.Size}}, @{n='Used';e={Format-HumanReadable ` (($_.Size)-($_.FreeSpace))}}, @{n='Avail';e={Format-HumanReadable $_.FreeSpace}}, @{n='Use%';e={[int](((($_.Size)-($_.FreeSpace))` /($_.Size) * 100))}}, @{n='FS';e={$_.FileSystem}}, @{n='Type';e={$_.Description}} } else { foreach ($disk in $disks) { $diskprops = @{'Volume'=$disk.DeviceID; 'Size'=$disk.Size; 'Used'=($disk.Size - $disk.FreeSpace); 'Available'=$disk.FreeSpace; 'FileSystem'=$disk.FileSystem; 'Type'=$disk.Description 'Computer'=$disk.SystemName;} # Create custom PS object and apply type $diskobj = New-Object -TypeName PSObject ` -Property $diskprops $diskobj.PSObject.TypeNames.Insert(0,'BinaryNature.DiskFree') Write-Output $diskobj } } } catch { # Check for common DCOM errors and display "friendly" output switch ($_) { { $_.Exception.ErrorCode -eq 0x800706ba } ` { $err = 'Unavailable (Host Offline or Firewall)'; break; } { $_.CategoryInfo.Reason -eq 'UnauthorizedAccessException' } ` { $err = 'Access denied (Check User Permissions)'; break; } default { $err = $_.Exception.Message } } Write-Warning "$computer - $err" } } } END {} }

Usage
The function can be utilized for a variety of use cases. The following are just a few examples:

# Default Output
By default, the function will return PS "disk" objects. From this specific output, you will notice three separate objects are returned from the local computer named DC01 with the numeric values in bytes.

PS> Get-DiskFree

FileSystem : NTFS
Type : Local Fixed Disk
Used : 13246943232
Volume : C:
Available : 29595770880
Computer : DC01
Size : 42842714112

FileSystem : CDFS
Type : CD-ROM Disc
Used : 623890432
Volume : D:
Available : 0
Computer : DC01
Size : 623890432

FileSystem : NTFS
Type : Network Connection
Used : 16416772096
Volume : Z:
Available : 26425942016
Computer : DC01
Size : 42842714112

# Output with the Format Option
In this example, We're performing a query against a couple of remote servers. Instead of having the function return separate PowerShell "disk" objects for each remote computer, we prefer to have the collection output in a structured table format with human-readable numbers. This would be similar to the *nix df command output with the -h option.

Note: The -Format option should only be enabled when no further numeric operations will need to be performed on the Available, Size, and Used properties. The option converts these values to the string data type.


PS> $cred = Get-Credential -Credential 'example\administrator'
PS> 'db01','sp01' | Get-DiskFree -Credential $cred -Format | ft -GroupBy Name -auto

Name: DB01

Name Vol Size Used Avail Use% FS Type
---- --- ---- ---- ----- ---- -- ----
DB01 C: 39.9G 15.6G 24.3G 39 NTFS Local Fixed Disk
DB01 D: 4.1G 4.1G 0B 100 CDFS CD-ROM Disc

Name: SP01

Name Vol Size Used Avail Use% FS Type
---- --- ---- ---- ----- ---- -- ----
SP01 C: 39.9G 20G 19.9G 50 NTFS Local Fixed Disk
SP01 D: 722.8M 722.8M 0B 100 UDF CD-ROM Disc

# Low Disk Space
What if we just need a list of Windows servers in the Active Directory domain which have disk space below 20% for their C: volume?

PS> Import-Module ActiveDirectory
PS> $servers = Get-ADComputer -Filter { OperatingSystem -like '*win*server*' } | Select-Object -ExpandProperty Name
PS> Get-DiskFree -cn $servers | Where-Object { ($_.Volume -eq 'C:') -and ($_.Available / $_.Size) -lt .20 } | Select-Object Computer

Computer
--------
FS01
FS03

# Out-GridView
And in this example, we will filter on the local hard drives of four select servers and have the output displayed in an interactive table.

PS> $cred = Get-Credential 'example\administrator'
PS> $servers = 'dc01','db01','exch01','sp01'
PS> Get-DiskFree -Credential $cred -cn $servers -Format | ? { $_.Type -like '*fixed*' } | select * -ExcludeProperty Type | Out-GridView -Title 'Windows Servers Storage Statistics'

# Output to CSV
PowerShell also gives us the ability to output to a comma-separated values (CSV) file type. This example is similar to the previous except we will also sort the disks by the percentage of usage. We've also decided to narrow the set of properties to name, volume, total size, and the percentage of the drive space currently being used.

PS> $cred = Get-Credential 'example\administrator'
PS> $servers = 'dc01','db01','exch01','sp01'
PS> Get-DiskFree -Credential $cred -cn $servers -Format | ? { $_.Type -like '*fixed*' } | sort 'Use%' -Descending | select -Property Name,Vol,Size,'Use%' | Export-Csv -Path $HOME\Documents\windows_servers_storage_stats.csv -NoTypeInformation

Read More
Posted in PowerShell, Windows | No comments

Monday, 29 March 2010

SSH using Public-Key Authentication

Posted on 16:27 by Unknown
Lately, I've been implementing a solution to make SSH connections more secure and manageable (i.e., getting away from password authentication). A couple of benefits public-key authentication has over the default password authentication is:
  • You only have to remember the passphrase of your private key rather than possibly dozens of username/password combinations for remote hosts.
  • A password sent across the network, even protected by an SSH secure channel, can be captured when it arrives on the remote host if that host has been compromised.

#Generate the Key Pair
RSA authentication will need a passphrase to encrypt the private key. It is highly recommended to create a strong passphrase for the private key. A strong passphrase is at least 10 - 15 characters long and not a grammatical sentence. The following command creates a 2048-bit RSA key pair and prompts you for a passphrase:
$ ssh-keygen -t rsa -b 2048
Generating public/private rsa key pair.
Enter file in which to save the key (/home/marc/.ssh/id_rsa):
Created directory '/home/marc/.ssh'.
Enter passphrase (empty for no passphrase): Thi$isy0urP@ssphra$e
Enter the same passphrase again: Thi$isy0urP@ssphra$e
Your identification has been saved in ~/.ssh/id_rsa.
You public key has been saved in ~/.ssh/id_rsa.pub.
The key fingerprint is:
39:c0:50:dd:a7:0a:8f:bb:6e:6a:e0:83:98:34:88:a5 marc@test.internal

#Identify and Copy the Authorized Keys
Now that you have a public-key file, you can simply place that key in a remote account on any machine running the SSH server (usually named sshd). Once you've set up the account properly, your private key will allow easy access to it.

To allow access to an account, simply create the file ~/.ssh/authorized_keys. The file contains one key per line. Here is one example that will copy the public key to the remote host account:
$ cat ~/.ssh/id_rsa.pub | ssh marc@remotehost 'cat >> ~/.ssh/authorized_keys'

Verify (or set) the permissions, on the remote host account, for the .ssh folder and the authorized_keys file:
$ chmod 0700 ~/.ssh
$ chmod 0600 ~/.ssh/authorized_keys

#SSHD Configuration
By default, the account password also allows access to the account. You can disable this feature in the OpenSSH sshd by modifying /etc/ssh/sshd_config (or the equivalent on your system) and adding (or modifying) this line:
PasswordAuthentication no

You also want to verify the PubkeyAuthentication property of the /etc/ssh/sshd_config file is enabled.
PubkeyAuthentication yes
Read More
Posted in Security, SSH | No comments

Tuesday, 9 February 2010

Configure Inter-VLAN routing on a Cisco L3 Catalyst Switch

Posted on 17:20 by Unknown
I recently had to configure inter-VLAN routing at a client's site. I don't have to perform this task on a regular basis, so I figured I would make a post for future reference of a sample implementation.


Ingredients used for the recipe:
  • Cisco 2811 Router
  • Cisco Catalyst 3560
  • Cisco Catalyst 2950


1. Configure the Corp router
Corp> enable
Corp# conf t
Corp# int fa 0/1
Corp(config-if)# description Link_to_L3SW
Corp(config-if)# ip address 172.17.17.9 255.255.255.252
Corp(config-if)# no shut
Corp(config-if)# end

2. Configure the Cisco Catalyst 3560 Switch
L3SW> enable
L3SW# conf t
L3SW(config)# vtp mode server
L3SW(config)# vtp domain test
L3SW(config)# vtp password test
L3SW(config)# vlan 10
L3SW(config-vlan)# name Marketing
L3SW(config-vlan)# end
L3SW(config)# vlan 20
L3SW(config-vlan)# name IT
L3SW(config-vlan)# end
L3SW(config)# int gi 0/1
L3SW(config-if)# switchport trunk encapsulation dot1q
L3SW(config-if)# switchport mode trunk
L3SW(config-if)# switchport nonegotiate
L3SW(config-if)# end
L3SW(config)# ip routing
L3SW(config)# int vlan 1
L3SW(config-if)# ip address 10.100.1.1 255.255.255.0
L3SW(config-if)# no shut
L3SW(config)# int vlan 10
L3SW(config-if)# ip address 10.100.10.1 255.255.255.0
L3SW(config-if)# no shut
L3SW(config)# int vlan 20
L3SW(config-if)# ip address 10.100.20.1 255.255.255.0
L3SW(config-if)# no shut
L3SW(config-if)# end
L3SW(config)# int fa 0/24
L3SW(config-if)# no switchport
L3SW(config-if)# ip address 172.17.17.10 255.255.255.252
L3SW(config-if)# no shut
L3SW(config-if)# end
L3SW(config)# ip route 0 0 172.17.17.9
L3SW(config)# end

3. Configure the Cisco Catalyst 2950 Switch
L2SW> enable 
L2SW# conf t
L2SW(config)# vtp mode client
L2SW(config)# vtp domain test
L2SW(config)# vtp password test
L2SW(config)# int range fa 0/1 - 4
L2SW(config-if-range)# switchport mode access
L2SW(config-if-range)# switchport access vlan 10
L2SW(config-if-range)# int range fa 0/5 - 8
L2SW(config-if-range)# switchport mode access
L2SW(config-if-range)# switchport access vlan 20
L2SW(config-if-range)# end
L2SW(config)# int gi 0/1
L2SW(config-if)# switchport trunk encapsulation dot1q
L2SW(config-if)# switchport mode trunk
L2SW(config-if)# switchport nonegotiate
L2SW(config-if)# end
L2SW(config)# int vlan 1
L2SW(config-if)# ip address 10.100.1.2 255.255.255.0
L2SW(config-if)# no shut
L2SW(config-if)# end
L2SW(config)# ip default-gateway 10.100.1.1
L2SW(config)# end


Read More
Posted in Cisco | No comments

Tuesday, 5 January 2010

Install/Upgrade VMware Tools on Ubuntu Server guest

Posted on 22:01 by Unknown
I'm always "googling" this task whenever I have to install or upgrade the VMware Tools on a Linux VM guest. I figure I would make a post for future reference.

Ingredients used for the recipe:
  • Host: VMware ESX Server 4.0
  • Guest: Ubuntu Server 9.10

1. Use the vSphere Client to connect to a vCenter Server or directly to an ESX host.

2. Right-click the virtual machine and select Open Console.

3. Log into Ubuntu with an administrative user account.

4. From the Virtual Machines tab, right-click the Linux VM -> Guest -> Install/Upgrade VMware Tools



5. Create a root login shell.
$ sudo -i

6. Update and install prerequisite packages.
# apt-get update
# apt-get install build-essential linux-headers-$(uname -r) psmisc

7. Mount the CD drive and change to the directory.

# mount /media/cdrom; cd $_

8. Extract the compressed file to the /tmp directory and then cd to it.
# tar xf VMwareTools-*.tar.gz -C /tmp
# cd /tmp/vmware-tools-distrib

9. Execute the vmware-install.pl Perl script with the defaults option.
# ./vmware-install.pl -d

10. Remove the temporary installation.

# rm -rf /tmp/vmware-tools-distrib

11. Unmount the CD drive.
# umount /media/cdrom

Note: You will need to reinitialize the VMware toolset after a kernel upgrade.
# /usr/bin/vmware-config-tools.pl
Read More
Posted in Linux, VMware | No comments
Newer Posts Older Posts Home
Subscribe to: Comments (Atom)

Popular Posts

  • Cisco ASA SSL VPN with Active Directory
    There is little doubt the bring-your-own-device (BYOD) strategy is becoming a popular method to access company resources. As technical prof...
  • PowerShell Function for Windows System Memory Statistics
    Memory is one of the four primary hardware resources an operating system manages. The other three are cpu, disk, and network. Analysis of sy...
  • Integrate VMware Fusion with GNS3 on your Mac
    At long last, we can finally integrate VMware Fusion with GNS3. VMware Workstation for Windows and Linux has had this capability for quite s...
  • Configure Inter-VLAN routing on a Cisco L3 Catalyst Switch
    I recently had to configure inter-VLAN routing at a client's site. I don't have to perform this task on a regular basis, so I figur...
  • SSL VPN configuration on Cisco ASA with AnyConnect VPN client
    This post will describe how to setup a Cisco Adaptive Security Appliance (ASA) device to perform remote access SSL VPN with the stand-alone ...
  • Enable sudo for RHEL and CentOS
    Sudo is an arguably safer alternative to logging in (or using the su command) to the root account. Sudo allows you to partition and delegat...
  • Get Exchange Server Version and Update Info with PowerShell
    I prefer not to "reinvent the wheel", so I spent quite a bit of time searching the web for available code that would perform the t...
  • Cisco Security Device Manager on the Mac
    Cisco Router and Security Device Manager (SDM) is a Web-based device-management tool that enables you to deploy and manage the services on a...
  • Install Request Tracker 4 on Ubuntu Server
    The CentOS6/RT4 blog post has generated terrific feedback, so I figure an Ubuntu (and Debian) distribution port is essential. The core com...
  • Install Request Tracker 4
    The argument could be made Request Tracker is the de facto standard when it comes to issue tracking systems. Maybe the only drawback of RT ...

Categories

  • AD
  • Apache
  • AWS
  • Cisco
  • Exchange
  • FFmpeg
  • GNS3
  • Linux
  • Mac
  • MariaDB
  • MySQL
  • PowerShell
  • RT
  • Security
  • SSH
  • VMware
  • Windows
  • Zenoss

Blog Archive

  • ►  2013 (8)
    • ►  October (1)
    • ►  September (1)
    • ►  August (1)
    • ►  May (1)
    • ►  April (1)
    • ►  March (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2012 (3)
    • ►  December (1)
    • ►  November (1)
    • ►  April (1)
  • ►  2011 (3)
    • ►  June (1)
    • ►  May (2)
  • ▼  2010 (8)
    • ▼  August (1)
      • Enable sudo for RHEL and CentOS
    • ►  July (1)
      • Install and configure GNS3 with TunTap on the Mac
    • ►  June (1)
      • Convert AC3 audio to MP3 for XviD files with FFmpeg
    • ►  May (1)
      • PowerShell version of the uptime command
    • ►  April (1)
      • PowerShell version of the df command
    • ►  March (1)
      • SSH using Public-Key Authentication
    • ►  February (1)
      • Configure Inter-VLAN routing on a Cisco L3 Catalys...
    • ►  January (1)
      • Install/Upgrade VMware Tools on Ubuntu Server guest
  • ►  2009 (3)
    • ►  December (1)
    • ►  November (1)
    • ►  October (1)
Powered by Blogger.

About Me

Unknown
View my complete profile