Learning MySQL / PostgreSQL and other stuff

Just somewhere to keep my notes while I'm playing.

Thursday, January 16, 2020

Compiling Python

Python is great in that you can extend the language using pip to download libraries, but if you want to run your code on a number of servers, you have to ensure that they all have the required libraries.

One way around this is to compile your code so that it runs native.  The example below reads data from a Mongo database and prints it in a pretty format.

jinkersont@testdockerhost:~/python$ cat Mongo.py
import pymongo
import pprint

from pymongo import MongoClient
muser = "dba"
mpassword = "haha"
mhost = "mongodb1.hehe.hoho"
mport = 27017
uri = "mongodb://%s:%s@%s:%s" % ( muser, mpassword, mhost, mport )
client = MongoClient(uri)
db = client['evergreen']
print db.list_collection_names()
collection = db['customers']
pprint.pprint(collection.find_one())
jinkersont@testdockerhost:~/python$

To run this we require the pymongo and pprint libraries to be installed.
apt install python-pip
pip install pymongo pprint
The output looks like this:
jinkersont@testdockerhost:~/python$ python Mongo.py
[u'customers']
{u'_id': ObjectId('5df8ed88d819a6f218b58bc9'),
 u'age': 25.0,
 u'cars': [u'Audi R8'],
 u'name': u'Honey'}
jinkersont@testdockerhost:~/python$

You can compile this code using pyinstaller
pip install pyinstaller
pyinstaller --onefile Mongo.py
Then you can run the code using:

jinkersont@testdockerhost:~/python$ file dist/Mongo
dist/Mongo: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 2.6.32, BuildID[sha1]=294d1f19a085a730da19a6c55788ec08c2187039, stripped
jinkersont@testdockerhost:~/python$ dist/Mongo
[u'customers']
{u'_id': ObjectId('5df8ed88d819a6f218b58bc9'),
 u'age': 25.0,
 u'cars': [u'Audi R8'],
 u'name': u'Honey'}
jinkersont@testdockerhost:~/python$





Friday, June 21, 2019

Am I running on a VM?

This is a regular question - have I logged in to a physical linux server or is this a virtual machine?

One simple way of finding this out (if you have root access) is to check the Chassis in dmidecode. Here are a few examples:

myuser@myopennebulahost:~$ sudo dmidecode -s chassis-manufacturer
Dell Inc.
myuser@myopennebulahost:~$

myuser@buildserver:~$ sudo dmidecode -s chassis-manufacturer
HP
myuser@buildserver:~$

myuser@apacheserver:~$ sudo dmidecode -s chassis-manufacturer
QEMU
myuser@apacheserver:~$

We can see that the OpenNebula server is a Dell, and the build server is an HP. But the Apache server is QEMU, which is a common virtualization hardware emulator. Clearly the Apache server is a VM.

Edit:
I've noticed that some Red hat VMs return Red Hat, not QEMU
[root@freepbx ~]# dmidecode -s chassis-manufacturer
Red Hat

[root@freepbx ~]#

Thursday, January 3, 2019

SELinux

Install the following packages:
apt-get install selinux-basics selinux-policy-default auditd

vi /etc/selinux/config and set to enforcing



Wednesday, May 2, 2018

My bread recipe

Just leaving this here so that I can find it again.

Ingredients
  • 2 Co-op  yeast sachets
  • 450ml (3/4 pint) warm water
  • 700g (1.5lb) Co-op Strong white bread flour
  • 1 heaped teaspoon of salt
  • 3 heaped teaspoons of caster sugar
  • 40 grams of butter or equiv
  • Milk to glaze
Requires
  • Mixing bowl
  • Knife 
  • Two baking tins
  • Baking parchment

Method:
  1. Mix yeast, flour, salt and sugar in a large mixing bowl.
  2. Rub in the butter
  3. Add water and mix in using a knife until it is workable
  4. Tip out on to a lightly floured work surface and need for 15 minutes until it is stretchy
  5. Return to bowl, cover and leave in a warm room for 1 hour to rise.
  6. Grease your baking tins and line with baking parchment. 
  7. Heat oven to 220C
  8. Tip out the risen dough on to the work surface and need for a further 5 minutes. 
  9. Divide the dough in two and form rough loaf shapes, place in the lined baking tins.
  10. Cover and return to warm room for 15 minutes to prove.
  11. Cut a slit length-ways in each loaf and glaze with milk
  12. Bake for 35 minutes until golden brown. Check that the bread is cooked by tapping the bottom of the loaf, it should sound hollow.
  13. Allow to cool on a baking rack.

Tuesday, July 12, 2016

The full Coin Flip Porgram

I got the Coin Flip program to work! Note that there are a few methods in here that I have implemented but not used, this is fairly normal. So for instance when writing the Coin class, it seemed obvious to be able to turn a coin over, not just flip it, but I don't need that right now.

require 'optparse'
class Coin
  attr_reader :face, :value
  @@FaceRange = [0, 1]
  @@ValidValues = [1, 2, 5, 10, 20, 50, 100, 200]
  @@prng = Random.new # Pseudo-random Number Generator
  # Default Face to an illegal value so that it will flip the coin
  def initialize (value=10, face=-1) # CONSTRUCTOR
    self.value = value
    self.face = face
  end
  def face= (new_face)        # Set a valid face
    @face ||= 0 # default
    if @@FaceRange.include? new_face
      @face = new_face
    else
      self.flip
    end
  end
  def value= (new_value)      # Set a valid value
    @value ||= 1 # default
    @value = new_value if @@ValidValues.include? new_value
  end
  def set_face (new_face)     # Set face to a chosen value
     @face = new_face if [0, 1].include? new_face
  end
  def turn                    # Turn the coin over
     @face = (@face + 1).modulo(2)
  end
  def flip                    # Flip the coin
    @face = @@prng.rand(0..1)
  end
  def to_s # Over-ride the to_s method inherited from the Object class
    "Value is #{@value} Face is #{@face}"
  end
end

class CList
  attr_reader :size
  def initialize (size=10)
    @size = size
    @coins = []
    (1..size).each do |i| 
      @coins.push(Coin.new)
    end
  end
  def flip
    @coins.each do |coin|
      coin.flip
    end
  end
  def countheads
    heads = 0
    @coins.each do |coin|
      heads += 1 if coin.face == 1
    end
    heads
  end
  def to_s
    @coins.each do |coin|
      puts coin
    end
    "Total #{@coins.length}"
  end
end

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: clist.rb [options]"

  opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
    options[:verbose] = v
  end
  opts.on("-c", "--coins [CCOUNT]", "Number of coins to flip") do |c|
    options[:count] = c.to_i
  end
  opts.on("-f", "--flips [FCOUNT]", "Number of flips") do |f|
    options[:flips] = f.to_i
  end
end.parse!

ccount = options[:count] # Number of coins
fcount = options[:flips] # Number of flips

puts "Flipping a row of #{ccount} coins #{fcount} times"

my_list = CList.new(ccount)
hoccurs = Array.new(ccount)
(0..hoccurs.length).each { |i| hoccurs[i] = 0 } # Zero Array
(1..fcount).each do 
  my_list.flip
  hoccurs[my_list.countheads] += 1
end

(0..hoccurs.length-1).each do |i|
  times="times"
  times="time" if hoccurs[i] == 1
  puts "Flipped #{i} heads #{hoccurs[i]} #{times}" if hoccurs[i] > 0
end
Here is how to run it: If we want 10 coins and 40 flips:

$ ruby clist.rb -c 10 -f 40
Flipping a row of 10 coins 40 times
Flipped 2 heads 2 times
Flipped 3 heads 4 times
Flipped 4 heads 10 times
Flipped 5 heads 10 times
Flipped 6 heads 9 times
Flipped 7 heads 5 times

tjinkers@TJINKERS-LAP ~/ruby
$

But it's much more fun with bigger numbers than that

Learning Ruby - First Object

Learning how to construct an object in Ruby, this is what I have so far.

class Coin
  attr_reader :face, :value
  @@FaceRange = [0, 1]
  @@ValidValues = [1, 2, 5, 10, 20, 50, 100, 200]
  @@prng = Random.new # Pseudo-random Number Generator
  # Default Face to an illegal value so that it will flip the coin
  def initialize (value=10, face=-1) # CONSTRUCTOR
    self.value = value
    self.face = face
  end
  def face= (new_face)        # Set a valid face
    @face ||= 0 # default
    if @@FaceRange.include? new_face
      @face = new_face
    else
      self.flip
    end
  end
  def value= (new_value)      # Set a valid value
    @value ||= 1 # default
    @value = new_value if @@ValidValues.include? new_value
  end
  def set_face (new_face)     # Set face to a chosen value
     @face = new_face if [0, 1].include? new_face
  end
  def turn                    # Turn the coin over
     @face = (@face + 1).modulo(2)
  end
  def flip                    # Flip the coin
    @face = @@prng.rand(0..1)
  end
  def to_s # Over-ride the to_s method inherited from the Object class
    "Value is #{@value} Face is #{@face}"
  end
end

coin1 = Coin.new(20, 1)
puts coin1.face, coin1.value
puts coin1
coin1.set_face(0)
puts coin1

coin2 = Coin.new(50, 0)
puts "Coin 2 is #{coin2}"
coin2.set_face(0)
puts "Coin 2 is #{coin2}"
puts "Turn it"
coin2.turn
puts "Coin 2 is #{coin2}"
puts "Turn it"
coin2.turn
puts "Coin 2 is #{coin2}"

puts "Flip it"
coin2.flip
puts "Coin 2 is #{coin2}"
puts "Flip it"
coin2.flip
puts "Coin 2 is #{coin2}"
puts "Flip it"
coin2.flip
puts "Coin 2 is #{coin2}"
puts "Turn it"
coin2.turn
puts "Coin 2 is #{coin2}"

coin3 = Coin.new(5)
puts "Coin 3 is #{coin3}"

coin4 = Coin.new
puts "Coin 4 is #{coin4}"
puts "Flip it"
coin4.flip
puts "Coin 4 is #{coin4}"


$ ruby  coins2.rb
1
20
Value is 20 Face is 1
Value is 20 Face is 0
Coin 2 is Value is 50 Face is 0
Coin 2 is Value is 50 Face is 0
Turn it
Coin 2 is Value is 50 Face is 1
Turn it
Coin 2 is Value is 50 Face is 0
Flip it
Coin 2 is Value is 50 Face is 1
Flip it
Coin 2 is Value is 50 Face is 1
Flip it
Coin 2 is Value is 50 Face is 1
Turn it
Coin 2 is Value is 50 Face is 0
Coin 3 is Value is 5 Face is 1
Coin 4 is Value is 10 Face is 1
Flip it
Coin 4 is Value is 10 Face is 0

tjinkers@TJINKERS-LAP ~/ruby
$



Monday, August 10, 2015

Perl: Am I Root?

Testing to see if you are running with root privileges is straight-forward in Perl. Here is some sample code:

[tjinkers@ebl-oel6vm1 perl]$ cat ./testroot.pl
#!/usr/bin/perl

if ( $< eq 0 ){
   print "I'm root\n";
} else {
   print "Not root\n";
}
[tjinkers@ebl-oel6vm1 perl]$ ./testroot.pl
Not root
[tjinkers@ebl-oel6vm1 perl]$ sudo ./testroot.pl
I'm root
[tjinkers@ebl-oel6vm1 perl]$

As the saying goes, "That was easy!"


And the follow-up question - how do you check when using Bash
# Make sure only root can run our script
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" 1>&2
exit 1
fi