owncloud

ownCloud — это свободное и открытое веб-приложение для синхронизации данных, общего доступа к файлам и удалённого хранения документов в «облаке».

Предполагается, что установлена связка nginx, mariadb и php-fpm.

# yum install owncloud
# yum install memcached php56w-pecl-apcu redis php56w-pecl-redis
# systemctl start memcached
# systemctl enable memcached
# systemctl start redis
# systemctl enable redis

Проверяем:

[root@ring var]# netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address  Foreign Address State PID/Program name
tcp        0      0 0.0.0.0:11211  0.0.0.0:*       LISTEN 19000/memcached
tcp        0      0 127.0.0.1:6379 0.0.0.0:*       LISTEN 18714/redis-server
udp        0      0 0.0.0.0:11211  0.0.0.0:*              19000/memcached

Чтобы убедиться, что экземпляр Memcached прослушивает локальный интерфейс 127.0.0.1, нужно проверить настройку по умолчанию в конфигурационном файле /etc/sysconfig/memcached, а также отключить прослушиватель UDP. Эти действия защитят сервер от атак типа «отказ в обслуживании».

После установки правим:

# cat /etc/sysconfig/memcached 
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="256"
OPTIONS="-U 0 -l 127.0.0.1"

Настройки vhost nginx:

$ cat /etc/nginx/sites-available/cloud.example.com

upstream php-handler {
 #server 127.0.0.1:9000;
 server unix:/var/run/php-fpm/php-fpm.cloud.example.com.sock;
 }

server {
 listen 80;
 server_name cloud.example.com;

# For Lets Encrypt, this needs to be served via HTTP
 location /.well-known/acme-challenge/ {
 root /var/www/html/owncloud; # Specify here where the challenge file is placed
 }

# enforce https
 location / {
 return 301 https://$server_name$request_uri;
 }
 }

server {
 listen 443 ssl http2;
 server_name cloud.example.com www.cloud.example.com;

 add_header X-Content-Type-Options nosniff;
 add_header X-Frame-Options "SAMEORIGIN";
 add_header X-XSS-Protection "1; mode=block";
 add_header X-Robots-Tag none;
 add_header X-Download-Options noopen;
 add_header X-Permitted-Cross-Domain-Policies none;


 include /etc/nginx/conf.d/ssl.conf;

# Path to the root of your installation
 root /var/www/html/owncloud/;
 index index.php;

location = /robots.txt {
 allow all;
 log_not_found off;
 access_log off;
 }

 # The following 2 rules are only needed for the user_webfinger app.
 # Uncomment it if you're planning to use this app.
 #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
 #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last;

location = /.well-known/carddav {
 return 301 $scheme://$host/remote.php/dav;
 }
 location = /.well-known/caldav {
 return 301 $scheme://$host/remote.php/dav;
 }

# set max upload size
 client_max_body_size 10G;
 fastcgi_buffers 64 4K; # Please see note 1
 fastcgi_ignore_headers X-Accel-Buffering; # Please see note 2
 fastcgi_busy_buffers_size 192K;

gzip off;

 # Uncomment if your server is build with the ngx_pagespeed module
 # This module is currently not supported.
 #pagespeed off;

error_page 403 /core/templates/403.php;
error_page 404 /core/templates/404.php;

location / {
 rewrite ^ /index.php$uri;
 }

location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
 return 404;
 }

location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
 return 404;
 }

location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+|core/templates/40[34])\.php(?:$|/) {
 fastcgi_split_path_info ^(.+\.php)(/.*)$;
 include fastcgi_params;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 fastcgi_param SCRIPT_NAME $fastcgi_script_name; # necessary for owncloud to detect the contextroot https://github.com/owncloud/core/blob/v10.0.0/lib/private/AppFramework/Http/Request.php#L603
 fastcgi_param PATH_INFO $fastcgi_path_info;
 fastcgi_param HTTPS on;
 fastcgi_param modHeadersAvailable true; #Avoid sending the security headers twice
 fastcgi_param front_controller_active true;
 fastcgi_read_timeout 180; # increase default timeout e.g. for long running carddav/ caldav syncs with 1000+ entries
 fastcgi_pass php-handler;
 fastcgi_intercept_errors on;
 fastcgi_request_buffering off; #Available since NGINX 1.7.11
 }

location ~ ^/(?:updater|ocs-provider)(?:$|/) {
 try_files $uri $uri/ =404;
 index index.php;
 }
 # Make sure it is BELOW the PHP block
 location ~ \.(?:css|js)$ {
 try_files $uri /index.php$uri$is_args$args;
 add_header Cache-Control "max-age=15778463";
 # Add headers to serve security related headers (It is intended to have those duplicated to the ones above)
 # Before enabling Strict-Transport-Security headers please read into this topic first.
 #add_header Strict-Transport-Security "max-age=15552000; includeSubDomains";
 add_header X-Content-Type-Options nosniff;
 add_header X-Frame-Options "SAMEORIGIN";
 add_header X-XSS-Protection "1; mode=block";
 add_header X-Robots-Tag none;
 add_header X-Download-Options noopen;
 add_header X-Permitted-Cross-Domain-Policies none;
 # Optional: Don't log access to assets
 access_log off;
 }

 location ~ \.(?:svg|gif|png|html|ttf|woff|ico|jpg|jpeg|map)$ {
 add_header Cache-Control "public, max-age=7200";
 try_files $uri /index.php$uri$is_args$args;
 # Optional: Don't log access to other assets
 access_log off;
 }
 }
$ cat /etc/php-fpm.d/cloud.example.com.conf
[cloud.example.com]
listen = /var/run/php-fpm/php-fpm.cloud.example.com.sock
listen.mode = 0666
user = nginx
group = www-data
chdir = /var/www/html/owncloud

# В зависимости от нагрузки меняем параметры
pm = dynamic
pm.max_children = 10
pm.start_servers = 2
pm.min_spare_servers = 2
pm.max_spare_servers = 4

# Default Value: clean env
env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

Конфигурационный файл owncloud:

# nano /var/www/html/owncloud/config/config.php
<?php
$CONFIG = array (
       'updatechecker' => false,
       'instanceid' => 'bjkkjljkf48o5',
       'passwordsalt' => '3BMoYgjhghhkStcX6Iw4lgT7lgh',
       'secret' => 'U1ZEBI3W9PppZNFPIDPkJJsizVAi3eox9ZvdYqT6JQkHRLZP',
       'trusted_domains' =>
 array (
       0 => 'host.example.com',
 ),
 'datadirectory' => '/var/www/html/owncloud/data',
 'overwrite.cli.url' => 'https://host.example.com/owncloud',
 'dbtype' => 'mysql',
 'version' => '10.0.8.5',
 'dbname' => 'owncloud',
 'dbhost' => 'localhost',
 'dbtableprefix' => 'oc_',
 'dbuser' => 'owncloud',
 'dbpassword' => 'xxxxxxxxxxx',
 'logtimezone' => 'Europe/Kiev',
 'installed' => true,

'filelocking.enabled' => 'true',
 'memcache.local' => '\OC\Memcache\APCu',
 'memcache.distributed' => '\OC\Memcache\Redis',
 'memcache.locking' => '\OC\Memcache\Redis',
 'memcached_servers' => array(
         array('localhost', 11211),
 ),
 'redis' => [
         'host' => 'localhost', // Can also be a unix domain socket => '/tmp/redis.sock'
         'port' => 6379,
         'timeout' => 0,
         'password' => '',  // Optional, if not defined no password will be used.
         'dbindex' => 0     // Optional, if undefined SELECT will not run and will
                            // use Redis Server's default DB Index.
 ],
);

Чтобы убрать ошибки на вкладке Настройки –> Основные

Переключаем Cron (Планировщик) в Cron (системный) и в терминале набираем:

# crontab -e
*/15 * * * * nginx php /var/www/html/owncloud/cron.php

Performance tips for Redis Cache Server

3. Disable THP

1417:M 25 Oct 06:13:31.840 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command ‘echo never > /sys/kernel/mm/transparent_hugepage/enabled’ as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled
This is also simple to fix by just running the recommended command as stated in the warning.

echo never > /sys/kernel/mm/transparent_hugepage/enabled

Go to /etc/rc.local

$~: sudo nano /etc/rc.local

Add this:

echo never > /sys/kernel/mm/transparent_hugepage/enabled

Now this will be persistent upon reboot as well.

 

image_pdfimage_print

ProFTPD

ProFTPD (Professional FTP Daemon) — FTP-сервер для Linux и UNIX-подобных операционных систем. ProFTPD использует лишь один конфигурационный файл proftpd.conf.
Сервер может быть настроен для работы нескольких виртуальных хостов, также поддерживает chroot. Может быть запущен в виде отдельного сервера (демона) или в составе суперсервера inetd. Также поддерживает IPv6.

Расширения: поддерживает модули, добавляющие SSL/TLS-шифрование, аутентификацию через LDAP, работу с SQL, туннелирование соединений через SSH.

$ sudo yum update
$ sudo yum install proftpd

Правим:

nano /etc/proftpd.conf
ServerName            "FTP server"
ServerIdent           on "FTP Server ready."
ServerAdmin           root@localhost
DefaultServer         on
UseIPv6               off
IdentLookups          off
PassivePorts          40900 40999
DefaultRoot           ~ !adm
AuthPAMConfig         proftpd
AuthOrder             mod_auth_pam.c* mod_auth_unix.c
UseReverseDNS         off
User                  nobody
Group                 nobody
MaxInstances          20
UseSendfile           off
SystemLog             /var/log/proftpd/proftpd.log
TransferLog           /var/log/proftpd/xfer.log
ExtendedLog           /var/log/proftpd/access.log WRITE,READ write
ExtendedLog           /var/log/proftpd/auth.log AUTH auth
DebugLevel            9
LoadModule            mod_ctrls_admin.c
LoadModule            mod_vroot.c
ModuleControlsACLs    insmod,rmmod allow user root
ModuleControlsACLs    lsmod allow user *
ControlsEngine        on
ControlsACLs          all allow user root
ControlsSocketACL     allow user *
ControlsLog           /var/log/proftpd/controls.log


<IfModule mod_ctrls_admin.c>
    AdminControlsEngine   on
    AdminControlsACLs     all allow user root
</IfModule>
<IfModule mod_vroot.c>
    VRootEngine on
</IfModule>
<IfDefine TLS>
    TLSEngine on
    TLSRequired on
    TLSRSACertificateFile    /etc/pki/tls/certs/proftpd.pem
    TLSRSACertificateKeyFile /etc/pki/tls/certs/proftpd.pem
    TLSCipherSuite           ALL:!ADH:!DES
    TLSOptions               NoCertRequest
    TLSVerifyClient          off
    #TLSRenegotiate          ctrl 3600 data 512000 required off timeout 300
    TLSLog                   /var/log/proftpd/tls.log
 <IfModule mod_tls_shmcache.c>
 TLSSessionCache             shm:/file=/var/run/proftpd/sesscache
 </IfModule>
</IfDefine>
<IfDefine DYNAMIC_BAN_LISTS>
    LoadModule               mod_ban.c
    BanEngine                on
    BanLog                   /var/log/proftpd/ban.log
    BanTable                 /var/run/proftpd/ban.tab
 # If the same client reaches the MaxLoginAttempts limit 2 times
 # within 10 minutes, automatically add a ban for that client that
 # will expire after one hour.
    BanOnEvent               MaxLoginAttempts 2/00:10:00 01:00:00
 # Inform the user that it's not worth persisting
    BanMessage              "Host %a has been banned"
# Allow the FTP admin to manually add/remove bans
    BanControlsACLs         all allow user ftpadm
</IfDefine>
<IfDefine QOS>
    LoadModule              mod_qos.c
 # RFC791 TOS parameter compatibility
    QoSOptions              dataqos throughput ctrlqos lowdelay
 # For a DSCP environment (may require tweaking)
 #QoSOptions dataqos CS2 ctrlqos AF41
</IfDefine>
<Global>
 # Umask 022 is a good standard umask to prevent new dirs and files
 # from being group and world writable
    Umask                   022
 # Allow users to overwrite files and change permissions
 AllowOverwrite             yes
 <Limit ALL SITE_CHMOD>
 AllowAll
 </Limit>
</Global>
<IfDefine ANONYMOUS_FTP>
 <Anonymous ~ftp>
 User                      ftp
 Group                     ftp
 AccessGrantMsg "Anonymous login ok, restrictions apply."
 # We want clients to be able to login with "anonymous" as well as "ftp"
 UserAlias                 anonymous ftp
 # Limit the maximum number of anonymous logins
 MaxClients                10 "Sorry, max %m users -- try again later"
 # Put the user into /pub right after login
 #DefaultChdir /pub
 # We want 'welcome.msg' displayed at login, '.message' displayed in
 # each newly chdired directory and tell users to read README* files.
    DisplayLogin /welcome.msg
    DisplayChdir .message
    DisplayReadme README*
 # Cosmetic option to make all files appear to be owned by user "ftp"
    DirFakeUser on ftp
    DirFakeGroup on ftp
 # Limit WRITE everywhere in the anonymous chroot
 <Limit WRITE SITE_CHMOD>
    DenyAll
 </Limit>
 # An upload directory that allows storing files but not retrieving
 # or creating directories.
 #
 # Directory specification is slightly different if mod_vroot is in
 # use: see http://sourceforge.net/p/proftp/mailman/message/31728570/
 # https://bugzilla.redhat.com/show_bug.cgi?id=1045922


<IfModule mod_vroot.c>
 <Directory /uploads/*>
    AllowOverwrite     no
 <Limit READ>
    DenyAll
 </Limit>

<Limit STOR>
    AllowAll
 </Limit>
 </Directory>
 </IfModule>
 <IfModule !mod_vroot.c>
 <Directory uploads/*>
    AllowOverwrite no
 <Limit READ>
    DenyAll
 </Limit>

<Limit STOR>
    AllowAll
 </Limit>
 </Directory>
 </IfModule>
 # Don't write anonymous accesses to the system wtmp file (good idea!)
 WtmpLog off
 # Logging for the anonymous transfers
    ExtendedLog       /var/log/proftpd/access.log WRITE,READ default
    ExtendedLog       /var/log/proftpd/auth.log AUTH auth
 </Anonymous>
</IfDefine>

С такой настройкой уже можно подключаться любым системным пользователем.

Переходим к более безопасному и гибкому варианту – виртуальным пользователям.

 

image_pdfimage_print

Bind9 в chroot

# yum -y install bind bind-utils bind-chroot
# systemctl start named-chroot 
# systemctl enable named-chroot

Подготовим chroot-каталог, запустив специальный скрипт:

# /usr/libexec/setup-named-chroot.sh /var/named/chroot on

Укажем параметр для использования chroot

# mcedit /etc/sysconfig/named
OPTIONS="-4"

Редактируем конфиг:

# nano /var/named/chroot/etc/named.conf
acl "bsd" { 192.168.113.0/24; 127.0.0.1; };

options {
    listen-on port 53 { 127.0.0.1; 192.168.113.1; _IP_WAN_; };
    //listen-on-v6 port 53 { ::1; };
    directory "/var/named";
    dump-file "/var/named/data/cache_dump.db";
    statistics-file "/var/named/data/named_stats.txt";
    memstatistics-file "/var/named/data/named_mem_stats.txt";
    allow-query { bsd; };

/*
 - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
 - If you are building a RECURSIVE (caching) DNS server, you need to enable
 recursion.
 - If your recursive DNS server has a public IP address, you MUST enable access
 control to limit queries to your legitimate users. Failing to do so will
 cause your server to become part of large scale DNS amplification
 attacks. Implementing BCP38 within your network would greatly
 reduce such attack surface
 */
     recursion yes;
     allow-recursion { bsd; };

forwarders {
     127.0.0.1;
     _IP_DNS_провайдера;
     8.8.8.8;
 };

version "DNS Server";

blackhole {
    0.0.0.0/8;
    10.0.0.0/8;
    169.254.0.0/16;
    172.16.0.0/12;
    192.0.2.0/24;
    //192.168.0.0/16;
    224.0.0.0/4;
    240.0.0.0/4;
 };

dnssec-enable yes;
dnssec-validation yes;

/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";

managed-keys-directory "/var/named/dynamic";

pid-file "/run/named/named.pid";
session-keyfile "/run/named/session.key";
 };

logging {
 channel queries {
     file "/var/log/named/queries.log" versions 2 size 10M;
     print-time yes;
     print-category yes;
     print-severity yes;
 };
 channel bind_log {
     file "/var/log/named/named.log" size 10M;
     print-category yes;
     print-severity yes;
     print-time yes;
 };
 channel update_debug {
     file "/var/log/named/named-update.log" versions 6 size 10M;
     severity debug 10;
     print-category yes;
     print-severity yes;
     print-time yes;
 };
 channel security_info {
     file "/var/log/named/named.log" versions 6 size 10M;
     severity info;
     print-category yes;
     print-severity yes;
     print-time yes;
 };
 channel edns-disabled {
     file "/var/log/named/edns-disabled.log" versions 1 size 500K;
     severity info;
     print-category yes;
     print-severity yes;
     print-time yes;
 };
category default { bind_log; };
category xfer-in { bind_log; };
category xfer-out { bind_log; };
category update { update_debug; };
category security { security_info; };
category queries { queries; };
category edns-disabled { edns-disabled; };
category lame-servers { null; };
};

zone "." IN {
    type hint;
    file "named.ca";
 };

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

Не забыть создать директорию для логов:

# mkdir -p /var/named/chroot/var/log/named
# cd /var/named/chroot/var/log
# chown named:named named

Перечитать конфигурацию:

# rndc reconfig

Проверяем конфигурацию и зоны на ошибки:

# named-checkconf
# named-checkzone example.com /var/named/external/example.com.zone
# named-checkzone example.com /var/named/internal/example.com.zone

DNS-сервер работает на 53 порту UDP, а для передачи зон использует 53 порт TCP. Отвечать на запросы будет всем, но передавать зону только slave-серверу, по локальной сети.

# iptables -A INPUT -p udp --dport 53 -j ACCEPT -m comment --comment "dns-query"
# iptables -A INPUT -s 172.16.0.2 -p tcp --dport 53 -j ACCEPT -m comment --comment "dns-transfer"

Проверяем.

источник
http://itzx.ru/linux/install-named-bind-chroot-on-centos
https://webhostinggeeks.com/howto/bind-dns-server-in-chroot-jail-on-centos-7/

 

image_pdfimage_print

Apcupsd на Centos 7

APC UPS SMART 1500, подключен по USB.

Настройка на сервере:

$ sudo yum -y install apcupsd
$ sudo nano /etc/apcupsd/apcupsd.conf
UPSCABLE usb
UPSTYPE usb
LOCKFILE /var/lock
SCRIPTDIR /etc/apcupsd
PWRFAILDIR /etc/apcupsd
NOLOGINDIR /etc
ONBATTERYDELAY 6
BATTERYLEVEL 37
MINUTES 10
TIMEOUT 0
ANNOY 300
ANNOYDELAY 60
NOLOGON disable
KILLDELAY 0
NETSERVER on
NISIP 0.0.0.0
NISPORT 3551
EVENTSFILE /var/log/apcupsd.events
EVENTSFILEMAX 10
UPSCLASS standalone
UPSMODE disable
STATTIME 0
STATFILE /var/log/apcupsd.status
LOGSTATS off
DATATIME 0

Проверяем:

$ sudo apcaccess

Настройка на клиенте:

[root@faust apcupsd]# cat apcupsd.conf | egrep "^[^#]"
UPSCABLE ether
UPSTYPE net
DEVICE _IP_сервера:3551
LOCKFILE /var/lock
SCRIPTDIR /etc/apcupsd
PWRFAILDIR /etc/apcupsd
NOLOGINDIR /etc
ONBATTERYDELAY 6
BATTERYLEVEL 41
MINUTES 12
TIMEOUT 0
ANNOY 300
ANNOYDELAY 60
NOLOGON disable
KILLDELAY 0
NETSERVER on
NISIP 0.0.0.0
NISPORT 3551
EVENTSFILE /var/log/apcupsd.events
EVENTSFILEMAX 10
UPSCLASS standalone
UPSMODE disable
STATTIME 0
STATFILE /var/log/apcupsd.status
LOGSTATS off
DATATIME 0

 

image_pdfimage_print

Bind9.9 на Centos 7

Устанавливаем:

$ sudo yum install bind bind-utils
$ cat /etc/named.conf

acl "bsd" { 192.168.113.0/24; 127.0.0.1; };

options {
       listen-on port 53 { 127.0.0.1; 192.168.113.1; };
       listen-on-v6 port 53 { none; };

forwarders {
       127.0.0.1;
       _DNS_провайдера;
       8.8.8.8;
       };


directory "/var/named";
       dump-file "/var/named/data/cache_dump.db";
       statistics-file "/var/named/data/named_stats.txt";
       memstatistics-file "/var/named/data/named_mem_stats.txt";

/*
 - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
 - If you are building a RECURSIVE (caching) DNS server, you need to enable
 recursion.
 - If your recursive DNS server has a public IP address, you MUST enable access
 control to limit queries to your legitimate users. Failing to do so will
 cause your server to become part of large scale DNS amplification
 attacks. Implementing BCP38 within your network would greatly
 reduce such attack surface
 */


allow-query { bsd; };

recursion yes;
allow-recursion { bsd; };

blackhole {
      0.0.0.0/8;
      10.0.0.0/8;
      169.254.0.0/16;
      172.16.0.0/12;
      192.0.2.0/24;
     //192.168.0.0/16;
      224.0.0.0/4;
      240.0.0.0/4;
     };

dnssec-enable yes;
dnssec-validation yes;

/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";

managed-keys-directory "/var/named/dynamic";

pid-file "/run/named/named.pid";
session-keyfile "/run/named/session.key";
};


logging {
     channel queries {
     file "/var/log/named/queries.log" versions 2 size 10M;
     print-time yes;
     print-category yes;
     print-severity yes;
     };
 channel bind_log {
     file "/var/log/named/named.log" size 10M;
     print-category yes;
     print-severity yes;
     print-time yes;
     };
 channel update_debug {
     file "/var/log/named/named-update.log" versions 6 size 10M;
     severity debug 10;
     print-category yes;
     print-severity yes;
     print-time yes;
     };
 channel security_info {
     file "/var/log/named/named.log" versions 6 size 10M;
     severity info;
     print-category yes;
     print-severity yes;
     print-time yes;
     };

channel edns-disabled {
     file "/var/log/named/edns-disabled.log" versions 1 size 500K;
     severity info;
     print-category yes;
     print-severity yes;
     print-time yes;
     };

category default { bind_log; };
category xfer-in { bind_log; };
category xfer-out { bind_log; };
category update { update_debug; };
category security { security_info; };
category queries { queries; };
category edns-disabled { edns-disabled; };
category lame-servers { null; };
};

zone "." IN {
    type hint;
    file "named.ca";
};

#controls {
# inet 127.0.0.1 port 953
# allow { 127.0.0.1; } keys { "rndc-key"; };
# };

include "/etc/rndc.key";

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
$ sudo systemctl start named
$ sudo systemctl enable named

Правим:

cat /etc/resolv.conf
# Generated by NetworkManager
search imp.kiev.ua
nameserver 194.44.219.161
nameserver 8.8.8.8
nameserver 8.8.4.4

Проверяем:

[root@ring etc]# dig ya.ru

; <<>> DiG 9.9.4-RedHat-9.9.4-61.el7 <<>> ya.ru
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 5166
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;ya.ru. IN A

;; Query time: 0 msec
;; SERVER: 194.44.219.161#53(194.44.219.161)
;; WHEN: Срд Июл 25 16:26:48 EEST 2018
;; MSG SIZE rcvd: 34

Делаем chroot

 

 

image_pdfimage_print

Обновление ядра Centos

Смотрим текущую версию ядра:

$ uname -r

Подключаем репозиторий, предварительно импортировав ключ:

$ sudo rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
$ sudo rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-2.el7.elrepo.noarch.rpm

Смотрим доступную версию ядра:

$ sudo yum --disablerepo="*" --enablerepo="elrepo-kernel" list available

Устанавливаем:

$ sudo yum --enablerepo=elrepo-kernel install kernel-ml

Проверяем:

$ uname -sr

Настройка загрузчика для ядра по умолчанию:

$ sudo vim /etc/default/grub
GRUB_DEFAULT=0

Это означает, что по умолчанию будет использоваться первое ядро , которое находится в
списке Grub. А первым обычно размещается именно самое новое. Чтобы обновить конфигурацию
выполните команду:

$ sudo grub2-mkconfig -o /boot/grub2/grub.cfg

Осталось еще раз перезагрузиться чтобы убедиться, что теперь все по умолчанию выбирается
нужное ядро.

image_pdfimage_print

Как отключать и включать репозитории в CentOS

1. Получение списка репозиториев

Получим список всех доступных системе.

# yum repolist

epel Extra Packages for Enterprise Linux 6 — x86_64 12 219
ol7_UEKR3/x86_64 Latest Unbreakable Enterprise Kernel Release 3 for Oracle Linux 7Server (x86_64) 489
ol7_latest/x86_64 Oracle Linux 7Server Latest (x86_64) 15 165
repolist: 27 873

Для того что бы посмотреть к какому пакету принадлежит пакет, нужно выполнить следующую команду:

yum info package-name | grep -i repo

2. Выключение репозитория (метод 1)

Репозиторий выключается опцией —disablerepo=repository-name. Например выключим репозиторий epel:

yum —disablerepo=epel update

Для отключения нескольких репозиториев, их нужно писать через запятую:

yum update —disablerepo=epel.repo

3. Выключение репозитория (метод 2)

Репозиторий можно отключить в конфигурационном файле хранилища. Для этого зайдем в настройки и значение параметра enabled выставим в 0.

# vi /etc/yum.repos.d/epel.repo
 [epel]
 name=Extra Packages for Enterprise Linux 7 — $basearch
 #baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
 mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
 failovermethod=priority
 enabled=0
 gpgcheck=1
 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

И теперь если вывести список репозиториев, то отключенного не будет:

ol7_UEKR3/x86_64 Latest Unbreakable Enterprise Kernel Release 3 for Oracle Linux 7Server (x86_64) 489
 ol7_latest/x86_64 Oracle Linux 7Server Latest (x86_64) 15 165
 repolist: 15 654

4. Включение репозитория

Если репозиторий выключен, и его нужно включить в конкретной команде, то опцией enablerepo его можно включить:

yum update —enablerepo=epel

5. Комбинация

Если нужно включить один и выключить другой репозиторий, то пишется две опции:

yum update —disablerepo=* —enablerepo=epel

https://unix.freegeek.ru/repo-centos-red-hat/

image_pdfimage_print

nginx кодировка cp-1251 и utf-8

При переносе сайта с апача на nginx слетела кодировка. У меня часть сайтов на utf-8 и есть парочка на cp-1251.

$ sudo nano /etc/php.ini

; PHP's default character set is set to empty.
; http://php.net/default-charset
;default_charset = "UTF-8"
default_charset =.

пустое значение. И в блоке /etc/nginx/sites-avialable/vsite1.com

server {
...
 charset windows-1251;
 error_log /var/log/nginx/err.imp.log;
 index index.php index.html index.htm;

Рестартуем сервисы.

image_pdfimage_print

MySQL Server Has Gone Away (error 2006)

Ошибка MySQL Server Has Gone Away (error 2006) может возникнуть в двух случаях.

Таймаут соединения

Наиболее распространенная проблема: таймаут соединения, в результате чего сервер его закрывает. Решение весьма тривиальное — увеличение лимита времени wait_timeout в файле конфигурации my.cnf. Для этого в Debian нужно выполнить:

sudo nano 
/etc/mysql/my.cnf

# Открытие файла настроек MySQL

Затем установить тайм-аут ожидания:

wait_timeout = 600

# Время ожидания в секундах, можно установить вплоть до 28800 с (8 часов)

Не забудьте перезагрузить базу:

sudo /etc/init.d/mysql restart

# Перезагрузка базы данных MySQL

Иногда, при выполнении длительных запланированных задач, также может появиться ошибка MySQL Server Has Gone Away все из-за того же таймаута соединения. При этом лимит времени не получится существенно увеличить (максимум до нескольких часов), так как это может привести к заполнению буфера ожидающими соединениями.

Поэтому лучше проверить соединение и, при необходимости, переподключиться.

$link = mysql_connect("localhost","root","root"); 

# Здесь будут cron jobs

if( !mysql_ping($link) ) $link = mysql_connect("localhost","root","root", true);

# Подключение БД и переподключение при необходимости

Большой или некорректный пакет

Вторая распространенная проблема: сервер получает большой или некорректный пакет и отклоняет его. В этом случае сервер считает, что проблема на стороне клиента и закрывает соединение. Так что для решения нужно увеличить лимит на максимальный размер пакета все в том же файле конфигурации:

[mysqld]
...
max_allowed_packet = 64M
…

# Увеличение лимита размера входящего пакета, в МБ

Также не забудьте перезагрузить базу данных.

Самое главное

После того, как устраните ошибку MySQL Server Has Gone Away, поиграйтесь с параметрами wait_timeout и max_allowed_packet для получения оптимальных лимитов.

 

https://ruhighload.com/mysql+server+has+gone+away+-+%D0%BA%D0%B0%D0%BA+%D0%BF%D0%BE%D1%84%D0%B8%D0%BA%D1%81%D0%B8%D1%82%D1%8C

image_pdfimage_print