Merge remote-tracking branch 'upstream/master'

Merging the upstream master
This commit is contained in:
Samir Madhavan 2015-11-28 14:15:35 +05:30
commit 107daa112a
18 changed files with 328 additions and 78 deletions

View File

@ -15,7 +15,7 @@ story](https://www.jitbit.com/alexblog/249-now-thats-what-i-call-a-hacker/)_:
> xxx: [`hangover.sh`](https://github.com/NARKOZ/hacker-scripts/blob/master/hangover.sh) - another cron-job that is set to specific dates. Sends automated emails like "not feeling well/gonna work from home" etc. Adds a random "reason" from another predefined array of strings. Fires if there are no interactive sessions on the server at 8:45am.
> xxx: (and the oscar goes to) [`fucking-coffee.sh`](https://github.com/NARKOZ/hacker-scripts/blob/master/fucking-coffee.sh) - this one waits exactly 17 seconds (!), then opens an SSH session to our coffee-machine (we had no frikin idea the coffee machine is on the network, runs linux and has SSHD up and running) and sends some weird gibberish to it. Looks binary. Turns out this thing starts brewing a mid-sized half-caf latte and waits another 24 (!) seconds before pouring it into a cup. The timing is exactly how long it takes to walk to the machine from the dudes desk.
> xxx: (and the oscar goes to) [`fucking-coffee.sh`](https://github.com/NARKOZ/hacker-scripts/blob/master/fucking-coffee.sh) - this one waits exactly 17 seconds (!), then opens a telnet session to our coffee-machine (we had no frikin idea the coffee machine is on the network, runs linux and has a TCP socket up and running) and sends something like `sys brew`. Turns out this thing starts brewing a mid-sized half-caf latte and waits another 24 (!) seconds before pouring it into a cup. The timing is exactly how long it takes to walk to the machine from the dudes desk.
> xxx: holy sh*t I'm keeping those
@ -37,22 +37,22 @@ GMAIL_PASSWORD=password
```
For Ruby scripts you need to install gems:
`gem install dotenv twilio gmail`
`gem install dotenv twilio-ruby gmail`
## Cron jobs
```sh
# Runs `smack-my-bitch-up.sh` daily at 9:20 pm.
20 21 * * * /path/to/scripts/smack-my-bitch-up.sh >> /path/to/smack-my-bitch-up.log 2>&1
# Runs `smack-my-bitch-up.sh` monday to friday at 9:20 pm.
20 21 * * 1-5 /path/to/scripts/smack-my-bitch-up.sh >> /path/to/smack-my-bitch-up.log 2>&1
# Runs `hangover.sh` daily at 8:45 am.
45 8 * * * /path/to/scripts/hangover.sh >> /path/to/hangover.log 2>&1
# Runs `hangover.sh` monday to friday at 8:45 am.
45 8 * * 1-5 /path/to/scripts/hangover.sh >> /path/to/hangover.log 2>&1
# Runs `kumar-asshole.sh` every 10 minutes.
*/10 * * * * /path/to/scripts/kumar-asshole.sh
# Runs `fucking-coffee.sh` hourly from 9am to 6pm.
0 9-18 * * * /path/to/scripts/fucking-coffee.sh
# Runs `fucking-coffee.sh` hourly from 9am to 6pm on weekdays.
0 9-18 * * 1-5 /path/to/scripts/fucking-coffee.sh
```
---

28
coffee/fucking.coffee Executable file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env coffee
username = 'name'
host = 'localhost'
port = '3000'
pass = '5555'
sh = require('child_process').execSync
# weekend
process.exit 0 if new Date().getDay() in [6, 0]
# no sessions
process.exit 0 unless new RegExp(username).test sh('who -q').toString()
conn = require('net').createConnection(port, host)
setTimeout ->
conn.write "#{pass}\nsys brew\n"
setTimeout ->
conn.end 'sys pour'
process.exit(0)
, 2 * 1000
, 1 * 1000
# alert
sh('say come here and take your fucking coffee')

View File

@ -1,8 +1,5 @@
#!/usr/bin/env ruby
# Skip on weekends
exit if Time.now.saturday? || Time.now.sunday?
# Exit early if no sessions with my username are found
exit unless `who -q`.include? ENV['USER']

View File

@ -1,8 +1,5 @@
#!/usr/bin/env ruby
# Skip on weekends
exit if Time.now.saturday? || Time.now.sunday?
# Exit early if sessions with my username are found
exit if `who -q`.include? ENV['USER']

View File

@ -1,12 +1,5 @@
#!/bin/sh -e
DAYOFWEEK=$(date +%u)
# Skip on weekends
if [ "$DAYOFWEEK" -eq 6 ] || [ "$DAYOFWEEK" -eq 7 ]; then
exit
fi
# Exit early if any session with my username is found
if who | grep -wq $USER; then
exit

View File

@ -14,8 +14,16 @@ kumars_email = 'kumar.a@example.com'
DB_NAME_REGEX = /\S+_staging/
KEYWORDS_REGEX = /sorry|help|wrong/i
def create_reply(subject)
gmail.compose do
to kumars_email
subject "RE: #{subject}"
body "No problem. I've fixed it. \n\n Please be careful next time."
end
end
gmail.inbox.find(:unread, from: kumars_email).each do |email|
if email.body[KEYWORDS_REGEX] && (db_name = email.body[DB_NAME_REGEX])
if email.body.raw_source[KEYWORDS_REGEX] && (db_name = email.body.raw_source[DB_NAME_REGEX])
backup_file = "/home/backups/databases/#{db_name}-" + (Date.today - 1).strftime('%Y%m%d') + '.gz'
abort 'ERROR: Backup file not found' unless File.exist?(backup_file)
@ -29,11 +37,3 @@ gmail.inbox.find(:unread, from: kumars_email).each do |email|
gmail.deliver(reply)
end
end
def create_reply(subject)
gmail.compose do
to kumars_email
subject "RE: #{subject}"
body "No problem. I've fixed it. \n\n Please be careful next time."
end
end

49
perl/fucking-coffee.pl Executable file
View File

@ -0,0 +1,49 @@
#!/usr/bin/perl
use strict;
use warnings;
use DateTime;
use YAML;
use Net::Telnet;
# Config
my $conf = Load( <<'...' );
---
coffee_machine_ip: 10.10.42.42
password: 1234
password_prompt: Password:
delay_before_brew: 17
delay: 24
...
# Skip on weekends
my $date = DateTime->now;
if ( $date->day_of_week >= 6 ) {
exit;
}
# Exit early if no sessions with my username are found
open( my $cmd_who, '-|', 'who' ) || die "Cannot pipe who command ". $!;
my @sessions = grep {
m/$ENV{'USER'}/
} <$cmd_who>;
close $cmd_who;
exit if ( scalar( @sessions ) == 0 );
sleep $conf->{'delay_before_brew'};
my $con = Net::Telnet->new(
'Host' => $conf->{'coffee_machine_ip'},
);
$con->watifor( $conf->{'password_prompt'} );
$con->cmd( $conf->{'password'} );
$con->cmd( 'sys brew' );
sleep $conf->{'delay'};
$con->cmd( 'sys pour' );
$con->close;

73
perl/hangover.pl Executable file
View File

@ -0,0 +1,73 @@
#!/usr/bin/perl
use strict;
use warnings;
use DateTime;
use SMS::Send;
use YAML;
# Config
my $conf = Load( <<'...' );
---
phone_numbers:
my_number: +15005550006
boss_number: +xxx
reasons:
- Locked out
- Pipes broke
- Food poisoning
- Not feeling well
...
my $date = DateTime->now;
# Skip on weekends
if ( $date->day_of_week >= 6 ) {
exit;
}
# Exit early if no sessions with my username are found
open( my $cmd_who, '-|', 'who' ) || die "Cannot pipe who command ". $!;
my @sessions = grep {
m/$ENV{'USER'}/
} <$cmd_who>;
close $cmd_who;
exit if ( scalar( @sessions ) == 0 );
# Load Twilio API config
open( my $env, '<', '../.env' ) || die "Cannot find .env file in project root.";
LINE: while ( my $line = <$env> ) {
next LINE unless ( $line =~ m/^(TWILIO[^=]+)=(.*)(?:[\n\r]*)/ );
$conf->{'env'}->{ $1 } = $2;
}
close $env;
# Randomize excuse
my $reason_number = int( rand( scalar( @{ $conf->{'reasons'} } ) ) );
my $sms_text = "Gonna work from home. ". $conf->{'reasons'}[ $reason_number ];
# Create an object. There are three required values:
my $sender = SMS::Send->new('Twilio',
_accountsid => $conf->{'env'}->{'TWILIO_ACCOUNT_SID'},
_authtoken => $conf->{'env'}->{'TWILIO_AUTH_TOKEN'},
_from => $conf->{'phone_numbers'}->{'my_number'},
);
# Send a message to me
my $sent = $sender->send_sms(
text => $sms_text,
to => $conf->{'phone_numbers'}->{'boss_number'},
);
# Did it send?
if ( $sent ) {
print "Sent message.\n";
} else {
print "Message failed.\n";
}

88
perl/kumar-asshole.pl Executable file
View File

@ -0,0 +1,88 @@
#!/usr/bin/perl
use strict;
use warnings;
use YAML;
use DateTime;
use Mail::Webmail::Gmail;
# Config
my $conf = Load( <<'...' );
---
kumar_mail: kumar.a@examle.com
database_regex: \S+_staging
keywords_regex: sorry|help|wrong
backup_path: /home/backups/databases/
...
$conf->{'database_regex'} = qr/ ( $conf->{'database_regex'} ) /x;
$conf->{'keywords_regex'} = qr/ ( $conf->{'keywords_regex'} ) /x;
my $date = DateTime->now->subtract(
'days' => 1
);
# Load GMail API config
open( my $env, '<', '../.env' ) || die "Cannot find .env file in project root.";
LINE: while ( my $line = <$env> ) {
next LINE unless ( $line =~ m/^(GMAIL[^=]+)=(.*)(?:[\n\r]*)/ );
$conf->{'env'}->{ $1 } = $2;
}
close $env;
my $gmail = Mail::Webmail::Gmail->new(
username => $conf->{'env'}->{'GMAIL_USERNAME'},
password => $conf->{'env'}->{'GMAIL_PASSWORD'},
encrypt_session => 1,
);
my $messages = $gmail->get_messages( label => $Mail::Webmail::Gmail::FOLDERS{ 'INBOX' } );
die "Cannot fetch emails: ". $gmail->error_msg();
MESSAGE: foreach my $message ( @{ $messages } ) {
unless (
( $message->{ 'new' } )
&& ( $message->{'sender_email'} eq $conf->{'kumars_email'} )
&& ( $message->{'body'} =~ m/$conf->{'keywords_regex'}/ )
&& ( $message->{'body'} =~ m/$conf->{'database_regex'}/ )
) {
print "Skipping mail from=[". $message->{'sender_email'}."] subject=[". $message->{'subject'} ."]\n";
next MESSAGE;
}
exit 1;
my $database = $1;
my $backup_file = $conf->{'backup_path'} . $database .'-'. $date->ymd() .'.gz';
unless ( -f $backup_file ) {
die 'Cannot find backup file=['. $backup_file ."]\n";
}
print 'Restoring database=['. $database .'] from day=['. $date->ymd() .'] from file=['. $backup_file ."]\n";
# Restore DB
system( 'gunzip -c '. $backup_file .' | psql '. $database );
die "Error while restoring the database=[". $database ."] from file=[". $backup_file ."]" if ( $? >> 8 );
# Mark as read, add label, reply
$gmail->edit_labels(
'label' => 'Database fixes',
'action' => 'add',
'msgid' => $message->{'id'}
);
$gmail->send_message(
'to' => $conf->{'kumars_email'},
'subject' => 'RE: '. $message->{'subject'},
'msgbody' => "No problem. I've fixed it. \n\n Please be careful next time.",
);
$gmail->edit_labels(
'label' => 'unread',
'action' => 'remove',
'msgid' => $message->{'id'}
);
}

72
perl/smack-my-bitch-up.pl Executable file
View File

@ -0,0 +1,72 @@
#!/usr/bin/perl
use strict;
use warnings;
use DateTime;
use SMS::Send;
use YAML;
# Config
my $conf = Load( <<'...' );
---
phone_numbers:
my_number: +15005550006
her_number: +xxx
reasons:
- Working hard
- Gotta ship this feature
- Someone fucked the system again
...
my $date = DateTime->now;
# Skip on weekends
if ( $date->day_of_week >= 6 ) {
exit;
}
# Exit early if no sessions with my username are found
open( my $cmd_who, '-|', 'who' ) || die "Cannot pipe who command ". $!;
my @sessions = grep {
m/$ENV{'USER'}/
} <$cmd_who>;
close $cmd_who;
exit if ( scalar( @sessions ) == 0 );
# Load Twilio API config
open( my $env, '<', '../.env' ) || die "Cannot find .env file in project root.";
LINE: while ( my $line = <$env> ) {
next LINE unless ( $line =~ m/^(TWILIO[^=]+)=(.*)(?:[\n\r]*)/ );
$conf->{'env'}->{ $1 } = $2;
}
close $env;
# Randomize excuse
my $reason_number = int( rand( scalar( @{ $conf->{'reasons'} } ) ) );
my $sms_text = "Late at work. ". $conf->{'reasons'}[ $reason_number ];
# Create an object. There are three required values:
my $sender = SMS::Send->new('Twilio',
_accountsid => $conf->{'env'}->{'TWILIO_ACCOUNT_SID'},
_authtoken => $conf->{'env'}->{'TWILIO_AUTH_TOKEN'},
_from => $conf->{'phone_numbers'}->{'my_number'},
);
# Send a message to me
my $sent = $sender->send_sms(
text => $sms_text,
to => $conf->{'phone_numbers'}->{'her_number'},
);
# Did it send?
if ( $sent ) {
print "Sent message.\n";
} else {
print "Message failed.\n";
}

View File

@ -1,17 +1,10 @@
#!/usr/bin/env python
import datetime
import sys
import subprocess
import telnetlib
import time
today = datetime.date.today()
# skip weekends
if today.strftime('%A') in ('Saturday', 'Sunday'):
sys.exit()
# exit if no sessions with my username are found
output = subprocess.check_output('who')
if 'my_username' not in output:

View File

@ -1,18 +1,11 @@
#!/usr/bin/env python
import datetime
import os
import random
from twilio.rest import TwilioRestClient
from time import strftime
import subprocess
today = datetime.date.today()
# skip weekends
if today.strftime('%A') in ('Saturday', 'Sunday'):
sys.exit()
# exit if sessions with my username are found
output = subprocess.check_output('who')
if 'my_username' in output:

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python
import datetime
import os
import random
from twilio.rest import TwilioRestClient
@ -8,13 +7,6 @@ import subprocess
import sys
from time import strftime
today = datetime.date.today()
# skip weekends
if today.strftime('%A') == 'Saturday' || today('%A') == 'Sunday':
sys.exit()
# exit if no sessions with my username are found
output = subprocess.check_output('who')
if 'my_username' not in output:

View File

@ -1,7 +1,6 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import telnetlib
import time
@ -13,10 +12,6 @@ COFFEE_MACHINE_PROM = 'Password: '
def main():
# Skip on weekends.
if datetime.date.today().weekday() in (0, 6,):
return
# Exit early if no sessions with my_username are found.
if not any(s.startswith(b'my_username ') for s in sh('who').split(b'\n')):
return

View File

@ -1,7 +1,6 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import random
from twilio import TwilioRestException
@ -18,10 +17,6 @@ LOG_FILE_PATH = get_log_path('hangover.txt')
def main():
# Skip on weekends.
if datetime.date.today().weekday() in (0, 6,):
return
# Exit early if any session with my_username is found.
if any(s.startswith(b'my_username ') for s in sh('who').split(b'\n')):
return

View File

@ -1,7 +1,6 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import random
from twilio import TwilioRestException
@ -18,10 +17,6 @@ LOG_FILE_PATH = get_log_path('smack_my_bitch_up.txt')
def main():
# Skip on weekends.
if datetime.date.today().weekday() in (0, 6,):
return
# Exit early if no sessions with my_username are found.
if not any(s.startswith(b'my_username ') for s in sh('who').split(b'\n')):
return

View File

@ -1,12 +1,5 @@
#!/bin/sh -e
DAYOFWEEK=$(date +%u)
# Skip on weekends
if [ "$DAYOFWEEK" -eq 6 ] || [ "$DAYOFWEEK" -eq 7 ]; then
exit
fi
# Exit early if no sessions with my username are found
if ! who | grep -wq $USER; then
exit

View File

@ -1,10 +1,7 @@
#!/usr/bin/env ruby
# Skip on weekends
exit if Time.now.saturday? || Time.now.sunday?
# Exit early if no sessions with my username are found
exit if `who -q`.include? ENV['USER']
exit unless `who -q`.include? ENV['USER']
require 'dotenv'
require 'twilio-ruby'