agosto 29, 2018

¿CÓMO DAR DE ALTA UNA WEB EN LOS PRINCIPALES BUSCADORES?

¿CÓMO DAR DE ALTA UNA WEB EN LOS PRINCIPALES BUSCADORES?


Es muy común encontrar anuncios de empresas que, previo pago, dan de alta tu web en decenas de buscadores, muchos de ellos, la mayoría, que ni siquiera nadie conoce. Y, obviamente, si nadie conoce, ¿quién va a buscar nuestra página ahí?

Según un estudio realizado por desarrolloweb.comGoogle es el rey absoluto, con el 85% de las búsquedas realizadas en España. Yahoo y Bing son segundo y tercero respectivamente. El buscador chino Baidu y Ask apenas se utilizan, pero ahí están, con su pequeña porción de las búsquedas en Internet.

Es por ello que a la hora de posicionar nuestra web, debemos prestar mucha atención a cómo Google la indexa. (En sucesivos post veremos distintas acciones que nos ayudarán a mejorar nuestro posicionamiento, y también veremos cómo monitorizar nuestra posición respecto determinadas palabras claves o key words y las webs de la competencia.)

Pero, no obstante, no debemos olvidarnos del resto, por ello, para comenzar a trabajar el posicionamiento de nuestra web, es conveniente sugerir nuestra url a los buscadores más populares. Quizá, por diversos motivos, los robots ya la hayan indexado, pero no está de más, aunque ningún buscador garantiza su optimo posicionamiento simplemente por esto. Aquí tenéis los enlaces para sugerir urls de los distintos buscadores.

Sugerir sitio a Google.


Sugerir sitio a Yahoo.


Sugerir sitio a Bing.


Sugerir sitio a Baidu.


Incluir url en Ask.com. Para este site es necesario que la web cuente con un sitemap.xml. Si se tiene, simplemente hay que enviarlo a través de la ping-URL:


http://submissions.ask.com/ping?sitemap=http%3A//www.la URL de su sitemap aquí.xml.


Es decir, poner tal cual el enlace indicado más el dominio y /sitemap.xml.

También es conveniente incluir el site en directorios, por ejemplo en www.allabord.com puedes ingresar tu sitio para ser indexado y que haga referencia a tu sitio.

Por favor, Necesito saber ¿como se hace para que cuando busquen mi web, aparezca un encabezado y debajo mis páginas internas como ofreciendo cada una de las principales. que parece un árbol?

Hola, esto que indicas depende de Google. Para ello, es importte el número de links entrantes que reciba cada una de las páginas de tu web. No puedes crearlo directamente.

¿Cómo dar de alta una web en los principales buscadores?

agosto 28, 2018

Can't exec "/bin/sh": Argument list too long at /usr/sbin/logwatch line

Síntoma:


Can't exec "/bin/sh": Argument list too long at /usr/sbin/logwatch line 988


Can't exec "/bin/sh": Argument list too long at /etc/cron.daily/0logwatch line 980



Solución:


Este bug está documentado en https://bugzilla.redhat.com/show_bug.cgi?id=472226


para resolverlo hay que hacer dos cosas.


  • Poner un firewall para las ips permitidas.
  • Borrar los logs almacenados en /var/log/samba/








  • Poner un firewall para las ips permitidas.

Usando iptables puede usarse https://blogdeecomputo.blogspot.com/search?q=iptables






  • Borrar los logs almacenados en /var/log/samba/

cd /var/log/samba/

rm *


agosto 23, 2018

Crear tu tienda virtual con Shopify, kichink o mercadoshops

Crear tu tienda online con Shopify es fácil


https://www.shopify.com.mx/


Otra opción es kichink


https://www.kichink.com/


Otra opción mercadoshops


https://www.mercadoshops.com.mx/

Error: Skipping oversized log record en Webalizer

Síntoma Error:

Error: Skipping oversized log record

al ejecutar

webalizer -o /path/webstats /path/archivo_access_log


Solución:

Hay que borrar la línea del archivo que provoca el error

Encontrar la línea más grande

$wc -L -l archivo_access_log
23597983       7426 archivo_access_log
# de línea, #cantidad de palabras, nombre de archivo


Borrar la línea 23597983 en el archivo archivo_access_log:
sed -e '23597983d' archivo_access_log


Fuente: https://talk.plesk.com/threads/etc-cron-daily-00webalizer-error-skipping-oversized-log-record.56224/

Fuente: https://stackoverflow.com/questions/1655372/longest-line-in-a-file

Fuente: https://unix.stackexchange.com/questions/45944/delete-specific-line-numbers-from-a-text-file-using-sed

Fuente: https://linux.die.net/man/1/sed


¿Cómo quitar disco duro de forma segura en Linux?

En una terminal.

Invoca un "df -h" para ver cuáles son los puntos de montaje de tu sistema. Te saldrá algo así:


/dev/sdb1 917G 662G 209G 77% /Respaldo
/dev/sda5 379G 92G 268G 26% /home
/dev/sda1 477M 66M 386M 15% /boot
/dev/sda6 379G 15G 345G 4% /var


Fíjate en la primera columna, tu disco duro tendría que aparecer como "/dev/sdb1" o algo así (fíjate en la capacidad de la segunda columna).

$sudo umount /dev/sdb1

donde /dev/sdb1 es tu dispositivo USB y arreglado.

o

$su -c "umount /dev/sdb1"

Fuente: https://www.genbeta.com/respuestas/como-quitar-disco-duro-de-forma-segura-en-linux

AMP Accelerated Mobile Pages

AMP Accelerated Mobile Pages

AMP HTML es HTML con algunas restricciones para lograr un rendimiento confiable, y con algunas extensiones para compilar contenido enriquecido más allá del formato HTML básico.

https://www.ampproject.org/

error 2059 (hy000) authentication plugin 'caching_sha2_password' cannot be loaded

Error:

error 2059 (hy000) authentication plugin 'caching_sha2_password' cannot be loaded


Solución:


ALTER USER 'yourusername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'youpassword';

Fuente: https://stackoverflow.com/questions/49194719/authentication-plugin-caching-sha2-password-cannot-be-loaded

agosto 22, 2018

Instalar MySQL 8.0/5.7 en Fedora 31/30/29/28/27, CentOS/RHEL 7.5/6.9 y Red Hat (RHEL) 7.5/6.9



Instalar MySQL 8.0/5.7 en Fedora 31/30/29/28/27, CentOS/RHEL 7.5/6.9


Guía para instalar MariaDB 10.2/10.1/10.3

MySQL es un Sistema Manejador de Bases de Datos  Relacionales - Relational Database Management System (RDBMS) que corre como un servidor dando acceso multiusuario y a  varias bases de datos.

Con esta guía ser instalará o actualizará MySQL Community Server a su última versión 5.7 (5.7.22) / 8.0 (8.0.11)  en Fedora 31/30/29/28/27, CentOS/RHEL 7.5/6.9

Esta guía trabaja con Oracle Linux y Scientific Linux tambíen.

Importante: Si estás actualizando MySQL (desde una versión anterior), entonces asegurate que tengas los respaldos y copias de tu base de datos y de la configuración. Recuerda correl el comando mysql_upgrade

Instalar MySQL Database 5.7.22/8.0.11 on Fedora 31/30/29/28/27/26, CentOS 7.5/6.9, Red Hat (RHEL) 7.5/6.9

1. Cambiate al usuario root

su -
## OR ##
sudo -i

2. Instala los repositorios YUM de MySQL

Fedora

## Fedora 31 ##
dnf install https://dev.mysql.com/get/mysql80-community-release-fc31-1.noarch.rpm

## Fedora 30 ##
dnf install https://dev.mysql.com/get/mysql80-community-release-fc30-1.noarch.rpm

## Fedora 29 ##
dnf install https://dev.mysql.com/get/mysql80-community-release-fc29-1.noarch.rpm

## Fedora 28 ##
dnf install https://dev.mysql.com/get/mysql80-community-release-fc28-1.noarch.rpm

## Fedora 27 ##
dnf install https://dev.mysql.com/get/mysql80-community-release-fc27-1.noarch.rpm

## Fedora 26 ##
dnf install https://dev.mysql.com/get/mysql80-community-release-fc26-1.noarch.rpm

CentOS and Red Hat (RHEL)

## CentOS 7 and Red Hat (RHEL) 7 ##
yum localinstall https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm

## CentOS 6 and Red Hat (RHEL) 6 ##
yum localinstall https://dev.mysql.com/get/mysql80-community-release-el6-1.noarch.rpm

3a. Actualiza o instala MySQL 8.0.11

Fedora 31/30/29/28/27/26

dnf install mysql-community-server

o

dnf update mysql-community-server

CentOS 7.5/6.9 and Red Hat (RHEL) 7.5/6.9

yum install mysql-community-server

o

yum update mysql-community-server


3b. Actualiza o instala MySQL 5.7.22

Fedora 31/30/29/28/27/26

dnf --disablerepo=mysql80-community --enablerepo=mysql57-community install mysql-community-server

CentOS 7.5/6.9 and Red Hat (RHEL) 7.5/6.9

yum --disablerepo=mysql80-community --enablerepo=mysql57-community install mysql-community-server

4. Arranca MySQL server y realizar ejecución automática de MySQL al bootear

Fedora 31/30/29/28/27/26 and CentOS 7.5 and Red Hat (RHEL) 7.5

systemctl start mysqld.service ## use restart after update

systemctl enable mysqld.service

CentOS 6.9 and Red Hat (RHEL) 6.9

/etc/init.d/mysql start ## use restart after update
## OR ##
service mysql start ## use restart after update

chkconfig --levels 235 mysqld on

5. Generar un password aleatorio para root

grep 'Un password temporal es generado para root@localhost' /var/log/mysqld.log |tail -1

Example Output:


2015-11-20T21:11:44.229891Z 1 [Note] Un password temporal es generado para root@localhost: -et)QoL4MLid

And root password is: -et)QoL4MLid


6. Instalación segura de MySQL

  • Change root password
  • Remove anonymous users
  • Disallow root login remotely
  • Remove test database and access to it
  • Reload privilege tables

Empezar una instalación segura para MySQL con el siguiente comando:

/usr/bin/mysql_secure_installation

Salida:

Securing the MySQL server deployment.

Enter password for user root: 

The existing password for the user account root has expired. Please set a new password.

New password: 

Re-enter new password: 

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No: y

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0
Using existing password for root.

Estimated strength of the password: 100 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

New password: 

Re-enter new password: 

Estimated strength of the password: 50 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

All done! 

Importante: Sin no quieres, por alguna razón , realizar la instalación Segura de MySQL, entonces, por lo menos, es importante cambiar el password de root con los siguientes comandos

mysqladmin -u root password [your_password_here]

## Example ##
mysqladmin -u root password myownsecrectpass

7. Conectar al Sistema Manejador de bases de datos MySQL mediante (localhost) pidiendo un password para acceder

mysql -u root -p

## OR ##
mysql -h localhost -u root -p

8. Crear una base de datos en MySQL y permitir una conexión a la base de datos creada

El siguiente ejemplo usa los siguientes parametros:
  • DB_NAME = webdb
  • USER_NAME = webdb_user
  • REMOTE_IP = 10.0.15.25
  • PASSWORD = password123
  • PERMISSIONS = ALL
## CREATE DATABASE ##
mysql> CREATE DATABASE webdb;

## CREATE USER ##
mysql> CREATE USER 'webdb_user'@'10.0.15.25' IDENTIFIED BY 'password123';

## GRANT PERMISSIONS ##
mysql> GRANT ALL ON webdb.* TO 'webdb_user'@'10.0.15.25';

##  FLUSH PRIVILEGES, Tell the server to reload the grant tables  ##
mysql> FLUSH PRIVILEGES;

Enable Remote Connection to MariaDB Server –> Open MySQL Port (3306) on Iptables Firewall (as root user again)


1. Fedora 31/30/29/28/27/26 and CentOS/Red Hat (RHEL) 7.5

1.1 Agregar una regla nueva al Firewalld

firewall-cmd --permanent --zone=public --add-service=mysql

## OR ##

firewall-cmd --permanent --zone=public --add-port=3306/tcp

1.2 Resetear el servicio firewalld.service

systemctl restart firewalld.service

2. CentOS/Red Hat (RHEL) 6.9

2.1 Editar el archivo /etc/sysconfig/iptables :

nano -w /etc/sysconfig/iptables

2.2 Agregar el siguiente regla INPUT:

-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT

2.3 Restart Iptables Firewall:

service iptables restart
## OR ##
/etc/init.d/iptables restart


3. Test remote connection

mysql -h 10.0.15.25 -u myusername -p


Fuente: https://www.if-not-true-then-false.com/2010/install-mysql-on-fedora-centos-red-hat-rhel/



No se encuentra el dispositivo Android con Vysor

Vysor Can't Find your Android

0) Restart your phone and restart your computer. You'd be surprised how often this fixes things.

1) Make sure you are using a USB DATA cable! Accidentally using a charge cable will not allow data transfer with the computer.

2) On Windows, download your the Universal ADB Drivers:
https://adb.clockworkmod.com
If that doesn't work, try installing your manufacturer's drivers.

3) Enable ADB debugging

4) Set your USB mode to PTP (it is usually MTP or Charge Only)

Check out the walkthrough video below for a step by step guide.

Do not open a bug for this issue. If these steps do not resolve it, there is no "other" solution. Follow the instructions.


Fuente: https://plus.google.com/110558071969009568835/posts/Bb2wMXVwsQ7

Para habilitar el modo de depuración por USB en Android

How to enable USB Debugging on Android



https://youtu.be/Ucs34BkfPB0

agosto 21, 2018

Sugerencia para nombrar archivos

Este artículo en inglés da muy buena referencia de como de nombrar los archivos, que como lo comenta el artículo, sirve para ahorrar tiempo y esfuerzo:


https://www.abdn.ac.uk/staffnet/documents/policy-zone-information-policies/File%20Naming%20Conventions%20July%202017.pdf

Cambiar la miniatura (Thumbnail) por la caratula del álbum en el archivo de música




Cambiar la miniatura (Thumbnail) por la caratula del álbum en el archivo de música





Ordenar archivos por nombre del album en Windows 10


      How to sort folders of music by Album Name


Hello..i know how to sort individual tracks by album/artist or whatever but I'm trying to sort folders of albums in a main folder and for the heck of it can't figure out how to get it to do so.

Just to clarify this is my setup that I'm talking about:

D:\Music\Dance\Artist - Album Name

now in that Dance folder is about 75 albums/folders. All i can do is sort them by name. But I want to sort them by Album Name. I have the Album name column showing but its blank. I even added the folder to indexing but still nothing shows up.

Is there a way to do this?



To sort by Album name, you need Sort By > Album in the right click context menu. But it is not there.

Add it there.
Step 1: Right Click > Sort by > More ....
Click image for larger version. 

Name: 1.jpg 
Views: 1 
Size: 79.1 KB 
ID: 81172
In the Choose Details dialog, check the album box, click OK.
Click image for larger version. 

Name: 2.jpg 
Views: 1 
Size: 94.3 KB 
ID: 81173
Now Sort By > Album is rightly there.
Click image for larger version. 

Name: 3.jpg 
Views: 1 
Size: 78.1 KB 
ID: 81174

Now, to add the Album column, you need to edit the music tags. I use MP3Tag in order to do this.

Fuente: https://www.tenforums.com/general-support/51125-how-sort-folders-music-album-name.html

Promoción de sitios web

Promoción de sitios web
Website Promotion US
Promoción de sitios web ES
Promotion d'un site web FR
Promozione di un sito web IT
Promoção de um website BR

Introducción al marketing

Promocionar un sitio web consiste en hacerlo conocido públicamente por medio de varios canales con el fin de, dependiendo del caso, mejorar el tráfico, ganar reconocimiento, atraer futuros clientes o promover las ventas.

"Se llama "marketing web" (también llamado "cybermarketing o redmarketing) a cualquier campaña que, a través del uso de Internet como canal de marketing, mejora la notoriedad de un sitio web. El término marketing web se usa en oposición a "marketing tradicional".

Como el marketing web y el tradicional no necesariamente se excluyen uno al otro, una buena campaña publicitaria en línea articulada con una campaña publicitaria tradicional fuera de Internet causará mayor impacto.
La prensa

La prensa es el mejor medio tradicional para organizar una campaña de divulgación. La promoción de sitios web no es la excepción a esta regla.

La divulgación por medio de este canal se da generalmente en la forma de comunicado de prensa, o sea, un texto descriptivo corto que se envía a periodistas.
Vínculos recíprocos

Configurar vínculos recíprocos implica establecer una sociedad entre varios sitios web complementarios a través del intercambio de vínculos para atraer más tráfico hacia todos ellos. Esta es una de las estrategias de publicidad más ventajosas porque es fácil de implementar y de bajo costo.

El intercambio de vínculos puede beneficiar a un sitio web a través del tráfico que llega desde los sitios asociados, pero también puede resultar contraproducente o dañar la imagen del sitio web si los socios elegidos no son los adecuados.

Para establecer este tipo de sociedad se debe escoger, como primera medida, sitios web que complementen el suyo y que no sean competidores directos. Para elegir futuros socios se deben seguir los siguientes criterios:

    Reputación
    Calidad de los contenidos
    Tráfico
    Ubicación en los motores de búsqueda

Existen servicios de intercambio de links (a menudo llamados granjas de vínculos o anillos web) que reúnen vínculos de varios sitios web que pertenecen a la misma categoría. Este tipo de servicio pone a disposición las herramientas mostrando al azar los vínculos de los sitios web que conforman una sociedad. Los sitios web que ofrecen este servicio por lo general prometen un incremento espectacular del tráfico. Sin embargo, quien más se beneficia es esta granja de vínculos ya que un vínculo a su sitio web figura en todas las páginas de la sociedad.
Intercambio de contenido

El intercambio de contenido es una buena manera de hacer conocer un sitio web mientras que se forjan relaciones con los sitios socios. El intercambio de contenido consiste en poner elementos del contenido a disposición de otros sitios a cambio de notoriedad, gracias a un vínculo hacia la fuente y posiblemente un logotipo.
Marketing viral

El marketing viral se basa en utilizar las relaciones interpersonales entre los usuarios de Internet para divulgar información. Esta técnica consiste en convertir a los visitantes de un sitio web en embajadores publicitarios de dicho sitio a través de la recomendación boca a boca. Un marketing viral exitoso llevará a una distribución exponencial.

Existe una diferencia entre el marketing viral pasivo, donde el producto es el responsable de promocionarse a sí mismo y el marketing viral activo, que consiste en transmitir un mensaje acerca de un producto en un medio de envío. La mensajería instantánea y los teléfonos móviles pueden asociarse al marketing pasivo en la medida en que su uso alienta a la familia y amigos de un usuario a utilizarlos también.

Es posible poner en marcha el marketing viral al hacer circular videos pequeños o "goodies" (lo ideal es que sean menores a 1 Mb) para que se difundan a través del correo electrónico. La mejor manera de garantizar su divulgación es hacerlos graciosos.

Los medios de marketing viral más importantes son:

    Postales virtuales o tarjetas electrónicas
    Protectores de pantalla
    Fondos de pantalla
    Animaciones y juegos
    Video clips
    Utilidades prácticas y originales

Cada vez más sitios web ofrecen una función que permite a los visitantes recomendar el sitio web a un amigo. Este es un tipo de marketing viral que utiliza al visitante como una herramienta de marketing para llegar a otras personas.
Promoción en medios existentes

Puede resultar beneficioso para una empresa tomar ventaja de los medios de marketing ya existentes, en especial el medio papel (tarjetas comerciales, formularios de presupuestos, catálogos y folletos), e imprimirles su URL.

Sitios recomendados para ingresar tu URL a un sistema de indexación:

www.allabord.com
www.richardsite.com.mx

agosto 20, 2018

Para autenticar correo de Yahoo con imap en Outlook 2016

Download your email from Yahoo Mail with IMAP

Use the IMAP settings below to download your email from Yahoo Mail into a third-party email app, like Thunderbird, Outlook, or Mac Mail. For accounts with a lot of content, it can take several days or longer to download everything. If you need specific instructions to configure your app with our settings or to check the progress of your download, please reach out to the app developer.

We've updated our Terms of Service and Privacy Policy - You'll need to review and accept the new Terms of Service and Privacy Policy to allow third-party email apps to access your Yahoo Mail account. If you haven't already, sign into your account using a web browser to do so.
First, review the following

Keep a copy of your email in your account - If your app asks you if you want to "keep mail on the server" during setup, select "yes," or your email will be deleted from your account when it's downloaded.
Backing up your email? Some apps default to only download a preview or snippet of your emails until an email is opened. Make sure your app is set to download the full contents of your email for offline use.
Limitations for large folders - Folders containing upwards of 1 million or more emails will have issues downloading all the messages. To resolve this, move some of the email to a new folder in your account.

Then, use this info to configure your app

Incoming Mail (IMAP) Server

Server - export.imap.mail.yahoo.com
Port - 993
Requires SSL - Yes

Outgoing Mail (SMTP) Server

Server - smtp.mail.yahoo.com
Port - 465 or 587
Requires SSL - Yes
Requires authentication - Yes

Your login info

If you're using Yahoo Account Key, generate an app password and use that for your account password.

Email address - Your full email address (name@domain.com)
Password - Your account's password
Requires authentication - Yes

For some older email apps, you'll need to adjust your account settings to grant it temporary access before the app will accept your password.

Fuente: https://en-global.help.yahoo.com/kb/new-mail-for-desktop/sln28681.html

Generate third-party app passwords


Some older third-party email apps (that do not use our Yahoo branded sign in page) require you to enter a single password for login credentials. If you've activated two-step verification or Account Key for your Yahoo account, you'll need to generate and use an "app password" to access Yahoo Mail from these apps.

  1. Sign in and go to your Account security page.
  2. Click Generate app password or Manage app passwords.
  3. Select your app from the drop down menu and click Generate.
  4. Follow the instructions below the password.
  5. Click Done.
  6. Use this app password and your email address to sign in to your email app.

Programar el apagado de la computadora linux


Antes de irme a dormir existen ocasiones en las que me pongo en la cama escuchando un podcast o la radio a través del ordenador. Al rato de estar escuchando la radio o el podcast acaba pasando una de estas dos cosas:
  1. Me quedo dormido y el ordenador queda abierto toda la noche. Obviamente no me gusta quedarme dormido con el ordenador y la radio encendida.
  2. Una vez estoy ya medio dormido tengo que levantarme para apagar el ordenador. Obviamente esto molesta ya que después hay que volver a coger el sueño.
Para solucionar este pequeño problema tenemos varias soluciones. Una de ellas es programar el apagado del ordenador. Algunos de los métodos que podemos usar para programar el apagado del ordenador son las siguientes:

MÉTODO 1: PROGRAMAR EL APAGADO DEL ORDENADOR MANUALMENTE DESDE LA TERMINAL

Es el método que acostumbro a usar. Mediante el uso de la terminal podemos programar el apagado del ordenador muy fácilmente. Algunos ejemplos de como podemos programar el apagado del ordenador son los siguientes:

Apagar el ordenador después de un tiempo determinado

Abrimos una terminal. Una vez abierta la terminal ejecutamos el siguiente comando:
sudo shutdown -h +30
El significado de cada uno los términos del comando son los siguientes:
sudo: Porque el programa shutdown precisa permisos de superusuario para ejecutarse.
shutdown: Es el programa que permite programar el apagado del ordenador.
-h: Indica la acción a realizar una vez pasado un tiempo determinado. En este caso la acción es la acción halt (-h). Por lo tanto una vez pasado el tiempo que queramos el ordenador se apagará.
+30: Indicamos el tiempo en minutos que queremos que tarde en apagarse el ordenador.
Tal y como se observa en la captura de pantalla, justo después de ejecutarse el comando empezará la cuenta atrás para apagar el ordenador.
Apagado del ordenador en 30 minutos
Una vez transcurridos los 30 minutos nuestro ordenador se apagará de forma irremediable consiguiendo así nuestro objetivo.
Si durante el proceso de cuenta atrás queremos abortar el proceso tan solo tenemos que presionar la combinación de teclas Ctrl+C con la terminal activa.

Apagar el ordenador a una hora determinada

En el apartado anterior hemos visto como apagar el ordenador después de un tiempo determinado que puede ser una hora, dos horas, etc. Si lo que queremos es apagar el ordenador a una hora en concreto lo podemos hacer ejecutando este comando en la terminal:
sudo shutdown -h 23:50
El significado de cada uno los términos del comando son los siguientes:
sudo: Porque el programa shutdown precisa permisos de superusuario para ejecutarse.
shutdown: Es el programa que permite programar el apagado del ordenador.
-h: Indica la acción a realizar una vez pasado un tiempo determinado. En este caso la acción es la acción halt (-h). Por lo tanto una vez pasado el tiempo que queramos el ordenador se apagará.
23:50: Indicamos la hora en la que queremos que se apague el ordenador. En mi caso he indicado que sean las 23 horas y 50 minutos.
Después de ejecutar el comando, tal y como se puede ver en la captura de pantalla, se iniciará la cuenta atrás para apagarse el ordenador:
Programar el apagado del ordenador a una hora
Si durante el proceso de cuenta atrás queremos abortar el proceso tan solo tenemos que presionar la combinación de teclas Ctrl+C con la terminal activa

MÉTODO 2: PROGRAMAR EL APAGADO DEL ORDENADOR MEDIANTE UN SCRIPT

Con un simple Script también podemos programar el apagado automático del ordenador. Para crear el script abrimos la terminal. Justo al abrir la terminal creamos el archivo apagar.sh ejecutando el siguiente comando en la terminal:
touch apagar.sh
Una vez creado el archivo lo abriremos ejecutando el siguiente comando en la terminal:
nano apagar.sh
Una vez abierto el editor de texto nano pegaremos el siguiente código:
#!/bin/bash
clear
echo " *** SCRIPT PARA EL APAGADO DEL EQUIPO *** "
echo " SELECCIONA UNA OPCIÓN:"
echo " 1.-Apagar equipo ahora"
echo " 2.-Reiniciar equipo ahora"
echo " 3.-Asignar hora de apagado del equipo"
echo " 4.-Apagar equipo a los xx minutos"
echo " 5.-Salir"
echo ""
read -p "OPCIÓN: " OPCION
case $OPCION in
1) sudo halt;;
2) sudo reboot;;
3) echo -n " ¿ A qué hora ?: "
read hora
sudo shutdown -h $hora;;
4)echo -n " ¿ En cuántos minutos se apagará el equipo?: "
read minutos
sudo shutdown -h $minutos;;
5) exit;;
*) echo " OPCIÓN NO VÁLIDA "
exit 1;;
esac
exit 0
Fuente del script
Una vez copiado el texto guardamos los cambios y cerramos el fichero. El siguiente paso será otorgar los permisos necesarios para que se pueda ejecutar el script. Para ello ejecutamos el siguiente comando en la terminal:
sudo chmod +x apagar.sh
Una vez ejecutado el comando ya podemos usar el script. Para ello ejecutamos el siguiente comando en la terminal:
sh ./apagar.sh
Justo después de ejecutar el script, tal y como se puede ver en la captura de pantalla, podremos programar la hora en que queremos que se apague nuestro ordenador.
programar el apagado mediante un script
Si queremos evitar tener que abrir la terminal cada vez que queramos ejecutar el script podemos crear un lanzador en el escritorio. Para ello ejecutamos el siguiente comando en la terminal:
touch /home/joan/Escritorio/Apagar
Después de ejecutar el comando se creará un archivo con nombre Apagar en nuestro escritorio. Para que este archivo se convierta en un lanzador de escritorio tenemos que editar su contenido. Para editar su contenido tenemos que teclear el siguiente comando en la terminal:
nano /home/joan/Escritorio/Apagar
Una vez se abra el editor de textos nano pegaremos el siguiente texto:
[Desktop Entry]
Name=Apagar
Name[de_DE]=Apagar
Exec=/home/joan/apagar.sh
Terminal=true
Type=Application
Icon=home/joan/Imágenes/red_glasses
Nota: Las partes del texto a pegar que están en rojo las tendréis que modificar en función los siguientes aspectos. En la variable Exec hay que poner la ruta del script que hemos creado. En la variable Icon hay que poner la ruta del icono que queremos que tenga nuestro lanzador.
Una vez pegado el contenido en el archivo Apagar guardamos los cambios y cerramos el fichero. A partir de estos momentos, cada vez que cliquemos encima del nuevo icono que tenemos en el escritorio se ejecutará el script para programar el apagado de nuestro ordenador.
Nota: Existen formas alternativas para ejecutar el script sin tener que abrir una terminal. En vez de crear un lanzador de escritorio podríamos haber creado un enlace duro o introducir el script dentro de los menús de la distribución que usamos.

MÉTODO 3: PROGRAMAR EL APAGADO DEL ORDENADOR USANDO UN PROGRAMA

Las personas a las que no les guste la terminal, programar scripts o simplemente prefieren no complicarse la vida, pueden optar por instalar un programa con interfaz gráfica para programar el apagado del ordenador.
Existen varios programas disponibles, pero en mi caso detallaré como usar qshutdown por los siguientes motivos:
  1. Es muy sencillo de usar.
  2. Funciona a la perfección.
  3. Está presente en los repositorios de la gran mayoría de distros Linux.
Para instalar qshutdown abriremos una terminal y ejecutaremos el siguiente comando:
sudo apt-get install qshutdown
Una vez instalado el programa ya lo podemos abrir sin ningún tipo de problema. Una vez abierto el programa verán una interfaz gráfica parecida a la siguiente:
Programar el apagado con qshutdown
Tal y como se puede en la captura de pantalla, tan solo hay que detallar el día y la hora en que queremos apagar el ordenador. Una vez seleccionadas las opciones que queramos tan solo tenemos que presionar el botón Aceptar y empezará la cuenta atrás para apagar el ordenador.

MÉTODO 4: PROGRAMAR EL APAGADO DEL ORDENADOR DE FORMA AUTOMÁTICA MEDIANTE CRON

Finalmente existe una ultima opción para programar el apagado del ordenador. Esta opción es utilizando cron. Posiblemente sea la opción que presente más opciones de configuración, pero con toda seguridad es la opción menos amigable de configurar.
Para programar el apagado de nuestro equipo con cron tenemos que ejecutar el siguiente comando en la terminal:
sudo crontab -e
Una vez abierto el editor de texto tenemos que editar el contenido del fichero crontab para programar el apagado del ordenador. La estructura a usar para programar el apagado del ordenador es la siguiente:
m h dom mon dow /sbin/shutdown -h now
Cada una de las partes en color rojo de este comando las tendréis que reemplazar por los siguientes términos:
m: Reemplazar m por un número entre el 0 y el 59. Este número indica el minuto en el que queremos que se apague nuestro ordenador.
h: Reemplazar h por un número entre el 0 y el 23. Este número indica la hora en la que queremos que se apague nuestro ordenador.
dom: Reemplazar dom por un número entre el 1 y el 31. Este número indica el día del mes en el que queremos que se apague nuestro ordenador. Si queremos que nuestro ordenador se apague todos los días del mes hay que reemplazar m por un *
mon: Reemplazar mon por un número entre el 1 y el 12. Este número indica el número de mes en el que queremos que se apague nuestro ordenador. Si queremos que nuestro ordenador se apague todos los meses hay que reemplazar mon por un *
dow: Reemplazar dow por un número entre el 0 y el 6. Este número indica el día de la semana en el que queremos que se apague nuestro ordenador. Si escribimos un cero se apagará el domingo y si un 6 se apagará el sábado. Si queremos que nuestro ordenador se apague todos los días deberemos reemplazar dow por un *.
/sbin/shutdown -h now: Esta parte del comando no hay que reemplazarla. Esta parte del comando es la que hace que el ordenador se apague una vez transcurrido el tiempo fijado en los parámetros anteriores.
Algunos ejemplos de comandos a introducir en el archivo crontab para programar el apagado de nuestro ordenador son los siguientes:

Apagar el ordenador todos los días a las 23 horas y 30 minutos

Si queremos programar el apagado del ordenador todos los días a las 23:30 horas, tal y como se puede ver en la captura de pantalla, tenemos que introducir el siguiente comando dentro del archivo contrab:
30 23 * * * /sbin/shutdown -h now
Programar apagado con Cron
Una vez introducido el comando guardamos los cambios y cerramos el fichero.
Para que los cambios surjan efecto tenemos que reiniciar el servicio cron. Para ello ejecutamos el siguiente comando en la terminal:
sudo service cron restart
Una vez reiniciado el servicio el proceso ha finalizado.

Apagar el ordenador a las 23 horas y 30 minutos todos los domingos

Si queremos que nuestro ordenador se apague a las 23:30 horas pero únicamente los domingos, tenemos que introducir el siguiente comando dentro del archivo contrab:
30 23 * * 0 /sbin/shutdown -h now
Una vez introducido el comando guardamos los cambios y cerramos el fichero.
Para que los cambios surjan efecto tenemos que reiniciar el servicio cron. Para ello ejecutamos el siguiente comando en la terminal:
sudo service cron restart
Una vez reiniciado el servicio el proceso ha finalizado.

Apagar el ordenador a las 23 horas y 30 minutos al 15 de Junio

Si queremos que nuestro ordenador se apague a las 23:30 horas del día 15 de Junio, tenemos que introducir el siguiente comando dentro del archivo contrab:
30 23 15 6 * /sbin/shutdown -h now
Una vez introducido el comando guardamos los cambios y cerramos el fichero.
Para que los cambios surjan efecto tenemos que reiniciar el servicio cron. Para ello ejecutamos el siguiente comando en la terminal:
sudo service cron restart
Una vez reiniciado el servicio el proceso ha finalizado.

Apagar el ordenador a las 23 horas y 30 minutos el 15 de Junio si es martes

Si queremos que nuestro ordenador se apague los martes que sean 15 de Junio a las 23:30 horas, tenemos que introducir el siguiente comando dentro del archivo contrab:
30 23 15 6 2 /sbin/shutdown -h now
Una vez introducido el comando guardamos los cambios y cerramos el fichero.
Para que los cambios surjan efecto tenemos que reiniciar el servicio cron. Para ello ejecutamos el siguiente comando en la terminal:
sudo service cron restart
Una vez reiniciado el servicio el proceso ha finalizado.


agosto 16, 2018

agosto 14, 2018

Listar tablas y bases de datos en Postgresql


Este artículo explica brevemente cómo listar bases de datos (lo que equivale a ejecutar show databases en MySQL) y tablas (show tables en MySQL) en Postgres, ejecutando consultas desde línea de comandos con la herramienta psql. La primera limitación que se encuentra un usuario de MySQL al interactuar por primera vez con un gestor de bases de datos Postgres.



A pesar de que existen herramientas gráficas, como pgAdmin, es necesario conocer cómo se realizan las tareas desde línea de comandos para estar preparado para cuando las papas queman.
La herramienta psql provee una terminal interactiva contra servidores de bases de datos PostgreSQL. Es posible utilizarla de forma local (ejecutar psql directamente en la consola del servidor de bases de datos), o contra un servidor remoto especificando el host y puerto mediante los parámetros -h y -p:
root@dbserver42:~# psql -U postgres
psql (9.3.3)
Type "help" for help.

postgres=#
Para listar las bases de datos de un servidor Postgres (luego de conectarse al mismo) ejecutar el comando \l:
postgres=# \l
                                     List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |      Access privileges
-----------+----------+----------+-------------+-------------+-----------------------------
 prueba    | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 | postgres=CTc/postgres      +
           |          |          |             |             | rol_prueba=Tc/postgres     +
           |          |          |             |             | rol_readonly=Tc/postgres
 postgres  | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 |
 template0 | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 | =c/postgres                +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 | postgres=CTc/postgres      +
           |          |          |             |             | =c/postgres
(4 rows)

postgres=#
Luego, para cerrar la terminal psql, ejecutar el comando \q:
postgres=# \q
root@dbserver42:~#
También es posible listar las bases de datos ejecutando directamente el comando psql -l en la terminal bash:
root@dbserver42:~# psql -U postgres -l
                                     List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |      Access privileges
-----------+----------+----------+-------------+-------------+-----------------------------
 prueba    | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 | postgres=CTc/postgres      +
           |          |          |             |             | rol_prueba=Tc/postgres     +
           |          |          |             |             | rol_readonly=Tc/postgres
 postgres  | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 |
 template0 | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 | =c/postgres                +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | es_AR.UTF-8 | es_AR.UTF-8 | postgres=CTc/postgres      +
           |          |          |             |             | =c/postgres
(4 rows)

En el listado se observan 4 bases de datos, de las cuales 3 son bases de datos de sistema (no se deben eliminar). Cada vez que se crea una base de datos con el comando CREATE DATABASE, en realidad se está copiando una base de datos existente (por defecto el modelo estándar de bases de datos "template1"). Entonces, la base de datos "template1" es una plantilla desde la cual se construyen nuevas bases de datos. Si se agregan objetos a esta base de datos, serán copiados en bases de datos subsecuentes cada vez que se utilice el comando CREATE DATABASE. El segundo modelo estándar de bases de datos "template0" contiene los mismos datos que posee inicialmente "template1", es decir los objetos estándar predefinidos por la versión de PostgreSQL. Nunca deben realizarse modificaciones sobre "template0". La tercera base de datos de sistema, "postgres", funciona como base de datos por defecto para gestionar conexiones al servidor de bases de datos por parte de usuarios y aplicaciones. Se crea cuando se inicia un cluster de bases de datos y es una simple copia de "template1". Puede eliminarse (drop) y recrearse si es necesario. Para mayor información ver la documentación oficial de PostgreSQL: 21.3. Template Databases.



Para listar tablas de una base de datos Postgres existe el comando \dt. Conectarse a la base de datos especificando su nombre con el parámetro -d, y luego ejecutar el comando \dt. Por ejemplo el listado de tablas de una base de datos de un sistema Moodle:
root@dbserver42:~# psql -U postgres -d moodle
psql (9.3.3)                                                           
Type "help" for help.                                                  

moodle=# \dt
                      List of relations
 Schema |               Name               | Type  |  Owner
--------+----------------------------------+-------+----------
 public | mdl_assign                       | table | postgres
 public | mdl_assign_grades                | table | postgres
 public | mdl_assign_plugin_config         | table | postgres
 public | mdl_assign_submission            | table | postgres
 public | mdl_assign_user_flags            | table | postgres
 public | mdl_assign_user_mapping          | table | postgres
 public | mdl_assignfeedback_comments      | table | postgres
 public | mdl_assignfeedback_file          | table | postgres
 public | mdl_assignment                   | table | postgres
 public | mdl_assignment_submissions       | table | postgres
 public | mdl_assignsubmission_file        | table | postgres
 public | mdl_assignsubmission_onlinetext  | table | postgres
 public | mdl_backup_controllers           | table | postgres
 public | mdl_backup_courses               | table | postgres
 public | mdl_backup_files_template        | table | postgres
 public | mdl_backup_ids_template          | table | postgres
 public | mdl_backup_logs                  | table | postgres
 public | mdl_badge                        | table | postgres
 public | mdl_badge_backpack               | table | postgres
 public | mdl_badge_criteria               | table | postgres
 public | mdl_badge_criteria_met           | table | postgres
--Más--
Manual de PostgreSQL 9.3: PostgreSQL 9.3.4 Documentation

Fuente: https://www.linuxito.com/programacion/337-como-listar-tablas-y-bases-de-datos-en-postgres

Montar partición formateada en sistema de archivos ext4 en Linux

Mounting an ext4 File System

An ext4 file system can be mounted with no extra options, same as any other file system:
~]# mount block_device /mount/point
The default mount options are optimal for most users. Options, such as acl, noacl, data, quota, noquota, user_xattr, nouser_xattr, and many others that were already used with the ext2 and ext3 file systems, are backward compatible and have the same usage and functionality. Also, with the ext4 file system, several new ext4-specific mount options have been added, for example:
barrier / nobarrier
By default, ext4 uses write barriers to ensure file system integrity even when power is lost to a device with write caches enabled. For devices without write caches, or with battery-backed write caches, you disable barriers using the nobarrier option:
~]# mount -o nobarrier block_device /mount/point
stripe=value
This option allows you to specify the number of file system blocks allocated for a single file operation. For RAID5 this number should be equal the RAID chunk size multiplied by the number of disks.
journal_ioprio=value
This option allows you to set priority of I/O operations submitted during a commit operation. The option can have a value from 7 to 0 (0 is the highest priority), and is set to 3 by default, which is slightly higher priority than the default I/O priority.
Default mount options can be also set in the file system superblock using the tune4fs utility. For example, the following command sets the file system on the /dev/mapper/VolGroup00-LogVol02 device to be mounted by default with debugging disabled and user-specified extended attributes and Posix access control lists enabled:
~]# tune4fs -o ^debug,user_xattr,acl /dev/mapper/VolGroup00-LogVol02
For more information on this topic, refer to the tune4fs(8) manual page.
An ext3 file system can also be mounted as ext4 without changing the format, allowing it to be mounted as ext3 again in the future. To do so, run the following command on a block device that contains an ext3 file system:
~]# mount -t ext4 block_device /mount/point
Doing so will only allow the ext3 file system to use ext4-specific features that do not require a file format conversion. These features include delayed allocation and multi-block allocation, and exclude features such as extent mapping.
Warning
Using the ext4 driver to mount an ext3 file system has not been fully tested on Red Hat Enterprise Linux 5. Therefore, this action is not supported because Red Hat cannot guarantee consistent performance and predictable behavior for ext3 file systems in this way.
For more information on mount options for the ext4 file system, see Section 2.2.2, “Specifying the Mount Options” and the mount(8) manual page.
Note
If you want to enable persistent mounting of the file system, remember to update the /etc/fstab file accordingly. For example:
/dev/mapper/VolGroup00-LogVol02    /test    ext4    defaults    0 0

Fuente: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html/deployment_guide/s1-filesystem-ext4-mount

Formatear discos duros con Linux

Linux Hard Disk Format Command

last updated in Categories , , ,
Q. I’ve installed a new 250GB SATA hard disk on our office CentOS Linux server. How do I format a hard disk under Linux operating system from a shell prompt?

A.. There are total 4 steps involved for hard disk upgrade and installation procedure:



Step #1 : Partition the new disk using fdisk command

Following command will list all detected hard disks:
# fdisk -l | grep '^Disk'
Output:
Disk /dev/sda: 251.0 GB, 251000193024 bytes
Disk /dev/sdb: 251.0 GB, 251000193024 bytes
A device name refers to the entire hard disk. For more information see Linux partition naming convention and IDE drive mappings.
To partition the disk – /dev/sdb, enter:
# fdisk /dev/sdb
The basic fdisk commands you need are:
  • m – print help
  • p – print the partition table
  • n – create a new partition
  • d – delete a partition
  • q – quit without saving changes
  • w – write the new partition table and exit

Step#2 : Format the new disk using mkfs.ext3 command

To format Linux partitions using ext2fs on the new disk:
# mkfs.ext3 /dev/sdb1

Step#3 : Mount the new disk using mount command

First create a mount point /disk1 and use mount command to mount /dev/sdb1, enter:
# mkdir /disk1
# mount /dev/sdb1 /disk1
# df -H

Step#4 : Update /etc/fstab file

Open /etc/fstab file, enter:
# vi /etc/fstab
Append as follows:
/dev/sdb1               /disk1           ext3    defaults        1 2
Save and close the file.

Task: Label the partition

You can label the partition using e2label. For example, if you want to label the new partition /backup, enter
# e2label /dev/sdb1 /backup
You can use label name insted of partition name to mount disk using /etc/fstab:
LABEL=/backup /disk1 ext3 defaults 1 2


Fuente: https://www.cyberciti.biz/faq/linux-disk-format/ 

Desinstalar PostgreSQL con Yum Linux

$ yum remove postgres\*
$ mv /var/lib/pgsql /var/lib/old.pgsql

Fuente: https://www.centos.org/forums/viewtopic.php?t=32438

Instalar o actualizar PostgreSQL 8.4 con Yum

Este es una guía para instalar o actualizar PostgreSQL 8.4 con Yum

In this exercise, we'll go thru our steps for upgrading a Redhat Enterprise Linux 64-bit PostgreSQL box from PostgreSQL 8.3 to PostgreSQL 8.4. If you don't have any kind of PostgreSQL installed on your box, you can skip the Upgrade step.
UPDATE - since Devrim's move from Command prompt - he has started a new yum repository. You may want to use this one instead since it seems more up to date than the other. http://yum.pgrpms.org/
UPDATEWe have instructions for installing PostgreSQL 9.0 via yum.

Updgrading from PostgreSQL 8.* to PostgreSQL 8.4

If you are starting from scratch -- just skip this section.
If you are upgrading from 8.4.0 to 8.4.1 you can get away with a simple
yum update postgresql
and skip the rest of this article.
If you are upgrading from PostgreSQL 8.3 to 8.4, in theory you can use PgMigrator, but in practice, particularly with a Yum install, you are bound to run into obstacles. If you are running an older version, you must dump and restore.

PgMigrator difficulties
For starters we did try upgrading our database using the PgMigrator but were unsuccessful. Keep in mind these comments are not flames -- just things we see that are obstacles to upgrade and perhaps can be made less painful for future migration work and we consider important to increase PostgreSQL adoption.
This process turns out to be a bit more difficult if you are using Yum for a couple of reasons.
  1. Yum and I think most distros always install in the same location -- the bin folder and bin/pgsql so its hard to tell which files you need and pgMigrator requires both the new binaries and the old binaries to complete. To work around that problem -- we did compile from scratch a PostgreSQL 8.3 that matched our 8.3 version by downloading the source and compile and setting --prefix== another location just to make the migrator happy.
  2. pg_migrator was not happy with the location of pg_migrator.so -- this is probably a 64-bit issue and one we run into a lot. No biggies just symlink
    ln -s /usr/lib64/pg_migrator.so /usr/local/pgsql84/lib/pg_migrator.so
  3. The third obstacle we ran into was an insurmountable one. Or rather one we didn't really care to tackle because we figured trying to work around it would bite us in the future and also prevent us from using Yum which we really like using by the way. This is that the default date time storage between 8.3 and 8.4 has changed. So it seems to be able to migrate or at least on our 64-bit Linux box, we would need to recompile the PostgreSQL 8.4 to ignore which sounded like a future management nightmare waiting to happen. The error you get is this Old and new pg_controldata date/time storage types do not match. You will need to rebuild the new server with configure --disable-integer-datetimes or get server binaries built with those options.
    I suspect this will become a non-issue in PostgreSQL 8.4 to 8.5
    Please see Greg's notes about suggestions for this issue
Using the tried and true dump/restore but slower more space needed
We were upgrading 800 gb database which reduces down to a 80gb backup file. Space was a concern, but this is a dev box we wanted to blow out and have clean anyway. We had a good last night backup from production so we were in good shape to uninstall and just remove our data folder.
  1. Note location of your old data cluster:
    
    psql –h localhost –U postgres –p 5432
    SELECT setting FROM pg_settings WHERE name='data_directory';
    
      
    Gives something like:
                 setting
    ---------------------------------
    /var/lib/pgsql/data/
    
  2. Make sure to backup at least the .conf files to different location which are located in same folder as data and also make backup of users and other global settings.
    
    mkdir /pgbak
    cp /var/lib/pgsql/data/*.conf /pgbak
    pg_dumpall -h localhost -p 5432 -U postgres --globals-only > /pgbak/globals.sql
    
      
  3. Make backup of each database or whole server. We liked compressed backups of each db since we don't always have space for a non-compressed and sometimes want to only selectively restore part of a db. Repeat the below for each db.
    
       /usr/bin/pg_dump -i -h localhost -U postgres -F c -b -v -f "/pgbak/mydb_beforeupgrade.backup" mydb
      
      
  4. Shut down the old service.
    service postgresql stop
  5. Uninstall it.
    yum erase postgresql You should get a screen that looks something like this and choose y to uninstall:
    Dependencies Resolved
    
    ================================================================================
     Package                Arch       Version                  Repository     Size
    ================================================================================
    Removing:
     postgresql             x86_64     8.3.7-1PGDG.rhel5        installed     4.7 M
    Removing for dependencies:
     postgresql-contrib     x86_64     8.3.7-1PGDG.rhel5        installed     1.3 M
     postgresql-devel       x86_64     8.3.7-1PGDG.rhel5        installed     4.9 M
     postgresql-plperl      x86_64     8.3.7-1PGDG.rhel5        installed      68 k
     postgresql-server      x86_64     8.3.7-1PGDG.rhel5        installed      12 M
    
    Transaction Summary
    ================================================================================
    Install      0 Package(s)
    Update       0 Package(s)
    Remove       5 Package(s)
    
    Is this ok [y/N]: y
      
  6. If you have space you can move your old cluster.
    mv /var/lib/pgsql/data to /var/lib/pgsql/dataold but if not and you know your backup is sound or this is a dev box just destroy it. You are destroying data so proceed with caution.
    rm -rf /var/lib/pgsql/data

Installing PostgreSQL 8.4.1 from Yum repository

  1. Figure out which OS you are on. Note the pgdn repository only works with CentOS and Redhat 4 and above, or Fedora.
    uname –a
      
    If you see a el5 you are most likely running an enterprise linux. If you see x64, then you have a 64-bit installation.
    vi /etc/redhat-release
    May help narrow it down.
  2. Download the right file - from http://yum.pgsqlrpms.org/reporpms/8.4/. In our case we were running a redhat EL distro so we downloaded.
    cd /pgbak
    wget  http://yum.pgsqlrpms.org/reporpms/8.4/pgdg-redhat-8.4-1.noarch.rpm 
      
  3. Install the rpm
    rpm -ivh pgdg-redhat-8.4-1.noarch.rpm
  4. To get a list of postgresql related stuff:
    yum list | grep postgresql

    If you see postgresql from other repositories besides pgdg84, then you need to exclude postgresql from coming from other repositories by following the below instructions excerpted from PostgreSQL How to Yum
    * As root, cd /etc/yum.repos.d
    
        * Edit distro's .repo file:
              o On Fedora, edit fedora.repo and fedora-updates.repo, [fedora] sections
              o On CentOS, edit CentOS-Base.repo, [base] and [updates] sections.
              o On Red Hat, edit edit /etc/yum/pluginconf.d/rhnplugin.conf [main] section.
                    + Add to the bottom of the section:
    
                      exclude=postgresql*
    
  5. To get a listing of what is available in the PostgreSQL 8.4.1 yum
    yum list | grep pgdg84
  6. Install what you want: The developer package is needed to compile things like PostGIS if you are going to compile your own. the name would be different if you are on a 32-bit box.
    yum install postgresql-devel.x86_64
    yum install postgresql-server
    yum install postgresql-contrib
    yum install postgresql-plperl 
  7. If you decide to use non-default location for data, you need to edit the postgresql service sysconfig file and change the PGDATA argument.
    vi /etc/rc.d/init.d/postgresql
    vi /etc/sysconfig/pgsql/postgresql
    (For vi you do a I to insert a line -- ESC then :w to save and exit) NOTE: postgresql in sysconfig/pgsql may not exist so you may need to create it and put in a line denoting where you want the data -- something like below
    PGDATA=/var/lib/pgsql/data
  8. Create data cluster:
    
    mkdir /var/lib/pgsql/data
    chown postgres /var/lib/pgsql/data
    su postgres
    initdb -D /var/lib/pgsql/data
       
      

    service postgresql initdb
  9. Set postgresql service restart automatically on reboots.
    su root
    chkconfig --list (to see list of services)
    chkconfig postgresql on
  10. Start the service.
    service postgresql start
  11. Copy config, Restore accounts -- this is needed only if you were upgrading.
      
    cp /pgbak/pg_hba.conf /yourdatacluster/
    (NOTE: for postgresql.conf -- you are best manually editing that since its changed considerably from 8.3 to 8.4)
    vi /var/lib/pgsql/data/postgresql.conf (-- use your old file as reference)
    psql -U postgres -d postgres -f /pgbak/globals.sql
      
  12. Install pgadmin pack if you want to be able to change config settings directly from pgAdmin III
    psql -U postgres -d postgres -f /usr/share/pgsql/contrib/adminpack.sql
  13. Restart for whatever config changes you made to take effect
    service postgresql restart
  14. If you have database backups, first create a blank db for each and then restore with pg_restore.

Ubicación de los repositorios rpm de Linux Fedora fc13

Ubicación de los repositorios rpm de Linux Fedora fc13

/etc/yum.repos.d/

Obtener la versión de Postgresql

Para obtener la versión instalada de postgresql se puede usar el comando psql

$ psql -V
psql (PostgreSQL) 8.4.8

agosto 13, 2018

Instalación fácil de Cerbot

$dnf install python3-certbot-apache

$certbot -a dns-plugin -i apache -d "*.dominio.com" -d dominio.com       --server https://dominio.com


$wget https://dl.eff.org/certbot-auto
$chmod a+x ./certbot-auto
$ wget -N https://dl.eff.org/certbot-auto.asc
$ gpg2 --recv-key A2CFB51FA275A7286234E7B24D17C995CD9775F2
$ gpg2 --trusted-key 4D17C995CD9775F2 --verify certbot-auto.asc certbot-auto
$./certbot-auto --apache -d dominio.com
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
Created redirect file: le-redirect-sua.linux.mx:443.conf
Rollback checkpoint is empty (no changes made?)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://dominio.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=dominio.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/sua.linux.mx/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/sua.linux.mx/privkey.pem
   Your cert will expire on 2018-11-08. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot-auto
   again with the "certonly" option. To non-interactively renew *all*
   of your certificates, run "certbot-auto renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le






¿Cómo poner el conteo de las filas en una consulta en MySql?

 ¿Cómo poner el conteo de las filas en una consulta en MySql? SELECT  @rownum := @rownum + 1 AS contador,  /*Contador*/ t.*  /* nombre d...