Mostrando entradas con la etiqueta GNU/Linux. Mostrar todas las entradas
Mostrando entradas con la etiqueta GNU/Linux. Mostrar todas las entradas

2023-05-27

Split text file into smaller multiple text file using command line

You can use:

split -l 5000 filename.txt

That creates files:

xaa
xab
aac
xad
xbe
aaf

Or you can use:

split -l 5000 -d --additional-suffix=.txt $FileName file

Where:

  • -l 5000: split file into files of 5,000 lines each.
  • -d: numerical suffix. This will make the suffix go from 00 to 99 by default instead of aa to zz.
  • --additional-suffix: lets you specify the suffix, here the extension
  • $FileName: name of the file to be split.
  • file: prefix to add to the resulting files.
Use man split for more info

P.S: Borrowed from here

Happy hacking!!!

2023-04-03

I want to usa a socks5 proxy, I want to install the simplest one that runs in linux. [ChatGPT]

One simple option for setting up a SOCKS5 proxy on Linux is to use the "dante" package, which provides a lightweight and easy-to-configure SOCKS server.

Here are the basic steps to install and configure dante as a SOCKS5 proxy on a Linux server:

  1. Install the dante-server package using your distribution's package manager. For example, on Ubuntu, you can run:

    sql
    sudo apt-get update sudo apt-get install dante-server
  2. Edit the /etc/socks.conf file to configure the proxy settings. Here's an example configuration file that allows connections from any IP address and requires authentication with a username and password:

    yaml
    logoutput: /var/log/socks.log internal: eth0 port = 1080 external: eth0 method: username # Require username/password authentication user.privileged: root user.notprivileged: nobody user.libwrap: nobody client pass { from: 0.0.0.0/0 to: 0.0.0.0/0 log: connect disconnect error method: username # Require username/password authentication } socksmethod: username # Require username/password authentication

    Note: You should replace eth0 with the name of the network interface that you want to use for the proxy server.

  3. Start the dante server using the command:

    sql
    sudo systemctl start danted.service

    You can also enable the service to start automatically at boot time using the command:

    bash
    sudo systemctl enable danted.service

That's it! Your SOCKS5 proxy should now be up and running on port 1080, and you can configure your applications to use it by specifying the IP address and port of the Linux server as the SOCKS proxy. For example, in a web browser, you can set the SOCKS proxy in the network settings to "127.0.0.1:1080" (assuming you're running the browser on the same machine as the proxy).

Happy hacking!!!

2023-02-24

Merge two pdfs in the same page in GNU/Linux (Debian/Ubuntu)

If you have two pdfs and you want to print them in a single page, you can start by merging both in a single page in a 3rd pdf.

Maybe you need to install using the following:

sudo apt install texlive-extra-utils

Then you can merge using one of the following commands:

  • Vertical
    pdfjam *.pdf --nup 1x2 --outfile merged.pdf
  • Horizontal
    pdfjam *.pdf --nup 2x1 --outfile merged.pdf
  • Landscape
    pdfjam *.pdf --nup 2x1 --landscape --outfile merged.pdf

Happy hacking!!!

2018-07-17

How to delete the mp3 file of the current audacious song

I you want to delete the mp3 file of the current song playing in audacious just follow these steps:

  • First add the following text to the change song plugin for the starting songs
    echo "%f"<audacious.tx
  • now execute this command each time you want to delete a song.
    rm "`cat audacious.txt|sed -e 's/%20/ /g' |sed -e 's/%26/\&/g' |sed -e 's/file:..//g'`"
    

Maybe you'll have to add more sed commands depending on the name of your songs.

Happy hacking!!!

2018-06-28

How to recreate /etc/nginx directory

Maybe you removed the /etc/nginx directory or you messed around with it, how can you recreate it?

To recreate it, first uninstall using purge to remove even configuration files and records:

sudo apt-get purge nginx nginx-common nginx-full

then reinstall:

sudo apt-get install nginx

If above doesn't work for you, you can also try using --force-confmiss option of dpkg.

sudo dpkg --force-confmiss -i /var/cache/apt/archives/nginx-common_*.deb

Borrowed from stackoverflow

2018-05-11

Concatenar imágenes usando la línea de comandos en GNU/Linux

Para concatenar una serie de imágenes usando la línea de comandos, para evitar la tediosa tarea de hacerlo con una aplicación como gimp o similar, se puede usar GraphicsMagick (un fork de ImageMagick). Para instalarlo se ejecuta el comando:

sudo apt-get install graphicsmagick

Una vez instalado ejecutamos gm que es el comando de GraphicsMagick. Ejemplos:

  • Concatenar dos imágenes en vertical:
  • gm montage -mode concatenate -tile 1x2 1.jpg 2.jpg resultado.jpg
  • Concatenar seis imágenes en horizontal:
  • gm montage -mode concatenate -tile 2x1 1.jpg 2.jpg resultado.jpg
  • Concatenar seis imágenes en un mosaico 2x3:
  • gm montage -mode concatenate -tile 2x3 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg 6.jpg resultado.jpg

Cómo reducir el tamaño de archivos PDF en GNU/Linux

Para reducir el tamaño de archivos PDF en GNU/Linux, necesitaremos tener instalado GhostScript para lo cual podemos ejecutar el comando:

sudo aptitude install ghostscript

Con GhostScript instalado ya se puede comprimir con el situiente comando:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=pdf-reducido.pdf pdf-original.pdf

Donde -dPDFSETTINGS=/ebook nos indica la calidad del PDF reducido y cuyos posibles valores para /ebook son:

  • /screen (72 dpi, baja calidad y destinado a ver por pantalla)
  • /ebook (150 dpi, calidad media y destinado a leer como ebook)
  • /printer (300 dpi, alta calidad y destinado a imprimirse)
  • /prepress (300 dpi, alta calidad preservando el color y destinado a imprimirse)
  • /default (viene a ser lo mismo /screen)

Además existe un script, que tendremos que descargar e instalar a mano, que puede facilitarnos algo el trabajo. Para descargarlo ejecutaremos:

wget http://www.alfredklomp.com/programming/shrinkpdf/shrinkpdf.sh
chmod +x shrinkpdf.sh

Si además queremos que se ejecute desde cualquier ruta y por cualquier usuario:

sudo mv shrinkpdf.sh /usr/bin/shrinkpdf.sh

Ahora ya puedes reducirlo ejecutando:

shrinkpdf.sh pdf-original.pdf pdf-reducido.pdf

2016-11-30

Como usar Tor para anonimizarte con Debian o Ubuntu

En estos días de la Ley mordaza en España y de otros sitios donde hablar públicamente puede salir caro, es necesario disponer de herramientas como tor. Hay que tener en cuenta que esto te libra de la policía, de la censura, de espias en tu casa o empresa de modo bastante robusto, pero sin llegar a la oscuridad total para grandes agencias como la NSA. Si eres un terrorista o un pederasta, probablemente el CNI (o servicio de inteligencia equivalente de tu País) podría pedir a la NSA que le diga quien eres e irás a la cárcel y yo me alegraré.

Dicho esto empecemos por el principo (recuerda que solo Debian y Ubuntu, los de Windows buscaos la vida que yo ya no lo uso):

  • Instalar tor:
    sudo apt-get install tor
  • Iniciar tor (normalmente se iniciará solo):
    sudo /etc/init.d/tor start
  • Parar tor:
    sudo /etc/init.d/tor stop
  • Reiniciar tor:
    sudo /etc/init.d/tor restart

Probablemente, esto podría cambiar con el tiempo, tor colocará un proxy SOCKS v5 en 127.0.0.1:9050, así que tienes que decirle a tu navegador que lo use para todo. Aquí tienes una captura de ejemplo con los pasos a seguir en firefox.

Has de tener en cuenta que no puedes usarlo en un navegador con plugins, ya que esto reduce la efectividad de tor, así que lo mejor es que uses un navegador para cosas normales y dejes otro navegador sin plugins ninguno para usar tor, salvo que tu necesidad sea muy baja como por ejemplo publicar cosas en Facebook con un usuario anónomio y denunciar a tu vecino por las cacas de perro que abandona o al policía de turno que aparca mal, o fuma en un establecimiento público. En estos casos la policía no podrá obtener tu identidad, ya que dudo que la NSA gaste recursos para eso y Facebook, Twitter o Blogger tampoco.

Por último te animo a instalarlo para dar servicio de anonimato a los disidentes de países como China, Cuba, Arabia Saudí, Marruecos, Síria, o la misma España, aunque aquí sea solo para evitar multas. O a saltarse la censura a usuarios normales tras cortafuegos masivos como el de China. O la discriminación por paises de algunas webs.

Por último si quieres que tu salida sea por un país concreto para evitar problemas con Facebook o la discriminación por ip de algunas webs tienes que modificar el archivo /etc/tor/torrc y añadir estas dos líneas, donde za es el código iso del país, en este caso Sudáfrica:

ExitNodes {za}
StrictNodes 1

Para editarlo puedes usar este comando

sudo gedit /etc/tor/torrc

Para saber más puedes ir directo a la fuente en la FAQ:

https://www.torproject.org/docs/faq

Happy Hacking!!!


2016-08-21

2015-06-28

GNU/Linux command line sortcuts

The following keyboard shortcuts are incredibly useful and will save you loads of time:

  • CTRL + U – Cuts text up until the cursor.
  • CTRL + K – Cuts text from the cursor until the end of the line
  • CTRL + Y – Pastes text
  • CTRL + E – Move cursor to end of line
  • CTRL + A – Move cursor to the beginning of the line
  • ALT + F – Jump forward to next space
  • ALT + B – Skip back to previous space
  • ALT + Backspace – Delete previous word
  • CTRL + W – Cut word behind cursor
  • Shift + Insert – Pastes text into terminal

Borrowed from here

2013-09-05

Ubuntu Ramdisk: An Easy Way

I'm doing some code that use Derby (Java DB) and creating every time the database is some time consuming. It may be solved using a ram disk, this is the ubuntu way (maybe most GNU/Linux way).

mkdir -p /tmp/ram
sudo mount -t tmpfs -o size=512M tmpfs /tmp/ram/

more info here

2013-03-26

Cómo instalar el sdk de android en /opt para todos los usuarios en GNU/Linux

Estoy reinstalando todo en mi ordenador de escritorio actual (epi) (yo uso el abecedario a nombrarlos, como los huracanes, aunque tiene alguna letra más en el interior). Estoy instalando el SDK de Android y me gusta instalado en /opt, por lo que he descargado y descomprimido usando tar, mv, chown, ... entonces me quedé atascado en que los permisos de ejecución/búsqueda (x) eran sólo para el propietario. Luego, utilizando man chmod encontré la manera correcta de hacerlo.

cd /opt

sudo tar xvzf /home/franci/Descargas/android-sdk_r21.1-linux.tgz

sudo chmod +r -R android-sdk-linux/

sudo chmod +X -R android-sdk-linux/

lo nuevo (no lo conocía antes de leer la páginas man de chmod) es +X, le indica a chmod que expanda el atributo de ejecución/búsqueda si uno de los tres grupos de permisos lo tiene.

Ahora todos los usuarios pueden utilizarlo.

How to install android sdk in /opt for everyone in GNU/Linux

I'm reinstalling everything in my current desktop computer (epi) (I use the alphabet to name them, like hurricanes, althought it has some more letter inside). I'm installing android SDK and I like it installed on /opt, so I downloaded it and unpacked using tar, mv, chown, ... then I got stuck when excution/search permits (x) was only for owners. Then using man chmod I found a way to do it the right way.

cd /opt

sudo tar xvzf /home/franci/Downloads/android-sdk_r21.1-linux.tgz

sudo chmod +r -R android-sdk-linux/

sudo chmod +X -R android-sdk-linux/

the new thing (I didn't know before reading chmod man page) is +X, it says to chmod to expand execution/search attribute if one of the three groups have it.

Now everyone can use it.

2013-03-14

Continuous dmesg output

You can use watch to display dmesg in a tail -f fashion.

watch -d dmesg

Using -n option let you add more time between executions (default is 2 seconds).

You can also add option -d to see differences

watch -d dmesg

Happy hacking!!!

2012-12-06

Truncate a video using mencoder or ffmpeg - Truncar un vídeo usando mencoder o ffmpeg

Here are two methods of truncate a video, using mencoder and ffmpeg. Choose your preferred one:
$ mencoder -ss [start] -endpos [duration] -oac copy -ovc copy [inputfile] -o [outputfile]

$ ffmpeg -vcodec copy -acodec copy -i [inputfile] -ss [start] -t [duration] [outputfile]

2012-07-20

Ubuntu + OracleJava7 [EN]

If you have any problem with java7 provided by Ubuntu (o any other version), you can install Oracle version (or any other), with the following instructions:

  1. Get the current version in order to verify it has changed.

    java -version

    It returns something like this:

    java version "1.7.0_03"
    OpenJDK Runtime Environment (IcedTea7 2.1.1pre) (7~u3-2.1.1~pre1-1ubuntu3)
    OpenJDK Server VM (build 22.0-b10, mixed mode)
    

  2. Unzip de file

    tar -xvf jre-7u5-linux-i586.tar.gz

  3. Move the resulting directory to a path reachable by other users, I like /opt

    sudo mv jre1.7.0_05 /opt

  4. Add this version to the list of available alternatives

    sudo update-alternatives --install /usr/bin/java java /opt/jre1.7.0_05/bin/java 0

  5. Select this version

    sudo update-alternatives --config java

    I returns something like this:

    There are 3 choices for the alternative java (providing /usr/bin/java).
    
      Selection    Path                                           Priority   Status
    ------------------------------------------------------------
    * 0            /usr/lib/jvm/java-7-openjdk-i386/jre/bin/java   1051      auto mode
      1            /opt/jre1.7.0_05/bin/java                       0         manual mode
    
    Press enter to keep the current choice[*], or type selection number:
    

    Select the appropiate option, in this case option 1

  6. Verify the current version has changed.

    java -version

    It returns something like this:

    java version "1.7.0_05"
    Java(TM) SE Runtime Environment (build 1.7.0_05-b06)
    Java HotSpot(TM) Server VM (build 23.1-b03, mixed mode)
    

If any problems with javaws, repeat steps above replacing java by javaws

Bibliography Instalar Oracle Java 7 en Ubuntu 12.04

Ubuntu + OracleJava7 [ES]

Si tienes algún problema con la versión de java7 que proporciona en Ubuntu (o cualquier otra versión) puedes poner la versión de Oracle (u otra), siguiendo las siguientes instrucciones:

  1. Obtener la versión actual para asegurarte después de que ha cambiado.

    java -version

    El resultado será algo parecido a esto:

    java version "1.7.0_03"
    OpenJDK Runtime Environment (IcedTea7 2.1.1pre) (7~u3-2.1.1~pre1-1ubuntu3)
    OpenJDK Server VM (build 22.0-b10, mixed mode)
    

  2. Descomprimir el fichero

    tar -xvf jre-7u5-linux-i586.tar.gz

  3. Mover el directorio resultante a una ruta accesible por todos los usuarios, yo soy partidario de /opt/

    sudo mv jre1.7.0_05 /opt

  4. Se añade esta versión a la lista de alternativa disponibles

    sudo update-alternatives --install /usr/bin/java java /opt/jre1.7.0_05/bin/java 0

  5. Seleccionar esta versión

    sudo update-alternatives --config java

    Se obtiene algo parecido a esto:

    Existen 3 opcioens para la alternativa java (que provee /usr/bin/java).
    
      Selección   Ruta                                           Prioridad  Estado
    ------------------------------------------------------------
    * 0            /usr/lib/jvm/java-7-openjdk-i386/jre/bin/java   1051      modo automático
      1            /opt/jre1.7.0_05/bin/java                       0         modo manual
    
    Pulse  para mantener el valor por omisión [*] o pulse un número de selección: 
    

    Seleccionar la opción adecuada, en este caso 1

  6. Verificar que la versión actual ha cambiado.

    java -version

    Se ha de obtener algo parecido a esto:

    java version "1.7.0_05"
    Java(TM) SE Runtime Environment (build 1.7.0_05-b06)
    Java HotSpot(TM) Server VM (build 23.1-b03, mixed mode)
    

Si hay problemas con javaws repetir los pasos anteriores cambiando java por javaws

Bibliografía Instalar Oracle Java 7 en Ubuntu 12.04

2011-01-08

Añadir nuestro usuario a sudo en Debian

visto en aquí

Para añadir nuestro usuario a sudo en Debian sólo hay que seguir los siguientes pasos:

para instalar sudo (sin no está ya)

apt-get install sudo

Editar el fichero de configuración (no es la forma ortodoxa pero da el apaño).
gedit /etc/sudoers


Y ahora nos vamos a donde pone.

# User privilege specification
root ALL=(ALL) ALL


Y debajo añadimos otra línea con nuestro usuario para que quede así

# User privilege specification
root ALL=(ALL) ALL
franci ALL=(ALL) ALL

2010-12-25

Creando un Videotutorial (screencast) en GNU/Linux

video 1: explicado por yoyo



el comando usado es

ffmpeg -f alsa -ac 2 -i pulse -f x11grab -r 30 -s 1680x1050 -i :0.0 -acodec pcm_s16le -vcodec libx264 -vpre lossless_ultrafast -threads 0 /home/yoyo/Videos/output.mkv


video 2: explicado por odaibanet, en el que se ha basado yoyo

http://www.youtube.com/watch?v=OxAfUabW5Vs

2010-10-31

25 Best GNU/Linux commands

borrowed from urfix blog

As a Linux user you’ll come to learn and love certain commands. Remembering these commands is the toughest part. Some people use cheat-sheets some create scripts, and some just refer to website for their fix. Here I have posted the 25 top command line snippets.

25) sshfs name@server:/path/to/folder /path/to/mount/point
Mount folder/filesystem through SSH
Install SSHFS from http://fuse.sourceforge.net/sshfs.html
Will allow you to mount a folder security over a network.

24) !!:gs/foo/bar
Runs previous command replacing foo by bar every time that foo appears
Very useful for rerunning a long command changing some arguments globally.
As opposed to ^foo^bar, which only replaces the first occurrence of foo, this one changes every occurrence.

23) mount | column -t
currently mounted filesystems in nice layout
Particularly useful if you’re mounting different drives, using the following command will allow you to see all the filesystems currently mounted on your computer and their respective specs with the added benefit of nice formatting.

22) command
Execute a command without saving it in the history
Prepending one or more spaces to your command won’t be saved in history.
Useful for pr0n or passwords on the commandline.

21) ssh user@host cat /path/to/remotefile | diff /path/to/localfile -
Compare a remote file with a local file
Useful for checking if there are differences between local and remote files.

20) mount -t tmpfs tmpfs /mnt -o size=1024m
Mount a temporary ram partition
Makes a partition in ram which is useful if you need a temporary working space as read/write access is fast.
Be aware that anything saved in this partition will be gone after your computer is turned off.

19) dig +short txt .wp.dg.cx
Query Wikipedia via console over DNS
Query Wikipedia by issuing a DNS query for a TXT record. The TXT record will also include a short URL to the complete corresponding Wikipedia entry.

18) netstat -tlnp
Lists all listening ports together with the PID of the associated process
The PID will only be printed if you’re holding a root equivalent ID.

17) dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp
output your microphone to a remote computer’s speaker
This will output the sound from your microphone port to the ssh target computer’s speaker port. The sound quality is very bad, so you will hear a lot of hissing.

16) echo “ls -l” | at midnight
Execute a command at a given time
This is an alternative to cron which allows a one-off task to be scheduled for a certain time.

15) curl -u user:pass -d status=”Tweeting from the shell” http://twitter.com/statuses/update.xml
Update twitter via curl

14) ssh -N -L2001:localhost:80 somemachine
start a tunnel from some machine’s port 80 to your local post 2001
now you can acces the website by going to http://localhost:2001/

13) reset
Salvage a borked terminal
If you bork your terminal by sending binary data to STDOUT or similar, you can get your terminal back using this command rather than killing and restarting the session. Note that you often won’t be able to see the characters as you type them.

12) ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg
Capture video of a linux desktop

11) > file.txt
Empty a file
For when you want to flush all content from a file without removing it (hat-tip to Marc Kilgus).

10) $ssh-copy-id user@host
Copy ssh keys to user@host to enable password-less ssh logins.
To generate the keys use the command ssh-keygen

9) ctrl-x e
Rapidly invoke an editor to write a long, complex, or tricky command
Next time you are using your shell, try typing ctrl-x e (that is holding control key press x and then e). The shell will take what you’ve written on the command line thus far and paste it into the editor specified by $EDITOR. Then you can edit at leisure using all the powerful macros and commands of vi, emacs, nano, or whatever.

8 ) !whatever:p
Check command history, but avoid running it
!whatever will search your command history and execute the first command that matches ‘whatever’. If you don’t feel safe doing this put :p on the end to print without executing. Recommended when running as superuser.

7) mtr google.com
mtr, better than traceroute and ping combined
mtr combines the functionality of the traceroute and ping programs in a single network diagnostic tool.
As mtr starts, it investigates the network connection between the host mtr runs on and HOSTNAME. by sending packets with purposly low TTLs. It continues to send packets with low TTL, noting the response time of the intervening routers. This allows mtr to print the response percentage and response times of the internet route to HOSTNAME. A sudden increase in packetloss or response time is often an indication of a bad (or simply over‐loaded) link.

6 ) cp filename{,.bak}
quickly backup or copy a file with bash

5) ^foo^bar
Runs previous command but replacing
Really useful for when you have a typo in a previous command. Also, arguments default to empty so if you accidentally run:
echo “no typozs”
you can correct it with
^z

4) cd -
change to the previous working directory

3):w !sudo tee %
Save a file you edited in vim without the needed permissions
I often forget to sudo before editing a file I don’t have write permissions on. When you come to save that file and get the infamous “E212: Can’t open file for writing”, just issue that vim command in order to save the file without the need to save it to a temp file and then copy it back again.

2) python -m SimpleHTTPServer
Serve current directory tree at http://$HOSTNAME:8000/

1) sudo !!
Run the last command as root
Useful when you forget to use sudo for a command. “!!” grabs the last run command.