Thursday, January 23, 2020

(Python) Setting nano up for Python scripting

There are much better IDEs for Python than using nano if you are doing app development. For quick hacks though nano works great. With a few tweaks it can be a much better experience.

For Python code the recommended spacing is to use:

Per the PEP: https://www.python.org/dev/peps/pep-0008/#indentation

  • Spaces are the preferred indentation method (Avoid using tabs).
  • Use 4 spaces per indentation level.
  • Limit all lines to a maximum of 79 characters (we dont fix this here)


I use nano all the time (convenience) but the default is an 8 space tab.

You can set it each time from using the nano arguments

nano -$ -clET 4 <filename.txt>

  • -$ = Enable soft line wrapping
  • -c  = Constantly show cursor position
  • -l = Show line numbers in front of text
  • -E =  Convert typed tabs to spaces
  • -T  <#cols> = Set width of a tab to #cols columns



or this can be permanently reset in the system nanorc file and just work when you launch nano:

nano /etc/nanorc

  • set tabsize 4
  • set tabstospaces
  • set constentshow
  • set linenumbers
  • set softwrap


Monday, October 8, 2018

(Python) GeoLocation of an IP address from the command line.



import sys
import json
import urllib.request

url = "http://ipinfo.io/" + sys.argv[1] + "/json"

#print(url)
with urllib.request.urlopen(url) as response:
    myDict = json.loads(response.read().decode())

try:
    outputHostname  = 'Hostname:\t{}\n'.format(myDict.get("hostname"))
    outputCity      = 'City:\t\t{}\n'.format(myDict.get("city"))
    outputRegion    = 'Region:\t\t{}\n'.format(myDict.get("region"))
    outputCountry   = 'Country:\t{}\n'.format(myDict.get("country"))
    outputLoc       = 'Loc:\t\t{}\n'.format(myDict.get("loc"))
    outputPostal    = 'Postal:\t\t{}\n'.format(myDict.get("postal"))
    outputPhone     = 'Phone:\t\t{}\n'.format(myDict.get("phone"))
    outputOrg       = 'Org:\t\t{}'.format(myDict.get("org"))

    output =  outputHostname + outputCity + outputRegion + outputCountry + outputLoc + outputPostal + outputPhone + outputOrg                             
    print(output)
except:
    output = 'IP Address: {}\nBogon: {}'.format(myDict.get('ip'),myDict.get('bogon'))
    print(output)

Sunday, April 16, 2017

(powershell) Remove line breaks from a file

I needed to remove the newlines from an exported certificate to get the public key.
Nice and simple.


 $result = 'string_with_newlines'' -replace "`t|`n|`r",""

Saturday, May 28, 2016

My GIT Notes

GIT (to practice git “try.git.io"
======================

Setup:

One time system setup:
git config —global user.name <username> 
git config —global user.email test.user@gmail.com
git config —global push.default matching (for forward compatibility, optional)
git config —global alias.co checkout (This aliases checkout to co, optional)

Note: these settings are saved globally in the "/home/<username>/.gitconfig” file


Step 1) Creating a github repository and connecting it to your project. 

NOTE: you need to create a project repository on the github website then add remote target to git.

  on the github web site: "+New Repository” enter <projectname> 

  on the local machine in the <projectname> directory
git remote add origin https://github.com/<username>/<projetname>.git
  The previous line adds the following to the "<projectname>/.git/config” file. 
  [remote "origen"]
        url = https://github.com/<username>/sample_app.git
        fetch = +refs/heads/*:refs/remotes/origen/*
  [branch "master"]
       remote = origen
        merge = refs/heads/master
 
Step 2) Initializing and synchronizing the project 

initialize git: (use this the first time for each project)

cd <project root directory>

git init  (Create an empty git repository or reinitialize a current one)

git add -A  (Adds all of the files in the current directory to a staging area {except what is in .gitignore})

git status (view files in staging area)

git commit -a -m “My log message goes here” (commit the changes to the repository {NOTE: local only})

-m “” lets you add a message to each commit. You can view the commit messages using "git log”
-a (be careful with the ‘-a’ this adds all changed files and commits them. This may or may not be what you want_ 

git add . (USE THIS VERY CAREFULLY AND NOT MUCH!!!!, This will add all data including images to your commit)

git push -u origin master (this will fail if you did not set up the github repository)


Branching
—————
git checkout -b branch-a  (This creates a new branch named “branch-a” and puts code into it)

git branch (This lists all of the current branches)
* branch-a
  master

git checkout master (Return to the master branch, Master is used for known working code. Do not post in progress code to this branch)

git diff branch-a  (This will compare the files in the master branch with the files in the “branch-a” branch and show you the difference)

To Delete a Branch
————————-
git branch -d branch-a (This will delete a branch ONLY if it has been merged, Use -D if you want to deleted regardless of merge state)



To save a work in progress if you need to go work on something else:
————————————————————————————————
git checkout -b branch-b 

git commit -am “WIP: This is a work in progress, needed to work on patch on master”

git checkout master

Tweak app

git commit -am “Fix to master done”

git checkout branch-b


To merge the branches, navigate to the branch you want code MOVED INTO and run merge:
————————————————————————————————————————

git checkout master

git merge branch-b -m “Merged branch-b features with master"


GitFlow
——————
Produces a diagram of the flow of the get matenence. 


Git Tree
———————
git tree

edit you .gitconfig and add this to the bottom
nano ~/.gitconf

tree = log —graph —decorate -oneline —all —color

Monday, May 25, 2015

(Powershell) Zip / Unzip


Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
    param([string]$zipfile, [string]$outpath)

    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}

Unzip "C:\a.zip" "C:\a"

Friday, May 15, 2015

(PowerShell) Quick and dirty NetCat style listener

I was trying to come up with something in PowerShell that would listen on an arbitrary port and return a string. This seems to do the job perfectly.


while ($true)
{
    $listener = new-object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse('0.0.0.0'), 42000)

    $listener.start()

    $client = $listener.AcceptTcpClient()

    $stream = $client.GetStream()
   
    $stWriter = new-Object System.IO.StreamWriter($stream)
   
    $stWriter.WriteLine("Put your text right here")
    $stWriter.Flush
    $stWriter.Close()

    $client.Close()

    $listener.Stop()

    write-host "Connection closed."
}

Thursday, April 30, 2015

(Metasploit) Clear console history

This is going here just so I don't have to go looking for it again.
I was trying to figure out how to clear the Metasploit command history to have a fresh msfconsole experience. It turns out that it is stored in the /root/.msf4/history file.

So we check the file sizes of the history and log files using tree -ha
















and clear them out.

echo "" > /root/.msf4/history

Done

Tuesday, April 28, 2015

(ASA5512) No ASDM connection

Thanks for this one Cisco :(

The symptoms of this particular problem threw me a little because ssh worked fine but ASDM just showed "Page not Found" or some such crap. Now I wanted to do some clean up on this box any way so I

erase disk0:/
format disk0:/

re-uploaded the core files.

asa912-smp-k8.bin
asdm-713.bin
csd_3.5.2008-k9.pkg
anyconnect-win-2.5.2014-k9.pkg

When it came back up I entered the license key and it still did not work >:(

So anyway, here is the fix.

Add these two lines in config# mode:
ssl encryption aes128-sha1 
ssl encryption 3des-sha1


The issue is described in the ASDM manual:




Monday, April 20, 2015

Friday, April 17, 2015

(OSX) lsof -i [View PID associated with a socket]

Just a note, I need to putz with this. It looks better than netstat-nao | grep tcp. 

lsof -i 

(OSX) GeoLocation of an IP address from the command line.


So I was trying to figure out an easy way to get a GeoLocation from an IP address. I wanted a one liner that could get the info instead of having to go to a web page.

The info.io web site did the trick. It outputs in json format.


curl ipinfo.io/<ip address>


EX:












Powershell:

(Invoke-WebRequest http://ipinfo.io/<ip address>/json).Content


EX:

Tuesday, January 13, 2015

(PowerShell) Enumerating Local User Accounts

This was mildly annoying so I thought I would put it here so next time I run into this I know how to do it. I wanted to simply enumerate all of the standard user accounts on the LocalMachine using a one liner PowerShell cmdlet. Most of methods I found online with a google search said to use [ASDI]. This was more convoluted than I wanted to get to do this seemingly simple thing.

After stewing for a bit I started digging through the Get-WmiObject cmdlet and there it was!!!

-Class Win32_UserAccount


So I took a look at the available properties and output the usernames only.

Get-WmiObject -Class Win32_UserAccount | Get-Member













So I just formatted the output to include just the Name property and there it is.

Get-WmiObject -Class Win32_UserAccount | Format-List -Property Name









But we are not going to stop there :)
I went ahead and pulled just the admin account.

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Name -eq "Administrator"}









That was only a subset of the properties so I used Format-List -Property * to pull up the rest of them

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Name -eq "Administrator"} | Format-List -Property *


















Now that I can see all of the properties I can check for certain properties across all of the accounts. For example I can list all of the accounts that are currently disabled.

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Disabled -eq $true}












If I break my one line rule I can even modify properties of the user object, for example lets say that I wanted to enable the Administrator account for some reason (Don't do this, I am just figuring out how this works and enabling the Administrator account is a bad idea).

[Note: The .Put() thing, this threw me for a few minutes. Remember when you use any of the Get- commands what you are actually doing is grabbing templates of the objects and then filling them with data PowerShell grabs from the OS. What I changed when I set Disabled = $false is the value in the new object I created. The .Put() command takes my object and saves it back to OS so that the changes take effect. Without the .Put() nothing changes on the OS]

$tempuser = Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Name -eq "Administrator"}

$tempuser.Disabled = $false

$tempuser.Put()



Now if I run my account disabled test from above I get this.

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Disabled -eq $true}




Friday, January 9, 2015

(PowerShell) Filtering netstat output

Update:
This works great :)

netstat -bno


Since standard Windows command line tools can easily interact with PowerShell cmdlets I thought I would try some grep style string filtering.

Lets find all of the ports that are listening on our system:

netstat -nao | Select-String LISTENING

Output:



Or search for a specific port:

netstat -nao | Select-String :139

Output:




Search for all of the UDP ports:

netstat -nao | Select-String UDP

Output:














Now look for all ports that are UDP and on port 1900:

netstat -nao | Select-String UDP | Select-String :1900








:)

Thursday, January 8, 2015

(PowerShell) Clock App Runtime

I wanted to figure out if there was a way in PowerShell to do something like the time command does in Linux (Calculates the amount of time in ms that an application takes to execute. It turns out that that it is built right in to PowerShell in the form of a cmdlet (Measure-Command).

I decided to start with something simple that would take a little time to complete.

Note: The {braces} define a statement block and in this case is used to combine the actions that you want to time. 

Measure-Command {Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue}

Output:












So that worked pretty much how I wanted. So I next I wanted to see if it would time something other than PowerShell cmdlets (like a regular Windows App). I wanted to do something that would take a bit of time so I copied a large file. I checked the PowerShell alias table to make sure robocopy was not an alias for a cmdlet  and gave this a try.

First I found a big file (did not care what it was, just that it was between 100-200MB)

Get-ChildItem -Path $PWD | Where-Object {$_.Length -gt 100MB -and $_.Length -lt 200MB}

Output:





Then ran the speed test on robocopy

Measure-Command {robocopy.exe $PWD $HOME MRT.exe}

Output:











So an executable without a GUI can be timed with no problem. What about a .exe that a user interacts with? It seemed to make sense that something like this would work.

Measure-Command {calc.exe}

Output:











Bad luck, it does not work, it only timed the launching of the app and then returned as soon as the window appeared. I need to do more research but I think that GUI apps disconnect themselves from the shell once they are launched and can not be measured this way :(.

Wednesday, January 7, 2015

(PowerShell) WindowsOS Version (Linux Style)

I decided to do this blog to prove that I can learn something that is worth writing down (and using again at a later time) everyday. It might boring on some days but hopefully I will have some useful info here. So off we go...

==================================================

I wanted a way to to list the Windows OS Version similar to how I can
in Ubuntu.

lsb_release -d







So I tried

Get-WmiObject -Class Win32_OperatingSystem

Which by default returns (Not really what I was looking for)








After digging through the properties a little What I ended up using was

(Get-WmiObject -Class Win32_OperatingSystem).caption

This returns (Exactly what I was looking for)



I added this as an alias so I do not have to type this in every time.
I had to make the function first and then alias that, using the command
itself did not work (It was trying to assign the alias to the caption
string object).

Note: There may be an easier way to do this, I will update if I find it.

function fget_os {(Get-WmiObject -Class Win32_OperatingSystem).caption}

Set-Alias getos fget_os


Done :)