31 August 2007

Configuring Rails To Use Gmail’s SMTP Server

Nothing original here I am afraid.
I copied Google's cache from http://blog.pomozov.info/posts/how-to-send-actionmailer-mails-to-gmailcom.html


  1. Save the following code within your rails app in lib/smtp_tls.rb




require "openssl"
require "net/smtp"

Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if @started
check_auth_args user, secret, authtype if user or secret

sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
@socket = Net::InternetMessageIO.new(sock)
@socket.read_timeout = 60 #@read_timeout
#@socket.debug_output = STDERR #@debug_output

check_response(critical { recv_response() })
do_helo(helodomain)

if starttls
raise 'openssl library not installed' unless defined?(OpenSSL)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@socket = Net::InternetMessageIO.new(ssl)
@socket.read_timeout = 60 #@read_timeout
#@socket.debug_output = STDERR #@debug_output
do_helo(helodomain)
end

authenticate user, secret, authtype if user
@started = true
ensure
unless @started
# authentication failed, cancel connection.
@socket.close if not @started and @socket and not @socket.closed?
@socket = nil
end
end

def do_helo(helodomain)
begin
if @esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if @esmtp
@esmtp = false
@error_occured = false
retry
end
raise
end
end

def starttls
getok('STARTTLS') rescue return false
return true
end

def quit
begin
getok('QUIT')
rescue EOFError, OpenSSL::SSL::SSLError
end
end
end



  1. Add this code to config/environment.rb

    require “smtp_tls”

    ActionMailer::Base.smtp_settings = {
    :address => “smtp.gmail.com”,
    :port => 587,
    :authentication => :plain,
    :user_name => “someone@openrain.com”,
    :password => ’someonesPassword’
    }

  2. Use ActionMailer as normal.


30 August 2007

Linux 101


The (sad but real) truth is I am new to Linux, even if I have been using Unix systems (solaris based), back in 1995 at the university. My teachers were quite uncompetent and as my home pc was windows based, I did not learn as much as I could have done and forget little by little the few things I knew ...
As I have decided to use this blog as a personal public knowledge database, I have decided to post about all the simple commands I learn.

firefox, how to synchronise bookmarks

I am using both Linux Ubuntu and Windows XP on my laptop (with dual boot), I am using the foxmarks extenstion to keep my "Bookmarks Tool folder" synchronised. I kepp all my personal bookmarks on my del.icio.us

man

To quit, type "q"

vi

to edit a file: vi file_name.rb, then type "i" to edit
More commands on http://www.comptechdoc.org/os/linux/usersguide/linux_ugvi.html

To quit:
If you were editing the file, escape the edition mode with the escape key.

:q

To save:
:wq

sudo

To do things that required "root" privileges.

configuration : /etc directory


To add a folder to the PATH variable, the "best" seems to edit the file ~/.bashrc
gedit ~/.bashrc

and append at the end of the file:
PATH=$PATH:~/programs/scripts export PATH

Taken from http://ubuntuforums.org/showthread.php?t=269793&highlight=PATH

bash

When I start my machine for work, I end up launching more or less the same application. I wanted to write a quick script which allows to launch all these applications in one-click!
Reading http://www.mkssoftware.com/docs/man1/sh.1.asp, I found about the &

&

asynchronously executes the command that precedes it. This means that the shell just starts the command running and then immediately goes on to take new input, before the command finishes execution.


creating alias

gedit ~/.bashrc
Append alias at the end of the file:
alias ll='ls -l'

Locking the screen with the "key menu" is not cool!

I was looking for a software which would allow me to customize keyboard shortcuts and I came accross keytouch , which seems great but you have to configure your keyboard in order to use it.
I thought I could do that later and then share my work to the community ...
Oooops! There was a side effect, every time I hitted the "menu" key
, it was locking my screen! After 1 day of clumsy locking and having lost 30 minutes searching into ubuntu forums what was happening, I decided to uninstall keytouch. Bingo!
It was such an improductive hour! Next time, I won't spend more than 15 minutes on that kind of shits ...

I didn't know the name of this *&$·%· key, this is how does it look like:


The "menu key" or "application key" is on the right side

Killing process which belong to a certain user


ps -ef | grep process_name
skill -9 -u 'username' -c process_name

Deleting a directory (reccursively)


rm -Rf directory_path

Copying an entire directory

The following command will copy "src" inside "dest"

cp -R src/ dest/

uses the backslash ( ) for directories whose name contain spaces o

Example:
cp -R /windows/Program Files/Macromedia/ ~/.wine/Program Files/

Display hidden files (files starting with dot)

ls -a

Display the list of process running and ... KILL!

ps -ef
kill -9 id_process

Display the list of process running and their memory footprint


ps -eo pid,pmem,size,args --sort=-size

It shows every process ID with the percentage of memory used, the actual KB of memory used and the full command w/ command line options. And sorts everything by used memory.

Environements variables

Display all env variables:
env
Display one env variable
echo $LOGON
Assign a value to an env variable
export PATH=${PATH}:${ANT_HOME}/bin

Chmod reccursively

chmod -R ...
Check out the informations in http://www.ss64.com/bash/chmod.html

Copy files through ssh using scp

scp username@server.com:/path_to/files path_to_local_destination_file

Examples:-

scp myfile you@remote.machine.org:/userdisk/yourdir

Copy the file called ``myfile'' from the current directory to the directory called ``userdisk/yourdir'' belonging to the user ``you'' on the computer ``remote.machine.org''.

scp "you@remote.machine.org:/userdisk/yourdir/*" ./

Copy all files from the directory called ``userdisk/yourdir'' belonging to the user ``you'' on the computer ``remote.machine.org'' to the current directory. For further information see section 8.7.



Console commands

  • CTRL + R : will search in all the commands typed not only in the current session
  • cd - : to come back to previous folder
Process commands

before the comand:

nice

A nice value of −20 is the highest priority and 19 is the lowest priority. The default nice value for processes is inherited by its parent process, usually 0
nohup
enabling the command to keep running after the user who issues the command has logged out

'a command '&& notify-send 'Done'

will pop up when the command has finnished

Call another shell script:

source ~/another_bash.sh



Swap

My system uses a lot of swap and I have no idea of how to tell it to use the RAM when it's available ...
I've found this:

cat /proc/sys/vm/swappiness
60
The value of 60 is often the default on SuSE Linux systems. This value ranges from 0 (less likely to swap) to 100 (very likely to swap). I notice that by setting it to 10, the system uses much less swap memory than before.
/proc/sys/vm/swappiness
The above code will set the value temporarily. To set it permanently so that it takes effect on each boot, edit the /etc/sysctl.conf file and add the line:

vm.swappiness=10
Changing the value contained into swappiness should help you tuning how your system swap.

Setting up public key authentication over SSH


Every time I want to setup public key authentication over SSH, I have to look it up, and I've never found a simple guide, so here's mine.

Generate key on local machine

ssh-keygen -t rsa

It will ask you for a password but you can leave it blank.

Note you could also pick -t dsa if you prefer.

Ensure that the remote server has a .ssh directory

Make sure the server your connecting to has a .ssh directory in your home directory. If it doesn't exist you can run the ssh-keygen command above, and it will create one with the correct permissions.

Copy your local public key to the remote server

If your remote server doesn't have a file called ~/.ssh/authorized_keys2 then we can create it. If that file already exists, you need to append to it instead of overwriting it, which the command below would do:

scp ~/.ssh/id_rsa.pub remote.server.com:.ssh/authorized_keys2

To copy to an existing .ssh/authorized_keys (99% of time):
cat ~/.ssh/id_rsa.pub | ssh user_name@remote.machine.com 'cat >> .ssh/authorized_keys'

You may also be able to remove the exact known host with the following command via ssh on your local machine. Remember to replace mt-example.com with your own domain.

ssh-keygen -R mt-example.com 

Finding a file


Here's an example find command using a search criteria and the default action:
find / -name foo
will search the whole system for any files named foo and display them. More examples here.

Finding a file containing a string



For example search for a string called redeem reward in all text files located in /home/tom/*.txt directory, use
$ grep "redeem reward" /home/tom/*.txt

Task: Search all subdirectories recursively

You can search for a text string all files under each directory, recursively with -roption:
$ grep -r "redeem reward" /home/tom




Recursively remove .svn directories

find . -type d -name .svn | xargs rm -rf

How to exit a process



[18:29:18] … What about Ctrl + Z
[18:29:26] … ?
[18:29:39] Marco i: now write 'jobs
[18:29:40] … '
[18:29:41] … jobs
[18:29:52] : Stopped telnet localhost 11211
[18:30:01] : do: kill %1
[18:30:11] … It kills the first stopped job.
[18:30:18]: [1]+ Terminated telnet localhost 11211
[18:30:23] Marco Lazzeri: ok
[18:30:27] … now you're out
[18:30:33] Jean-Michel Garnier: OK, I will add this trick to my linux trick. Thanks again
[18:30:39] Marco i: but having ctrl + ] as font increaser is NOT good ; )
[18:31:00] … You know that with CTRL + Z you can stop jobs.
[18:31:21] … Then if you issue 'bg' you send it to background
[18:31:36] … While if you issue 'fg' you take it back to your screen: foreground.
[18:31:44] Jean-Michel Garnier: I have learned it today
[18:31:57] Marco i: It can be uself.
[18:31:59] … useful
[18:32:05] … especially when working on remote systems.
[18:32:16] … when you don't have graphical shell
[18:32:29] … or when opening more terminals is a waste of time

Remote control with vnc

vncviewer -fullscreen 192.168.2.23:0

If you want to quit vncviewer: Press 'F8' and select Quit viewer


RFormat an external USB hard drive to ext2


sudo umount /dev/sdb1
[sudo] password for jeanmichel:
jeanmichel@21x100:~$ mkfs.ext2 /dev/sdb1
mke2fs 1.40.2 (12-Jul-2007)
warning: 424 blocks unused.

Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
61166016 inodes, 122093568 blocks
6104699 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=0
3726 block groups
32768 blocks per group, 32768 fragments per group
16416 inodes per group
Superblock backups stored on blocks:

Tar / Untar a file

Tar:
tar czf /path/to/output/folder/filename.tar.gz /path/to/folder
Untar:
tar xvf tsung-1.2.1.tar.gz && rm tsung-1.2.1.tar.gz


CPU Usage

top

type "1" to see mutliple cups

Hard drive Usage


du -s * | sort -nr | head

How to check if an IP is denied from ssh acces


grep 88.6.173.50 /etc/hosts.deny

How to make multiple folders

You can make multiple folders in bash and other shells with {folder1,folder2} :

mkdir /usr/local/src/bash/{old,new,dist,bugs}

Which version of packages I have installed?

dpkg -l | grep openssl


Configure /etc/init.d

sudo sysv-rc-conf

provides a terminal GUI for managing "/etc/rc{runlevel}.d/"

Free space on hard drive

DF command reports how much free disk space is available for each mount you have. When executing DF, I like to use the -h option, which returns the output in a more readable format:

wtn@wtn2:~$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 7.5G 2.1G 5.1G 30% /

What time is it?

$ date

Thu Jul 17 08:30:46 GMT 2008

See What Version of a Package Is Installed on Ubuntu

dpkg -s

Is drive mounted?

if [ ! -d /backup/mydir ]; then
echo "drive not mounted"
fi

List processes with ports they use

netstat -nlp