PowerShell - Host Lookup

by al feersum12. April 2013 12:58

PowerShell LogoHow do I lookup a host?  And how do I ensure I handle errors?  And why?

Well... I'm scanning my IIS logs and gathering information about the hosts that connect to my site.  But often, the address I've got can't be resolved, or has dropped off the net - especially if I'm parsing historical logs.

So, I need to get at least some data from the address I've got - the address on its own isn't that useful, apart from address matching in the IIS logs database.

As I process my IIS logs, I send the IP address fields to a PowerShell name resolver which returns a bit more information.

 

Function ResolveAddress {

  Param([string]$IP)

<#

An IPv4 lookup (target host doesn't support IPv6):

Source     Destination     IPV4Address     IPV6Address     Bytes   Time(ms)

------     -----------     -----------     -----------     -----   --------

MyHostName 192.168.55.24   192.168.55.24                   32      1

 

 

An IPv4 lookup (target host /does/ support IPv6):

Source     Destination     IPV4Address   IPV6Address                  Bytes  Time(ms)

------     -----------     -----------   -----------                  -----  --------

MyHostName 192.168.55.25   192.168.55.25 fe80::363f:e352:fd6c:390c%12 32     111

 

 

And an IPv6 lookup:

Source     Destination               IPV4Address   IPV6Address                  Bytes Time(ms)

------     -----------               -----------   -----------                  ----- --------

MyHostName fe80::363f:e352:fd6c:390c 192.168.55.25 fe80::363f:e352:fd6c:390c%12 32    1

 

 

An unknown address:

Bytes Source     Destination   IPV6Address Time(ms) IPV4Address   Dest

----- ------     -----------   ----------- -------- -----------   ----

32    MyHostName 192.168.55.26 ::          0        192.168.55.26 System.Net.IPHostEntry

 

Because we're using a custom object to return bad addresses, the Dest object is visible - although it's available in the normal return data, it doesn't show:

 

An available address:

HostName    Aliases AddressList

--------    ------- -----------

REMOTEHOST  {}      {192.168.55.25}

 

A non-available host:

HostName      Aliases AddressList

--------      ------- -----------

192.168.55.26 {}      {192.168.55.26}

 

What about a /real/ host?

Source Destination    IPV4Address    IPV6Address Bytes Time(ms)

------ -----------    -----------    ----------- ----- --------

MyHost 173.194.78.104 173.194.78.104             32    122

 

... and the 'dest' object?

HostName             Aliases AddressList

--------             ------- -----------

wg-in-f104.1e100.net {}      {173.194.78.104}

#>

 

  # First off, generate an IP address object based on the passed address

  $IPAddr = [System.Net.IPAddress]::Parse($IP)

 

  # Now handle both IPv4 and IPv6 addresses, by using an empty address object

  if ($IPAddr.AddressFamily -eq "InternetworkV6") {

    $IPv4 = [System.Net.IPAddress]::Any

    $IPv6 = $IPAddr

  } else {

    $IPv6 = [System.Net.IPAddress]::IPv6Any

    $IPv4 = $IPAddr

  } 

  # Try and resolve the address using Test-Connection, and send just one packet.

  # Store the returned object in a variable

  if (-not(($Resolved = Test-Connection $IP -Count 1 -ErrorAction SilentlyContinue))) {

    # If Test-Connection failed, create a custom object with the values we're going to want.

    $Resolved = New-Object psobject -Property @{Source = $env:COMPUTERNAME; Destination =$IP; IPV4Address = $IPv4; IPV6Address = $IPv6; Bytes ="32"; $("Time(ms)") = 0}

  } elseif (-not($Resolved.IPV4Address) -and -not($Resolved.IPV6Address)) {

    # Hmm. Test-Connection worked, but it didn't populate the address objects. Naughty.

    # Create a new custom object as above

    $Resolved = New-Object psobject -Property @{Source = $Resolved.PSComputerName; Destination =$IP; IPV4Address =$IPv4; IPV6Address = $IPv6; Bytes = "32"; $("Time(ms)") = 0}

  }

  # Now, lets try and resolve the address

  try {

    $RAddr = ([system.net.dns]::Resolve($IP))

  }

  catch {

    # Can't do it. Ah well. Let's just stick some dummy data in.

    $RAddr = New-Object psobject -Property @{HostName = "Unable to Resolve"}

  }

  # Add the returned address to the $Resolved object

  $Resolved | Add-Member -Name "Dest" -MemberType NoteProperty -Value ($RAddr)

  # And return it.

  return $Resolved

}

 Now I've got a nice object containing useful information about the host that has viewed my site.

Tags: ,

.NET | PowerShell

PowerShell - Ping

by al feersum4. April 2013 07:42

PowerShell LogoPowerShell is really cool!

 I've been doing a lot of work with PowerShell lately, and I needed to find a way of resolving and then pinging a host.

So - I did a quick lookup on MSDN for the System.Net libraries and cobbled together something that checks to see if we can resolve a host address, and then tries to ping it.

I haven't bothered with pipelining, because I don't actually need it in this case - though it shouldn't be too hard to put together.

So, first of all, Invoke-NetworkHostLookup:

Function Invoke-NetworkHostLookup

  Param (

    [string]$HostAddr

  )

  try {

    $HostAddr = ([System.Net.Dns]::GetHostEntry($HostAddr)).AddressList[0].IPAddressToString

  }

  catch {

    Write-Error ("Cannot resolve host " + $HostAddr)

  }

  return $HostAddr

}

Passing the HostAddress you want to lookup, the function calls the GetHostEntry method of the System.Net.Dns class, and returns the first address in the list (if an address has multiple IP addresses, these will get listed in the AddressList[] array, but I only want one).

If GetHostEntry throws an error, we catch this and throw a PowerShell error.

The function returns the first IP address in the AddressList[] array.

So:

$HostAddr = Invoke-NetworkHostLookup($HostAddr)

Sets the value of $HostAddr to the IP address of the first hostname/IP address of the passed $HostAddr string value.

So, now we've got a valid, resolved address, is the host actually listening?

I use the System.Net.NetworkInformation class Ping method to send a single ping to the host in $HostAddr:

Function Test-NetworkHostAvailable {

  Param (

    [string]$HostAddress,

    [int]$PingTimeout

  )

  if (-not($PingTimeout-or ($PingTimeout -lt 1)) {

    [int]$PingTimeout = 50

  }

  $PingOptions = New-Object System.Net.NetworkInformation.PingOptions

  $PingOptions.DontFragment = $true

  $PingSender = New-Object System.Net.NetworkInformation.Ping

 

  # Build a 32 byte buffer to send as the ping packet

  $PingBuffer = [byte[]][System.Text.ASCIIEncoding]::ASCII.GetBytes("012345678901234567890123456789012")

  $PingReply = $PingSender.Send($HostAddress$PingTimeout$PingBuffer$PingOptions)

  return $PingReply.Status

}

We pass the returned host address $HostAddr from Invoke-NetworkHostLookup into Test-NetworkHostAvailable (with an optional timeout in milliseconds - defaults to 50 if not passed or is 'less than 1' - so it'll handle strings too).

I create a PingOptions object $PingOptions so that I can tell the Ping request not to fragment the packet.  Then I create a new Ping object $PingSender.

I have to construct a datapacket to send as the ICMP request, so I just knock up a string containing 32 arbitrary characters, which I have to encode as bytes to pass into the Send method of the Ping object.

Now that I've got all the bits (address, timeout, buffer and options), I send the ping request and return the Reply.Status message - I don't need the timings or other data, I just want the status:

if (Test-NetworkHostAvailable($HostAddr-ne "Success") {

  # Didn't get a successful ping!

  Write-Error ("Did not get a successful ping response from host " + $HostAddr)

}

 ... and with that, I can continue with script flow.

So why don't I use Test-Connection?  It's a perfectly good Ping tool and does exactly what I need, but I want to muck about with the .NET classes, simply because I'm trying to increase my knowledge of the .NET classes, so I can push myself on to developing C# code.

This is all part of a library of tools I'm putting together that processes a database matching IP addresses that are on a blacklist, then passes the address into a PowerShell telnet tool that adds a 'drop' rule to the firewall on my router, so I can at least start on minimising access to my home network and reduce my attack surface.

Tags: ,

.NET | PowerShell

Congratulations Gary and Janis!

by al feersum16. October 2012 16:08

Janis Sharp and Gary McKinnonGary McKinnon has been fighting an unfair extradition request to the US for the last 10 years, now Home Secretary Theresa May has blocked the extradition request on the grounds it would breach his human rights.

This is a landmark decision, and is likely to change the whole relationship of the unfair extradition rules between the UK and US.  It has taken many years of campaigning from Gary's mother Janis to reach this stage, and it should never have even got to this stage.

Now, for godssake, give Gary a fucking job doing what he's good at!  He's got an innate talent, and this could be utilised either by UK plc, or a non-governmental business.

Don't forget, Gary should be hailed as a hero by the US simply because he exposed the holes in their systems before a terrorist organisation did - imagine how that would have panned out....

But... US.gov got caught with their pants around their ankles and were very embarrassed.  I just hope to fuck that heads will now roll.

 

Addendum:

The media are suggesting that there may not actually be a case to answer for.  However, Gary has admitted his guilt, so could technically be convicted under the Computer Misuse Act 1990.  As yet, I don't believe he has not been convicted, though he would have been charged on 'suspicion of offences in contravention of the Computer Misuse Act 1990' based on a 'complaint' from the US authorities, for which the police would have had to have acted upon.  He hasn't yet had a trial, so effectively he's been arrested and on police bail for the last 10 years.

CMA 1990 Penalties:

  1. Unauthorised access to computer material, punishable by 6 months' imprisonment or a fine "not exceeding level 5 on the standard scale" (currently £5000);
  2. Unauthorised access with intent to commit or facilitate commission of further offences, punishable by 6 months/maximum fine on summary conviction or 5 years/fine on indictment
  3. Unauthorised modification of computer material, subject to the same sentences as section 2 offences.

Given that Gary's been effectively in prison for the last 10 years (police bail is, in essence, the same as prison remand prior to sentencing), he's already served the maximum sentence covered by the CMA, so even if he is convicted, he should walk out of court a free man.

Tags: , ,

Autism | Cynical Basket | Law and Order

Mobile iPlayer - but not for me.

by al feersum20. September 2012 14:20

iPlayer logoI like the BBC iPlayer.  I use it a lot - in fact, I watch content on iPlayer more than I actually watch TV.  Sadly my phone (Lumia 800) doesn't support Flash, so when they announced iPlayer Everywhere back in March 2012 I was enthused - now I would be able to stream BBC News to my mobile!

Sadly it was not to be.

In September 2012, the BBC annouced a mobile download service.  Great!  At least I'll be able to download content to my phone and watch it later!  Oh.  Maybe not:

"With mobile downloads for BBC iPlayer, you can now load up your mobile phone or tablet with hours and hours of BBC television programmes, then watch them on the road, on the Tube, on a plane, without worrying about having an internet connection or running up a mobile data bill," said Daniel Danker, general manager of programmes and on-demand for the BBC.

"So you can fill up your device and take the BBC with you on holiday," he added.

Yeah!  I can get BBC content on my phone!  Only:

Available on iPhone, iPad and iPod touch devices, the feature will be coming to Android devices soon.

 Oh.  That's... that's... great.  Yeah.  Thanks for your support BBC.

Now they're saying that they'll replace Flash with their own media player.  OK.  Does this mean that they'll start using a platform agnostic content delivery system, so that I can watch BBC streamed content on my phone?  Can I really, finally, start watching streamed BBC content?  After all, I can watch Youtube content on my Lumia, and, for some reason, Sky have managed to produce an app which allows me to watch live streamed news.  So, BBC, can you do it?  Are you going to wake up to the joys of HTML5 or other platform agnostic RIA technology?

The BBC is launching a new media player for those who watch its catch-up service iPlayer on Android phones and tablets.

Oh.

From the BBC Internet Blog:

"I want to reassure you that Android is an important platform for us. And I know (not least from the comments on David Madden's recent post) that this platform is an important one for many of our users. We've supported iPlayer on Android since June 2010." 

 So - those of us with Windows Phone 7.x/8 will just have to lump it.  Which is a shame because I don't want to watch Sky News.  So why don't I use iPlayer at work?  Well, despite working in Central England, the company I work for has its web proxy hosted in Germany, so any web access I make actually comes from a German IP - so no luck there, as the BBC has thoughtfully blocked all access to addresses outside the UK.

Unless there's a serious push from MS, I don't think the BBC are ever going to support Windows Phone - even if the new range of WP8 devices (I've got my eye on a Lumia 920...) starts making a significant dent in the market, it's still going to be a niche platform.

Tags: , ,

Around the 'net | General | Media

Yet another rebuild... grrr!

by al feersum3. September 2012 10:23

Damn!  Thinking I'd be onto a winner, I decided to install Immunet 3.0 as a free Antivirus solution on my Home Server.  Seems that WHS 2011 doesn't like Immunet and ended up borking my server.

Even after I uninstalled Immunet, the server still wasn't stable - in the end I did an OS reinstall.  Fortunately the only things I lost were the local server backups (which I have replicated elsewhere anyway, using CrashPlan) and my client backups, which, as I haven't borked my PCs, I'm not that worried about.

OK, so I did lose about a day, and it is taking a lot of time for the libraries to resync, but I don't really care.

Tags: ,

Hyper-V | Windows Home Server

Another rebuild

by al feersum20. August 2012 13:36

After an unfortunate series of events, I have had to do yet another rebuild.  I've now got my Home Server running properly now, although I'm still experiencing the media library issues common with many users.

With a fresh install of Server 2008 R2, SQL Server 2008 R2, Windows Home Server 2011 and BlogEngine 2.6, I think I'm finally happy with the stability of my home platform.  Sure, I'd like a bigger machine to run my Server 2008 R2 platform, as its running SQL Server and WHS under Hyper-V, with only an AMD dual core processor and 4G of RAM, but it works well enough.

One of the problems I had before was that after installing BlogEngine on my WHS box, the remote administration stopped working - but this has also been resolved, so I'm pretty chuffed with that too.  Unfortunately I can't get to *.homeserver.com from work, so I had to get another domain... but remote administration doesn't like the name of the domain so I can't do that.  Still - accessing data works great.

Version 2.6 of BlogEngine is also pretty cool - there are still a few bugs, but its a massive improvement on 2.0 - and has some nice new features.  I'm going to have to make a new theme as my old one doesn't work, and Ruslan Tur's DarkBlog (which is really very nice) doesn't do quite what I want it to - so I'll take the BlogEngine.NET Standard theme and tweak it.

One very nice feature that the developers have added is running multiple virtual blogs - so I can effectively have a subsite under this one running another blog - using the same codebase and database!  I already have an idea for what to use this for... but it won't be a quick turnaround.

I want to put the 2.6 codebase into my TFS instance (which I don't currently have installed) so I can manage any updates more effectively before I do any tweaks to themes or the core code (tbh, I don't think I need to do any).

So all in all, the rebuild was pretty productive and gave me some new features to play with, plus got some broken stuff working.  The only data I lost was from the client backups - not a major hassle, but annoying all the same.

 

Tags: , ,

BlogEngine | Hyper-V | Windows Home Server

Microsoft Hyper-V and Windows Homeserver 2011

by al feersum31. May 2011 09:44

I've been running a Windows Home Server for a couple of years now in a Server 2008 R2 Hyper-V virtual machine.  WHS v1 was pretty good, and it did most things I wanted it to do.  Recently, Microsoft released Windows Home Server 2011 (codename 'Vail'), built around the Server 2008 R2 core.  I had tried the beta versions, but much of the functionality wasn't present, so I didn't spend much time with them - but since the official release, I got hold of a copy and installed it.

As I'm running the platform in a Hyper-V VM, I thought I'd try to be a bit clever - having one large VHD became cumbersome, and moving huge lumps of data between one drive and another was a hassle - especially as space is at a premium (I've only got about 2.5T of storage spread across 4 disks), coupled with the drop of Drive Extender (a good thing, IMO - DE was a real annoyance at times) I decided to use software RAID-5, with lots of small VHDs, making it less hassle to move the smaller chunks between disks.

Somewhere along the line, something has gone really bad - I keep getting bad blocks reported on my large physical (where the majority of the VHDs making up the 2T RAID drive are hosted), and every time I add a new VHD to repair the disk pack, during the resync, the physical reports another bad block right in the middle of one of the VHDs.  I don't have the funds to replace the physical right now - so I'm limping along trying to get a complete disk pack resync'd.  I s'pose I was trying to be too ambitious creating a 2T array out of 64G dynamically expanding VHDs.  The 1T array that I've also got configured seems to be OK.

Fortunately, I do have backups of the only irreplaceable files, so if the worst comes to it, I can trash the server, do a low-level format of the disk and rebuild - though it's going to take considerable time to rebuild my movie, music and recorded TV libraries (the recorded TV stuff may take a long time - and some may be lost forever: BBC Horizon programmes don't really get repeated).

Still - I'll keep struggling to bring the disk pack back to life - but I'm wondering if it's nothing to do with the drive, but more with how Windows writes to the disk - causing the filesystem to report errors, though I'm sure that perseverence will pay off in the end.

Tags: ,

Hyper-V | Windows Home Server

Reportin Aspergers. Ur doin it rite!

by al feersum12. April 2011 12:16

The Johnson FamilyScottish Newspaper The Daily Record reports about a family whose children were recently diagnosed with Asperger's syndrome.

But not only were Stephen and Tessa diagnosed, but both their parents Malcolm and Clare also found out that they had Asperger's syndrome.

Clare Johnson said that finding out her children were aspies was "like the sun coming out",  "We had always thought it was everyone else that was weird."

If it wasn't for Stephen's teacher Janice Lewis (pictured, front-left) who helped identify the condition, they'd probably have still been in the dark.  Kudos Janice - we desperately need more people like you to stop us from having a hard time at school, instead of us being bullied by other kids, and being ignored by staff, causing real damage to our education.

Also, thanks to The Daily Record for treating us with a bit of respect.  We aren't weird, strange or retarded - we're just different.  Thanks for showing real people that aren't obsessive criminal murdering nutcases 'because of their disability'.  The only thing in this article I take umbrage over is the picture - the filename is "johnson-family-asperger-sufferers-663523275.jpg" - we don't suffer from Asperger's, we suffer from how the NT world misunderstands us - and, of course, our comorbids (for those of us that have them).

Tags: ,

Autism | Media

Paddy Considine - Aspie advocate?

by al feersum11. April 2011 15:02

Paddy ConsidineThe Telegraph Online reports today that Paddy Considine has been diagnosed with Asperger's syndrome.  He mentions that 'acting normal' throughout his life has enabled him to 'hide' the real underlying aspects of his personality.

The Express gives a little bit more: "Basic interaction with people - the touch of strangers - becomes a problem. My response is to retreat into myself."  Yeah, I know that feeling Paddy.

Like Paddy, many of us search for answers to why we are the way we are, and finally getting a Dx can be the breakthrough we've been looking for.

Paddy credits his search for a diagnosis to his wife, Shelley, who could see that his coping strategies were starting to fail.  This is a bad time for many of us; we go through our lives trying to fit in, until bang!  One day it just doesn't work anymore.  So, all thanks to Shelley Considine, and to Paddy, welcome to the club.

As a high profile figure, maybe Paddy could help us out.  For many of us, our biggest difficulty is the ignorance and misunderstanding of the neurotypical public.  We find it hard (impossible, sometimes) to adapt to their way of thinking, yet, for them, it should be relatively easy to adapt to us.  Maybe their understanding would help reduce the difficulties we have, such as getting the work that we want, or preventing their ignorance resulting in us having mental health issues, just by giving themselves time to understand us.

After all, it's not as if we are rare!

Tags: ,

Autism | Media

BSkyB/News Corporation Deal Sealed?

by al feersum8. April 2011 15:42

Has the buyout between BSkyB and Murdoch's News Corporation been guaranteed?

Murdoch's News Corporation subsidiary News International's "News of the World" newspaper has now admitted to liability for phone hacking.  One BBC Reporter has suggested that News International expect to get away with paying around £20M in compensation.

Murdoch has been after total control of BSkyB for some time, even offering to 'spin off' popular 24 hour rolling news channel Sky News.  He's so desperate to get his hands on BSkyB that I suspect he's prepared to do anything.

I wonder how that conversation worked?

Murdoch: G'day Jezza you old bastard, give me BSkyB!

Jeremy 'Rhymes with' Hunt: I'm sorry Mister Murdoch, it doesn't work like that.

Murdoch: What have I got to do to get it?

'Rhymes with': Well, you can start by getting News International to accept liability for phone hacking, then bend over and take it up the... take your punishment.

Murdoch: No worries mate! I'll sort out a whole bloody flock of sacrificial lambs! Nice doing business with you!

'Rhymes with': It might cost you a few quid though.

Murdoch: Yeah? I got more money than I know what to do with, I don't give a toss! Cheers mate!

... and so the independence of British media is slowly eroded...

Tags: , ,

Cynical Basket | Law and Order | Social Decay

Contact me

Al Feersum
Aspie Geek
Email me
View Al Feersum's profile on LinkedIn

Calendar

<<  April 2014  >>
MoTuWeThFrSaSu
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

View posts in large calendar

Begging Bowl

Please support these organisations.