Архив рубрики: linux

swap

 

mkswap - системная утилита UNIX-подобных операционных систем предназначенная для создания раздела или файла подкачки (свопинга).

1)  Для начала необходимо создать сам файл подкачки (/swap) необходимого объема (1GB) с помощью dd.

bash:

  1. dd if=/dev/zero of=/swap bs=1024 count=1024K

2) С помощью утилиты mkswap записываем в файл /swap системную информацию, которую операционная система будет использовать при работе.

bash:

  1. mkswap /swap

3)  Если Вы будете активировать SWAP вручную, т.е. каждый раз после загрузки операционной системы, то можно воспользоватся командой swapon

bash:

  1. swapon /swap

4)  Для того, чтоб SWAP автоматически активировался при загрузке операционной системы, необходимо указать его в автоматическую загрузку через /etc/fstab

bash:

  1. echo «/swap swap swap defaults 0 0″ | sudo tee -a /etc/fstab

link


Для проверки состояния SWAP:

bash:

  1. cat /proc/swaps

Для удаления SWAP файла необходимо деактивировать SWAP файл подкачки, затем удалить сам SWAP файл подкачки, а так же не забыть удалить запись из /etc/fstab

bash:

  1. swapoff /swap
  2. rm /swap

Внимание! Для создания или удаления SWAP файла подкачки необходимо иметь права суперпользователя или выполнять команды с помощью sudo 

List All Users In The System

link

/etc/passwd file contains one line for each user account, with seven fields delimited by colons. This is a text file. You can easily list users using the cat command as follows: $ cat /etc/passwd Sample outputs:

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
....
..
...

OR use pages as follows to view /etc/passwd file: $ more /etc/passwd $ less /etc/passwd Sample outputs:

Centos / RHEL /  Fedora / Debian / Ubuntu List Users Command
All fields are separated by a colon (:) symbol. Total seven fields exists. The first field is username. It is used when user logs in. It should be between 1 and 32 characters in length.

Task: Linux List Users Command

To list only usernames type the following awk command: $ awk -F':' '{ print $1}' /etc/passwd Sample outputs:

root
daemon
bin
sys
sync
games
man
lp
mail
news
....
..
..hplip
vivek
bind
haldaemon
sshd
mysql
radvd

A Note About System and General Users

Each user has numerical user ID called UID. It is defined in /etc/passwd file. The UID for each user is automatically selected using /etc/login.defs file when you use useradd command. To see current value, enter: $ grep "^UID_MIN" /etc/login.defs $ grep UID_MIN /etc/login.defs Sample outputs:

UID_MIN			 1000
#SYS_UID_MIN		  100

1000 is minimum values for automatic uid selection in useradd command. In other words all normal system users must have UID >= 1000 and only those users are allowed to login into system if shell is bash/csh/tcsh/ksh etc as defined /etc/shells file. Type the following command to list all login users:

 
## get UID limit ##
l=$(grep "^UID_MIN" /etc/login.defs)
## use awk to print if UID >= $UID_LIMIT ##
awk -F':' -v "limit=${l##UID_MIN}" '{ if ( $3 >= limit ) print $1}' /etc/passwd

To see maximum values for automatic uid selection in useradd command, enter: awk -F’:’ -v «min=${l##UID_MIN}» -v «max=${l1##UID_MAX}» ‘{ if ( $3 >= min && $3 <= max ) print $0}’ /etc/passwd$ grep "^UID_MAX" /etc/login.defs Sample outputs:

UID_MAX			60000

In other words all normal system users must have UID >= 1000 (MIN) and UID <= 60000 (MAX) and only those users are allowed to login into system if shell is bash/csh/tcsh/ksh etc as defined/etc/shells file. Here is an updated code:

 
## get mini UID limit ##
l=$(grep "^UID_MIN" /etc/login.defs)
 
## get max UID limit ##
l1=$(grep "^UID_MAX" /etc/login.defs)
 
## use awk to print if UID >= $MIN and UID <= $MAX   ##
awk -F':' -v "min=${l##UID_MIN}" -v "max=${l1##UID_MAX}" '{ if ( $3 >= min && $3 <= max ) print $0}' /etc/passwd

Sample outputs:

vivek:x:500:500::/home/vivek:/bin/bash
raj:x:501:501::/home/raj:/bin/ksh
ash:x:502:502::/home/ash:/bin/zsh
jadmin:x:503:503::/home/jadmin:/bin/sh
jwww:x:504:504::/htdocs/html:/sbin/nologin
wwwcorp:x:505:505::/htdocs/corp:/sbin/nologin
wwwint:x:506:506::/htdocs/intranet:/bin/bash
scpftp:x:507:507::/htdocs/ftpjail:/bin/bash
rsynftp:x:508:508::/htdocs/projets:/bin/bash
mirror:x:509:509::/htdocs:/bin/bash
jony:x:510:510::/home/jony:/bin/ksh
amyk:x:511:511::/home/amyk:/bin/ksh

/sbin/nologin is used to politely refuse a login i.e. /sbin/nologin displays a message that an account is not available and exits non-zero. It is intended as a replacement shell field for accounts that have been disabled or you do not want user to login into system using ssh. To filter /sbin/nologin, enter:

#!/bin/bash
# Name: listusers.bash
# Purpose: List all normal user accounts in the system. Tested on RHEL / Debian Linux
# Author: Vivek Gite <www.cyberciti.biz>, under GPL v2.0+
# -----------------------------------------------------------------------------------
_l="/etc/login.defs"
_p="/etc/passwd"
 
## get mini UID limit ##
l=$(grep "^UID_MIN" $_l)
 
## get max UID limit ##
l1=$(grep "^UID_MAX" $_l)
 
## use awk to print if UID >= $MIN and UID <= $MAX and shell is not /sbin/nologin   ##
awk -F':' -v "min=${l##UID_MIN}" -v "max=${l1##UID_MAX}" '{ if ( $3 >= min && $3 <= max  && $7 != "/sbin/nologin" ) "$_p"

Sample outputs:

vivek:x:500:500::/home/vivek:/bin/bash
raj:x:501:501::/home/raj:/bin/ksh
ash:x:502:502::/home/ash:/bin/zsh
jadmin:x:503:503::/home/jadmin:/bin/sh
wwwint:x:506:506::/htdocs/intranet:/bin/bash
scpftp:x:507:507::/htdocs/ftpjail:/bin/bash
rsynftp:x:508:508::/htdocs/projets:/bin/bash
mirror:x:509:509::/htdocs:/bin/bash
jony:x:510:510::/home/jony:/bin/ksh
amyk:x:511:511::/home/amyk:/bin/ksh

Finally, this script lists both system and users accounts:

 
#!/bin/bash
# Name: listusers.bash
# Purpose: List all normal user and system accounts in the system. Tested on RHEL / Debian Linux
# Author: Vivek Gite <www.cyberciti.biz>, under GPL v2.0+
# -----------------------------------------------------------------------------------
_l="/etc/login.defs"
_p="/etc/passwd"
 
## get mini UID limit ##
l=$(grep "^UID_MIN" $_l)
 
## get max UID limit ##
l1=$(grep "^UID_MAX" $_l)
 
## use awk to print if UID >= $MIN and UID <= $MAX and shell is not /sbin/nologin   ##
echo "----------[ Normal User Accounts ]---------------"
awk -F':' -v "min=${l##UID_MIN}" -v "max=${l1##UID_MAX}" '{ if ( $3 >= min && $3 <= max  && $7 != "/sbin/nologin" ) print $0 }' "$_p"
 
 
 
echo ""
echo "----------[ System User Accounts ]---------------"
awk -F':' -v "min=${l##UID_MIN}" -v "max=${l1##UID_MAX}" '{ if ( !($3 >= min && $3 <= max  && $7 != "/sbin/nologin")) print $0 }' "$_p"

Sample outputs:

----------[ Normal User Accounts ]---------------
vivek:x:500:500::/home/vivek:/bin/bash
raj:x:501:501::/home/raj:/bin/ksh
ash:x:502:502::/home/ash:/bin/zsh
jadmin:x:503:503::/home/jadmin:/bin/sh
wwwint:x:506:506::/htdocs/intranet:/bin/bash
scpftp:x:507:507::/htdocs/ftpjail:/bin/bash
rsynftp:x:508:508::/htdocs/projets:/bin/bash
mirror:x:509:509::/htdocs:/bin/bash
jony:x:510:510::/home/jony:/bin/ksh
amyk:x:511:511::/home/amyk:/bin/ksh
----------[ System User Accounts ]---------------
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
saslauth:x:499:499:"Saslauthd user":/var/empty/saslauth:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
apache:x:48:48:Apache:/var/www:/sbin/nologin
webalizer:x:67:67:Webalizer:/var/www/usage:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
memcached:x:498:496:Memcached daemon:/var/run/memcached:/sbin/nologin
squid:x:23:23::/var/spool/squid:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/cache/rpcbind:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin

processor and other information in Centos

link

Вот несколько простых команд для получения необходимой информации о системе.

Просмотр общей памяти 
# grep MemTotal /proc/meminfo
MemTotal: 515340 kB

Просмотр swap памяти

# grep SwapTotal /proc/meminfo
SwapTotal: 1048568 kB

Просмотр модели процессора

# grep "model name" /proc/cpuinfo
model name : Intel(R) Core(TM)2 Quad CPU Q8300 @ 2.50GHz

Просмотр дистрибутива и версии Linux

# cat /etc/issue 
CentOS release 5.4 (Final)
Kernel on an m

Просмотр версии ядра Linux

# uname -r
2.6.18-164.el5
Просмотр наличия установки необходимого пакета 
# rpm -q make
make-3.81-3.el5
Просмотр имени хоста 
# hostname 
alfa.alldba.ru

Лимит ресурсов

#ulimit -a

Лимиты для VPS

#cat /proc/user_beancounters

Проверка производительности и нагрузка сайта 100 запросов 5тью потоками 

#ab -n 100 -c 5 http://localhost/test.html 

sh auto fetsh and pull

sh fetch.sh

fetch.sh:

#!/bin/bash 
echo 
echo "*************************************"
echo "*                      stencilapp                                   *"
echo "*************************************"
cd e:/ops/yd/sites/stencilapp
git stash -a
git clean -xfd
rm -rf .git/FETCH_HEAD
git pull

Nginx, ошибка accept() failed (24: Too many open files)

link

Для одного хостинга картинок арендован выделенный сервер. На нем LAMP с nginx-фронтендом.
В один прекрасный день Nginx начинает периодически выдавать ошибку 500 при заходе на страницы.

В логах что-то похожее на

Цитата: 
[alert] 8668#0: accept() failed (24: Too many open files)


Это значит, превышен лимит количества одновременно открытых файлов. 

Решаем:
В конец файла /etc/security/limits.conf нужно добавить такие строки:

Цитата: 
* soft nofile 16384
* hard nofile 16384



В текущей консоли от рута (от судо не пашет) сделать

Цитата: 
ulimit -n 16384


Хотя это необязательно, если есть возможность перезагрузить сервер.

В /etc/nginx/nginx.conf прописать новое значение worker_connections, равное 16384 поделить на значение worker_processes.

Если не делали ulimit -n 16384, нужно выполнить перезагрузку, после чего проблема отступит.

1) Читаем логи. (Если пустые чиним)
2) Если после починки видна в логах ошибка accept() failed (24: Too many open files)
В конфиг nginx прописвыем(к примеру):

worker_processes 2;

worker_rlimit_nofile 16384;

events {
worker_connections 8192;
}


Исходя из статьи:

В /etc/nginx/nginx.conf прописать новое значение worker_connections, равное 16384 поделить на значение worker_processes.

how to fix phpMyAdmin session error

phpMyAdmin is great free web based PHP software to manage databases, tables, fields, users… and more. phpMyAdmin support MySQL, MariaDB, and Drizzle with the ability to execute SQL statements.

Unfortunately sometimes I get problem with phpMyAdmin, here is the error from phpMyAdmin on my centos Linux Server

phpMyAdmin – Error

To test and find out where is session.save path
http://wiki.phpmyadmin.net/pma/session.save_path

run this script on your web server

Here is the output i have

If the folder doesn’t exist, create one.

 

You may have to change ownership of the directly

 

 

Or just need to change the permissions to readable and writable for the directory

 

 

Note: /var/lib/php/session ownership and permissions well reverse back to root and not writable after a reboot. It’s a good idea to run chmod and chown @reboot so you don’t have to do it manually.

add this to your crontab

with the content (replace user:group to user/group which running apache/nginx web server)

htop

yum install epel-release
yum install htop

apache passenger

First install packages:

- for Ubuntu:

sudo apt-get install libcurl4-gnutls-dev
sudo apt-get install apache2-dev

- for CentOS (good tutorial):

yum install curl-devel httpd-devel 

or

yum install curl-devel apache2-devel 

After install gem:

gem install passenger

And then successfully configurate it:

sudo passenger-install-apache2-module