Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Tuesday, November 27, 2012

How to set default session timeout in Linux

My DC operation guys access Linux servers on a daily basis but somehow they never remember to log out. This is a security risk as anyone could gain access to the open console and create caos.
Today, yet again I’m forced to play the bad guy by dummy proofing my Linux servers by implementing default timeout for user sessions.
Bash and Korn both support the TMOUT variable which I will use to set the default timeout.
The etc/.bashrc file will apply the timeout system wide but if you need it to be user specific then modify the ~/.bashrc file instead.
Here’s how it’s done.
echo "TMOUT=300 >> /etc/bashrc
echo "readonly TMOUT" >> /etc/bashrc
echo "export TMOUT" >> /etc/bashrc
Log off, start a new session and wait for 5 minutes. Your session should terminate

How to keep your Linux session alive

Recently I wrote about implementing session timeouts on Linux. For admin’s who know what they are doing(most times) this can sometimes be an annoying experience.
There’s a simple noop script over at bashcurescancer to help work around session timeouts. This will work for ssh and also the default virtual consoles.


Watch noop in action.



Source: BashCuresCancer

How to change the system date in Linux

A friend needed help changing the system date on his Linux box today. This is usually a simple task for Linux users but newbies tend to get confused by the "date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]" line in the man page.
To simplify, this is how you do it.
Set the current date to April 7 2008 8:42:45pm.
The easy way,
#date -s "7 April 2008 20:42:45"
The harder way,
#date 040720422008.45
The break down: MM DD hh mm YYYY ss
MM = month = 04
DD = day = 07
hh = hour = 20
mm = minute = 42
YYYY = year = 2008
ss = second = 450

sample output,
[root@klmsyslog01p ~]# date -s "7 April 2008 20:42:45"
Mon Apr 7 20:42:45 MYT 2008
[root@klmsyslog01p ~]#

[root@kmmserver01p ~]# date 040720422008.45
Mon Apr 7 20:42:45 MYT 2008
[root@kmmserver01p ~]#

Google Earth for Linux

A spanking new release of Google Earth is out. The latest 4.3 release comes with Photo Realistic 3D modeling for buildings, “Swoop navigation” for an improved navigation experience, “Light and shadow” to catch sunrise and sunset from anywhere and finally the popular “Street View” which was previously a Google Maps only feature.
Now something to excite Linux users, Google Earth is now available for Linux. Not on WINE as but as a native application based on Qt and openGL. I’m yet to try it but for those who have I have heard nothing but good reviews with some minor glitches.
However Google Earth for Linux currently only supports the i386 architecture and seems to only work with 32bit processors.
The embedded video speaks for itself.
Download the latest Google Earth

How to limit ssh access to specific users or groups

Its sometimes necessary to limit who has access to a server via SSH. Most Linux security hardening checklist today require this to be enforced.
Fortunately this can be easily done with openSSH. Just edit the /etc/ssh/sshd_config file and add the desired directives shown below. You don’t need them all, just use what suits you needs.
openSSH provides 4 directives, AllowUsers, AllowGroups, DenyUsers and DenyGroups
AllowUsers buddy john doe
Only users buddy, john and doe will be able to log in via ssh.
AllowGroups sysadmin bkpadmin
Only users within groups sysadmin and bkpadmin will be able to log in via ssh.
DenyUsers rambo tina
This is the opposite of AllowUsers. All users except for rambo and tina will be able to log in via ssh.
DenyGroups hr payroll
This is the opposite of AllowGroups. All groups except for hr and payroll will be able to log in via ssh.

How to send a process to the background

Sending a process to the background in Linux is quite easy. All you need is bg, fg, &, and ctrl+Z ( ^Z ).
For this example I will use a simple bash script test.sh I put together to print “Test” every 5 seconds.
#!/bin/bash
#This script will print "Test" every 5 seconds
#
while [ true ]
do
echo "Test at `date`"
sleep 5
done
#End

Now let’s see how it’s done.
[user@abubu root]$./test.sh &
This starts test.sh and sends it to the background. You will be back at shell but should see the “Test” message every 5 seconds.
[user@abubu root]$jobs
[1]+ Running ./test.sh &

The jobs command will print all the background processes. Each process is represented by a number to it’s left. For example, tesh.sh is represented by 1.
[user@abubu root]$fg 1
The fg command will send the test.sh process to the foreground and return control to the shell.
[user@abubu root]$ ./test.sh (hit ctrl+Z (^Z) now)
Test at Tue Jun 3 15:11:38 MYT 2008
[1]+ Stopped ./test.sh

The test.sh process is temporarily suspended.
[user@abubu root]$bg 1
The bg command will send test.sh to the background.
[user@abubu root]jobs
[1]+ Running ./test.sh &

The jobs command will print all the background processes. Each process will be represented by a number to it’s left. tesh.sh is represented by 1.
[user@abubu root]$fg 1
The fg command will send the test.sh process to the foreground and return control to the shell.
That’s it.

How to add route in Linux

To view the current routing table run “route -n
[root@klmppswdr01p ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
10.41.42.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
10.41.41.0 10.41.42.8 255.255.255.0 UG 0 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
0.0.0.0 10.41.42.1 0.0.0.0 UG 0 0 0 eth0

To add a route refer to the command below.
"route add -net 10.41.41.0 netmask 255.255.255.0 gw 10.41.42.8"
To delete a route refer to the command below.
"route del -net 10.41.41.0 netmask 255.255.255.0 gw 10.41.42.8"
The routing information above is not persistent across reboots. After a reboot, the routing information will be lost and you need to add them in again.
To make the routing information persistent, add the “route add” line as seen above into the /etc/rc.local file.
Sample /etc/rc.local file.
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
route add -net 10.41.41.0 netmask 255.255.255.0 gw 10.41.42.8

How To Execute Linux commands from Windows

Most of the time, users are having a Windows Machine on their desk or laptop. Normally, we want to perform a full scale data retrieval from our Linux servers in the DC, where we don’t have a trusted Linux server to manage it….the answer to it is use “PLINK” utility.
Plink comes together with the Putty…
A simple example of usage is:
C:> plink USERNAME@SERVERNAME ‘YOUR-LINUX-COMMAND’
If you have a dozen of servers…then you probably want to write a batch script in Windows to loop through a list of servers and mention the list of commands juz like what i did…..
Here a typical windows batch script:
@echo off
for / f “tokens=*” %%A in (your-server-list.txt) ( C:pathtoplink.exe user@server -w YOUR-PASSWORD -m linuxcommandscript > YOUR_OUTPUT_FILE.txt)
There you go, i did this for my sar report data collection for root cause analysis and infrastructure load analysis….keying in a password wif every darn login is impractical and yet you dont want to generate a security key for the servers.

How to reset the root password for MySQL

It happens, you set a super complicated password for your MySQL root account and 2 months down the road forget what it was.
Here’s how you’d fix that.
1. Stop your current MySQL database if it is running
root@abubu# service mysqld stop
2. Start MySQL in safe mode and bypass reading the privilege table.
root@abubu# mysqld_safe --skip-grant-tables
3. Reset your root password MySQL console. If it goes well you will not need to key in a password.
root@abubu# mysql -u root mysql
mysql> update user set Password=PASSWORD('new-password');
mysql> flush privileges;
mysql exit;

4. Kill the MySQL process and restart MySQL normally.

How to build a local DNS caching server

Being in Malaysia we are gifted with superior Internet speeds. NOT!!
Services like openDNS are awesome but the lag between us and them often results in sluggish performance anyways.
One way to improve performance is to use local DNS servers. I don’t use Streamyx’s DNS servers because they SUCK!!. TIME’s DNS servers are ok but I still prefer openDNS.
To improve performance, I put together a local DNS caching-only server that forwards to openDNS. Now I have openDNS with lighting fast response.
Let’s walk though the steps to get your own local DNS caching-only server setup. I’m using openSUSE 11 so the steps might vary depending on your distro.
1. Install BIND
pandora:~ # zypper in bind
2. Edit /etc/named.conf
pandora:~ # vi /etc/named..conf
Uncomment the forwarders section. Update the default values with the values below.
forwarders { 208.67.222.222; 208.67.220.220; };

forward only;

Add the line ” forward only; ” This will tell BIND to only forward to the forwarders and not the ROOT servers.
3. Start the service.
To have the service start automatically run ” chkconfig named on
pandora:~ # service named start
4. Let’s make sure your caching server is running fine.
pandora:~ # nslookup google.com localhost
Server:         localhost
Address:        127.0.0.1#53

Non-authoritative answer:
Name:   google.com
Address: 64.233.167.99
Name:   google.com
Address: 72.14.207.99
Name:   google.com
Address: 64.233.187.99


pandora:~ # nslookup yahoo.com localhost
Server:         localhost
Address:        127.0.0.1#53

Non-authoritative answer:
Name:   yahoo.com
Address: 68.180.206.184
Name:   yahoo.com
Address: 206.190.60.37

5. Update your /etc/resolv.conf file.
This will tell your system to use the local DNS server which we just setup instead of the external ones.
Add the lines below to the file.
nameserver 127.0.0.1
nameserver 127.0.0.2

That’s it. You now have local DNS caching. Enjoy!!

My /etc/named.conf file. Only the lines I changed.
#forwarders { 192.0.2.1; 192.0.2.2; };
forwarders { 208.67.222.222; 208.67.220.220; };

# Enable the next entry to prefer usage of the name server declared in
# the forwarders section.
#forward first;
forward only;

VLC media player 0.9.2

VLC media player 0.9.2
VLC media player 0.9.2
The best media player in my book, VLC has a new version out. Like WL it’s my player of choice on both my Linux and Windows machines.
Read the changelog while you download the installer.

How to find your Ubuntu version

2 easy ways find out what version of Ubuntu you’re running.
First option,
cat the /etc/issue file.
danny@family-desktop:/etc$ cat /etc/issue
Ubuntu 8.04.1 n l

Second option
cat the /etc/lsb-release file.
danny@family-desktop:/etc$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=8.04
DISTRIB_CODENAME=hardy
DISTRIB_DESCRIPTION="Ubuntu 8.04.1"

or
run the lsb_release command with the “-a” switch.
danny@family-desktop:/etc$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 8.04.1
Release:        8.04
Codename:       hardy

How to give someone root access in Linux

Giving someone root access in linux is easy. Why would someone need to be root I don’t know but this is how you do it using the usermod command.
To add root access
[root@abika root]# id sys_admin
uid=508(sys_admin) gid=508(sys_admin) groups=508(sys_admin)
[root@abika root]# usermod -G root sys_admin
[root@abika root]# id sys_admin
uid=508(sys_admin) gid=508(sys_admin) groups=508(sys_admin),0(root)

To remove root access.
[root@abika root]# usermod -G sys_admin sys_admin
[root@abika root]# id sys_admin
uid=508(sys_admin) gid=508(sys_admin) groups=508(sys_admin)

cannot allocate memory error

Had a weird memory error my Linux servers at work today. These were heavy duty machines running  heavy jobs throughout the day. /var/log/messages kept reporting that the kernel had no more memory to process new jobs. Most of the errors read ” cannot allocate memory ”
Some digging around later we found the fix. Kernel 2.6 has a new parameter “min_free_kbytes” which allows it to reserve a dedicated amount of memory for itself to process jobs. This kept the kernel from choking up when the servers were faced with sudden spikes in heavy jobs.
I set my server’s  “min_free_kbytes” to “4096″ kbytes which was the recommended value. It’s more of a trial and error configuration so I’ll have to monitor the server over a period of time and increase the value if needed till I hit the sweet spot.
How to set it?
To have the new value take effect immediately, edit the “/proc/sys/vm/min_free_kbytes” file. Remember!, reboot and the changes will be forgotten.
echo "4096" > /proc/sys/vm/min_free_kbytes
To have it permanent, add “vm.min_free_kbytes=65536″ to the /etc/sysctl.conf file.
echo "vm.min_free_kbytes=4096" >> /etc/sysctl.conf

Get your PID with $$

“$$” is a useful Linux variable you could use in your script to get it’s PID. The “$$” variable always holds the PID of the executing process.
Why do you need it? Maybe to check if the script is already running? This is what I normally use it for.
Sample Script;
#!/bin/bash
echo "My PID is $$"
sleep 2

Sample Output;
[root@keke ~]# ./test1.sh
My PID is 8909

System uptime with uptime

Want to know how long your Linux box has been up for?
Simple, just run the “uptime” command and you will be rewarded with the answer plus a bit more.
8:58pm  up  19:54,  1 user,  load average: 0.47, 0.62, 0.35
Above is the typical reply from uptime. On the left is the current time, followed by the system’s uptime, logged in users and finally the system’s load average.
Sample output;
danesh@pandora:~> uptime
8:58pm  up  19:54,  1 user,  load average: 0.47, 0.62, 0.35

Simple sort with the sort command

You can easily sort your outputs in Linux using the “sort” command. Simply pipe “|” your output to a “sort” command and you should see the sorted results.
See sample usage below. This is just to start off, I’ve cover more in future posts.
[root@hantu ~]# cat numbers
5
4
3
2
1
0
6
7
8
9

[root@hantu ~]# cat numbers | sort
0
1
2
3
4
5
6
7
8
9

[root@hantu ~]# cat numbers | sort -r
9
8
7
6
5
4
3
2
1
0

Happy sorting!!

Reload you /etc/inittab file

You made changes to your /etc/inittab file but can’t effort any downtime.
There’s a simple trick to reload and apply changes in your /etc/inittab file without a reboot.
Run “init q” or “init Q”
[root@snoopy ~]# init q
[root@snoopy ~]#
[root@snoopy ~]# init Q
[root@snoopy ~]#

Download with cURL

Here’s how to download a file using cURL.
curl -O [full url to file]
curl -O http://downloads.wordpress.org/plugin/simple-tags.1.6.6.zip
Sample Output;
[root@kmon01 bin]# curl -O http://downloads.wordpress.org/plugin/simple-tags.1.6.6.zip
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 585k 0 585k 0 0 95317 0 --:--:

How to find the number of physical CPUs in Linux

With multicore CPUs it’s easy for newbies to get confused when faced with questions like;
1. How many physical CPUs does the server have?
2. How many cores on each CPU? Duo/Quad
In Linux it’s actually quite easy to get this info.
You could go through the /var/log/dmesg file or the /proc/cpuinfo file. For this tutorial we’ll look at the /proc/cpuinfo file.
Physical CPU count?
Run “cat /proc/cpuinfo | grep “physical id” | sort | uniq | wc -l”.
[root@bender ~]# cat /proc/cpuinfo | grep “physical id” | sort | uniq | wc -l
2
How many cores?
Runcat /proc/cpuinfo | grep “cpu cores” | uniq”.
[root@kmigb000 ~]# cat /proc/cpuinfo | grep “cpu cores” | uniq
cpu cores       : 2
2 mean that each physical CPU has 2 cores on it. If cpu cores was 1 then the CPU’s single core.
How many virtual processors?
Run “cat /proc/cpuinfo | grep “^processor”"
[root@bender ~]# cat /proc/cpuinfo | grep “^processor”
processor       : 0
processor       : 1
processor       : 2
processor       : 3
That’s about right, 2 physical CPUs x 2 cores each = 4 virtual processeors.
However, it’s a bit different for HT (Hyper-Threading). If you get cpu core = 1 but the virtual processors = 2 then the CPU’s running HT. HT will only work with the SMP kernel.