------------------- WSL Ubuntu Linux --------------------------------
user: rayklash
pass: m4ndriva23
---------------- Check distro and c --------------
cat /etc/os-release
lsb_release -a
cat /etc/*-release
hostnamectl
uname -a
cat /proc/version
---------------- Kernel version --------------
uname -a
cat /proc/version
-------------- Setting default WSL --------------------------
--List distros
wsl --list
wsl -s Ubuntu
--Set WSL default distro
wsl --setdefault Ubuntu-20.04
--Set running distro
wsl --distribution Ubuntu-20.04
--Set WSL 2 as default version
wsl --set-default-version 2
--Set wsl version by distro
wsl --set-version [distro name] 1
-----------------------------
--HOME
\\wsl$\Ubuntu\home\rayklash
\\wsl$\Ubuntu-20.04\home\rayklash
-- Check vesion
wsl --list --verbose
-- Stop current wsl
wsl --shutdown
-- Stop specific wsl instance
wsl -t <distribution>
#create systemlinks
ln -s "C:\Users\username\Projects" "\home\username\Projects"
ln -s /usr/bin/python2.7 /usr/bin/python
#Show os info
-- hostnamectl
--uname -r
-- lsb_release -a
--cat /etc/os-release
#Ubuntu termial colors
RGB (48, 10, 36)
Hex Color Code is #300A24
#!/bin/bash
#init login script
~/.bashrc
############## cat #################
# Prompt for text and save to file. Exit with ^D
cat - >> doc.txt
--Types of input
cat < name of file
'cat << eof input eof'
cat <<< "text"
#General system log
/var/log/syslog
#refresh source file
source .bashrc
################# Tree ##################
-- Show dir and files
tree
--Show complete file structure
tree /f
################# Grep ###############
#Search term in file
cat filename | grep word
#Search word in multiple files
grep -r 'Nombre' ./home
---- Seach parameters
egrep 'pattern1|pattern2' *.py
grep -e pattern1 -e pattern2 *.pl
grep 'pattern*' file1 file2
grep 'warning\|error\|critical' /var/log/messages
--Just match words
grep -w 'warning\|error\|critical' /var/log/messages
-- Same with egrep
egrep -w 'warning|error|critical' /var/log/messages
################## History ##################
#Search in commands history
history | grep command-name
#Search multiple
history | grep -i 'scp|ssh|ftp'
#Find command in history
fc -l ssh
fc -l 443 444
############
#Search patterns of columns in text
Mostrar una determinada columna de información:
# ls -l | awk '{ print $5 }'
Mostrar varias columnas, así como texto adicional (entre comillas):
# ls -l | awk '{ print $8 ":" $5 }'
#Append only stdout to log
commnad 1 >> /path/log
#Append to stdout and stderr to log
command &>> /path/to/log
or
command 1> /path/to/log 2>&1
#Discard stdout and stderr
command > /dev/null 2>&1
#ARP poisoning
#SET dns spf
############# SYSTEMCTL ####################
--Suspend
systemctl suspend
############# VIM ####################
Esc -- normal mode
: -- command mode
Insert -- Edit mode
-- Save / quit
In normal mode:
: then ^q! -- Quit without saving
: then ^wq! -- Save and quit
-- Fast edit
In normal mode:
yy -- Copy line
p -- paste copied line
dd -- delete line
############# SED eliminate / substitute characters
|| replace original file -i
|| add a prefix to original line -i[PREFIX]############
sed '1s/^.//' infile >> outfile -- eliminate BO markers
--Delete ocurrence
sed '/delete_this/d' test.txt
--Substitute
-- First match replace
sed -i 's/TipoError:00/TipoError:000/' *
-- All matches in line replace, all appearences
sed -i 's/TipoError:00/TipoError:000/g' *
--replace a date
sed -i 's/2023-10-11/2023-10-12/g' *
--replace in a range of lines
sed '11,12s/sit/foo/g' test.txt
--spaces
sed -i 's/TipoError:\ 00/TipoError:000/g' *
--recursive
sed -i 's/TipoError:00/TipoError:000/g' $(find /dir to files -type f)
--replace multiple expressions
sed -e 's/<YEAR>/2018/' \
-e 's/<COPYRIGHT HOLDER>/Sylvain Leroux/' \
MIT.LICENSE
sed -e 's/<YEAR>/2018/
s/<COPYRIGHT HOLDER>/Sylvain Leroux/' \
MIT.LICENSE
############# Rename files ############
rename 's/20230919/20230920/' FMUTUOS*
############### ubuntu main repo #####################
91.189.88.161
archive.ubuntu.com
############## show free disk space ######################
df -h
############# Show last exit status ####################
echo $?
############# Send process to background ################
sleep 10 &
############# Show procecesses in background ############
jobs
fg 1 -- # brings job 1 to the foreground
############# Print enviromental variables ################
echo
printenv
or
env
############# Show all variables in system ##################
set
#############
############# Set environmental variable ###################
export FOO=BAR
############# Unset an environment variable #################
unset FOO
############# Show processes ########################
top
############## /etc #############################
/etc/passwd --- User information (user, userid, groupid, gecos, home dir, bash,
etc)
/etc/shadow --- User Ecncrypted password string
/etc/skel --- User config files
########### update apt cache ############
sudo apt update command
################ User Management tools ###############################
useradd -- create user
userdel -- remove user
usermod -- change user atribbutes
groupadd -- create a group
groupdel -- remove group
groupmod -- modify parameters of group
-- Create group
sudo addgroup sftp
-- Create user and add to group
sudo useradd -m sftp_user -g sftp
---- Debian ------
adduser, addgroup, deluser, delgroup
################### Change user to sudoer
usermod -aG sudo username
############### Quickly create file #########################
touch /tmp/files/file.txt
--Modify last date / time modified to now
touch file.txt
Ej. touch
/mnt/e/Users/DAndaluz/Dev/Desarrollos/DES_Teso_Abono_En_Cuenta/insumos/
operaciones/*.xl*
--Modify last date / time / accesed to custom time
-a = accessed
-m = modified
-t = timestamp - use [[CC]YY]MMDDhhmm[.ss] time format
Ej. touch -a -m -t 201512180130.09 fileName.ext
--Verify date / time
stat file
--------------------- Modify file attributes
touch -a -m -t 202203110000.00 *
--Modify last modified date
touch -d "2022-02-10 00:00:00.000000000 -0600" ReporteTTMasivo2462316.xlsx
-- Check file attributes
stat [filename]
-----------------------
################ Change owner ###################
--Change owner of simple file
chown user filename(s)
chown $USER thisfile.text
--Change owner of recursive
chown -R whales /TestUnix
-----------------------
############## Check installed library ####################
apt-cache policy [library or program]
############# Find installed library ######################
ldconfig -p | grep libjpeg
############ chmod ####################
chmod ugo
u - file owner
g - group members
o - all other users
a - all users
---Give execution rights to all
chmod +x filename
---Give execution rights to current user only
chmod u+x filename
---Give execution rights to group only
chmod g+x filename
---Give execution rights to owner only
chmod o+x filename
--Recursively remove the write permission for other users:
chmod -R o-w dirname
################ Turn ON the SetUID bit (Program runs with the owner´ privileges,
not the user´s) ##############
chmod 4755 /bin/ls
or
chmod u+s /bin/ls ~
############## Turn ON Sticky bit (Avoid file deletion by other user)
################
chmod +t /tmp/chapter-5/
################ Change user password ####################
sudo passwd rayklash
############### Copying a disk image ######################
dd if=~/file.img of=/dev/sdb1
############### Backing up de MBR ########################
dd if=/dev/sda of=/tmp/COPY_OF_MBR bs=512 count=1
############### List disk partitions #####################
fdisk -l
or
sudo sfdisk -l -uM
############### List info of mounted devices ###############
df
df sda
############### List BLOCK devices ######################
lsblk
############### Search UUID of devices ######################
sudo udevadm info /dev/sda2 | grep UUID
############## Main mounting points ###################
/mnt
/media
############## Mounting a device ###################
mount /dev/sdb1 /mnt
############## Unmounting a device ######################
umount /dev/sdb1
############## Check and repair filesystem for errors ##############
umount /dev/sdb1
fsck -p /dev/sdb1
################ Show disk sizes ####################
fdisk -l
################ Show disk space ####################
df -h
################ Show disk usage ####################
du -h
############### Show memory ammount ###################
free
############## Show proccess ####################
pd aux
or
top
############# Prioritize process ####################
--Init with some priority
nice -n 10 /etc/xorg.sh
--Reprioritize
renice 20 PID
############### Proxy config ########################
Create file /etc/apt/apt.conf with this lines
Acquire::http::Proxy "PROXY_URL:PROXY_PORT";
Acquire::http::Proxy "http://10.50.8.20:8080";
Acquire::http::Proxy "http://10.57.167.4:8080";
############### Mount to directory #####################
mount -o ro /dev/sda3 /bogus-directory
where:
-o -- mounting options
ro -- read only
############## Unmount #######################
unmount /bogus-directory
############## Partitions to mount during boot ############
/etc/fstab
############## Zip ###################
zip [options] zipfile files_list
#Zip folder
zip -r temp.zip Documents
#Zip with password
# with prompt in shell
zip -e file.zip file_to_zip.txt
# explicit password
zip -p password file.zip file_to_zip.txt
#Unzip
unzip file
#Unzip to dir
unzip ~/Downloads/sonar-scanner-cli-4.6.0.2311-linux.zip -d /opt/sonar-scanner/
############## Tar tgz ########################
############## Extract tar file #######################
tar -xzvf file.tar
where:
-x extract
-z gzip asocciated (tar.gz)
-v be verbose
-f which specific file
############# Extract a single file ###############
tar -zxvf backups.tgz etc/rsyslog.conf etc/xattr.conf
############# Extract tar to directory #################
tar -xvf articles.tar -C /tmp/my_article/
############## Create tar file #################
tar -cvf temp.tar docs1.txt docs2.txt files.zip
############## Look into tar file #################
tar -tvf temp.tar
############## Compression utilities
gzip / gunzip ---- tgz files
bzip2 / bunzip2
compress / uncompress
########### BZ2 compression #################
-- compress
bzip2 filename
-- Decompress
bzip2 -d filename.bz2
-- force , be verbose and keep input file
bzip2 -vfd Etcher-linux-x64.AppImage.bz2
############### Change the prompt ########################
PS1="New prompt value"
############## Edit path environment variable ######################
PATH=$PATH:/root/newProgram
echo
#################### Kernel directory #########################
/boot/vmlinuz
---------------------------------------
---------------------------------------
#################### Logging configuration #######################
rsyslog.conf
#################### Logging rotation configuration #####################
logrotate.conf
#################### Disable logging service #####################
service rsyslog stop
#################### Services ####################
-- Show system manager
pstree | head -n 5
-- List services with systemctl
systemctl list-units --type=service
-- List services with systemctl
systemctl list-units --type=service -all
#################### Starting, Stoping , Reseting services #####################
service apache2 start
service apache2 stop
service apache2 restart
#################### Shred (trash) a file ########################
shred -f -n 10 /var/log/auth.log
where
f - gives permission to shred if neccesary
n - number of time to overwrite the file
###################### LOG ############################
--Debian log
/var/log/syslog
##################### Show some wifi connection details ######################
iwconfig
##################### Show available wifi networks ######################
iwconfig wlan0 scan
##################### Show wifi connection detailed info ######################
nmcli dev wifi
##################### Start wifi card in monitor mode ########################
airmon-ng start wlan0
##################### Monitor wifi APs #########################
airodump-ng wlan0mon
##################### Capture packets traversing an AP #####################
airodump-ng -c 10 --bssid 00:00:AA:BB:00:10 -w NameOfLan wlan0mon
################ Deauthenticate some user from wifi and capture hash
##############
aireplay-ng -deauth 100 -a 00:00:00:22 -c A0:00:B0:A3 wlan0mon
##################### Obtain password by wordlist ########################
aircrack-ng -w wordlist.dic -b 01:43:AA:BB:CC:22 NameOfLan.cap
##################### Show bluetooth interface info ###########################
hciconfig
##################### Enable bt interface ###########################
hciconfig hci0 up
##################### Scan for bluetooth devices ###########################
hcitool scan
########### Scan for bluetooth devices with MAC detail ##############
hcitool inq
############ Scan services ################
sdptool browse MACAddress
############ Ping for active device ###############
l2ping MACaddress
############ Check kernel version ###############
uname -a
cat /proc/version
############ Check kernel parameters ###########
sysctl -a | less
############ Change kernel parameter ipv4 forwarding ############
sysctl -w net.ipv4.ip_forward=1
Modify /etc/sycstl.conf to make change permanent
############ List kernel modules ################
lsmod
############ Show info for kernel modules ############
modinfo bluetooth
############ Add kernel module ###############
modprobe -a <module to add>
############ Remove kernel module ################
modprobe -r <module to remove>
############ Print messages from kernel #############
dmesg | grep <search>
############ Location of crontab ################
/etc/crontab
minute hour dayOfMonth month dayOfWeek user command
30 2 * * 1-5 root /home/pi/xplore.sh #Run
xplore.sh from M-F at 2:30
############ Shortcuts for crontab #################
@yearly
@annualy
@monthly
@weekly
@daily
@midnight
@noon
@reboot
############ Rc scripts (Ran at init)###############
/etc/init.d/rc
############ Add / Remove scripts or services to rc to run at init ###############
update-rc.d <script or service> <remove | defaults | disable | enable>
############ Add / Remove scripts or services via GUI ###############
rcconf
############# Python #############
############# Python Package Index ###############
http://www.pypi.org
############ Install py modules from pip3 ######################
pip3 install <package name>
############ Installing py module from third party #################
wget <http://some site >
tar -xzf module.tar
python setup.py install
##################### SSH BASH COMMANDS ######################33
################# SCP copy file #####################
#From local to remote
scp myfile.txt remoteuser@remoteip:/remote/folder/
#Copy to remote
scp -P 2222 /PATH/TO/LOCAL/FILE IP:/PATH/TO/REMOTE/DESTINATION
#Copy from remote
scp -P 2222 IP:/PATH/TO/REMOTE/FILE /PATH/TO/LOCAL/DESTINATION
###################### GLOSARY ############################
###########################################################
UNIX epoch: January 1, 1970 -- the starting point or origin for
keeping time on UNIX systems.
date +%s
---------------------
PAM -- Pluggable Authentication Modules , Library of functions that an application
can use to request that a user be authenticated.
When invoked, PAM
checks the configuration file for that application. If it finds no
application-specific configuration file, it falls back to a default configuration
file. This
configuration file tells the library what types of checks need to be done to
authenticate
the user. Based on this, the appropriate module is called upon.
Parts of PAM config file line
module_type | control_flag | module_path | arguments
---------------------
Boot Loader. First software to handle control to Linux OS. It resides in the MBR.
Ex. GRUB.\
################# MARIADB ############################
-- Solucion para error : can not login as root@localhost
sudo systemctl start mariadb
cp -rp ./var/run/mysqld.sock ./var/run/mysqld.back
sudo systemctl stop mariadb
cp -rp ./var/run/mysqld.back ./var/run/mysqld.sock
sudo mysqld_safe --skip-grant-tables --skip-networking &
sudo mysql -u root
use mysql
update password = PASSWORD('newpass') where user = 'root';
exit
################ Restore GRUB #######################
From live iso :
#mount current linux installation
sudo mount /dev/sdaX /mnt
sudo mount –bind /dev /mnt/dev
sudo mount –bind /dev/pts /mnt/dev/pts
sudo mount –bind /proc /mnt/proc
sudo mount –bind /sys /mnt/sys
sudo chroot /mnt
#reintall grub
grub-install /dev/sda
update-grub
exit
#unmount
udo umount /mnt/sys
sudo umount /mnt/proc
sudo umount /mnt/dev/pts
sudo umount /mnt/dev
sudo umount /mnt
reboot
########### ERROR FIXES ###############
Howto fix “dpkg was interrupted, you must manually run sudo dpkg –configure -a to
correct the problem” error
--
sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/updates/*
sudo apt-get update
--
Fix vmmem taking too much ram
-- 1. Edit .wslconfig
Paste
[wsl2]
memory=2GB
2. Restart docker
########### CREATE DESKTOP SHORTCUT ###############
sudo desktop-file-install /opt/FileZilla3/filezilla.desktop
.desktop file example
[Desktop Entry]
Name=Filezilla
Type=Application
Exec=/opt/Filezilla3/filezilla
Terminal=false
Icon=/opt/FileZilla3/share/icons/hicolor/32x32/apps/filezilla.png
Comment=FTP client
NoDisplay=false
Categories=Tools;Files
Name[en]=Filezilla
Name[en_US]=Filezilla
**************
Configure system variables
--Create sh file with
#/bin/bash
export PATH="$PATH:/opt/sonar-scanner/bin"
-- Run scripts at OS boot
make the sh file to execute at init
/etc/profile.d/sonar-scanner.sh
reboot
env – The command allows you to run another program in a custom environment without
modifying the current one. When used without an argument it will print a list of
the current environment variables.
printenv – The command prints all or the specified environment variables.
set – The command sets or unsets shell variables. When used without an argument it
will print a list of all variables including environment and shell variables, and
shell functions.
unset – The command deletes shell and environment variables.
export – The command sets environment variables.
******** SSH ***************
-- Copying
Syntax:
scp <source> <destination>
--To copy a file from B to A while logged into B:
scp /path/to/file username@a:/path/to/destination
--To copy a file from B to A while logged into A:
scp username@b:/path/to/file /path/to/destination
scp /home/dandaluz/Docker/images/teso_abono\:front_data_server.tar devfindur@
---- SSH key generation ----------
ssh-keygen -b 2048 -t rsa
-- Import key to server
ssh-copy-id -i ~/.ssh/tatu-key-ecdsa user@host
-- Convert ssh key to another format
ssh-keygen -p -f ~/.ssh/id_rsa -m pem
ssh-keygen -f private.pem -y > private.pub
-- Output public key from private key file
ssh-keygen -y -f <private key file>
-- Set new host for ssh utils to read
ssh-keyscan -t rsa <HOST_NAME> >> ~/.ssh/known_hosts
------- SSH AUTH ----------
sshuser3
sshuser
--------------- GPG -----------------
gpg --full-generate-key
You must keep the private key to yourself and never share with anyone.
The public key you can give to people, so that they can encrypt messages/files with
your public key.
You will be the only one to decrypt those messages using your private key.
Private key is stored on the disc encrypted with a passphrase.
If you lose either your private key or the passphrase, you will not be able to
decrypt the messages.
Therefore, backup your private key securely, also write down the passphrase in a
safe place.
-- List public keys in your keyring:
gpg --list-keys
-- List private keys:
gpg --list-secret-keys
--Export your public key:
gpg --export --armor [email protected] > mypubkey.asc
-- Export your private key:
gpg --export-secret-key --armor [email protected] > mypubkey.asc
-- Import others public keys:
gpg --import pubkey.asc
-- Delete key
gpg --delete-key [uid]
-- Delete private key
gpg --delete-secret-key [uid]
-- You can use the same command to import your own private keys as well like if you
need to move your key to another machine or you have obtained from another place.
gpg --import privatekey.asc
-- ENCRYPT a file:
gpg --encrypt --recipient Pranab filename.txt
gpg --encrypt --recipient 'Pranab' filename.txt
gpg --encrypt --recipient '
[email protected]' --recipient 'Sam' filename.txt
-- It will generate encrypted file named filename.txt.gpg. If you want armor text,
use that flag:
gpg --encrypt --armor --recipient '[email protected]' filename.txt
-- It generates encrypted , SIGNED file named filename.txt.asc. Specify the output
file:
gpg --output filename.pgp --encrypt --sign --armor --recipient '[email protected]'
filename.txt
-- DECRYPT a file:
gpg --decrypt filename.txt.gpg
gpg filename.txt.gpg
--Decrypt with output
gpg --decrypt filename.txt.gpg > filename-copy.txt
-- If you do not provide an output file name, it will print decrypted text in the
terminal. If it is a binary file, you should provide an output file, possibly with
correct file extension.
--Decrypt trying all keys in keyring
gpg -d --try-all-secrets ResultadoPruebaEncripcion.pgp > salidaResultado
Edit a key:
gpg --edit-key 'Pranab Das'
trust
quit
-- Set the time a cache entry is valid to n seconds. The default is 600 seconds.
gpg --default-cache-ttl n
-- You can download anyones protonmail public key by visiting the URL:
#https://api.protonmail.ch/pks/lookup?op=get&search={username}@protonmail.com
#
#You can use PGP to perform symmetric encryption as well. Encrypt a file using
passphrase:
#
#gpg -c file.txt
## with more options
#gpg --symmetric \
# --armor \
# --cipher-algo AES256 \
# --output file.enc \
# file.txt
#
#By default gpg uses some compression leading to output size less than that of
input for non armor outputs. You can change the compression algorithm and
compression level by --compress-algo and -z options, respectively. See the manual
for more details.
#
#Decryption:
#
#gpg -d file.txt.gpg > file-copy.txt
---------------- ifconfig ----------------------
-- Search MAC address
ifconfig | egrep 'wlp0|ether'
----------------- Date ---------------------------
The following are the date format options.
$date +%[format-option]
%D: Display date as mm/dd/yy.
%d: Display the day of the month (01 to 31).
%a: Displays the abbreviated name for weekdays (Sun to Sat).
%A: Displays full weekdays (Sunday to Saturday).
%h: Displays abbreviated month name (Jan to Dec).
%b: Displays abbreviated month name (Jan to Dec).
%B: Displays full month name(January to December).
%m: Displays the month of year (01 to 12).
%y: Displays last two digits of the year(00 to 99).
%Y: Display four-digit year.
%T: Display the time in 24 hour format as HH:MM:SS.
%H: Display the hour.
%M: Display the minute.
%S: Display the seconds.
Ex.
date +%D
date +”Year: %Y, Month: %m, Day: %d”
Year: 2022, Month: 04, Day: 16
Command: $date “+%D”
Output: 10/11/30
Command: $date “+%D %T”
Output: 10/11/30 16:13:27
Command: $date “+%Y-%m-%d”
Output: 2030-10-11
Command: $date “+%Y/%m/%d”
Output: 2030/10/11
Epoch : Unix time since January 1, 1970 UTC
------------------ find ---------------------
$ find [where to start searching from]
[expression determines what to find] [-options] [what to find]
Options :
-exec CMD: The file being searched which meets the above criteria and returns 0
for as its exit status for successful command execution.
-ok CMD : It works same as -exec except the user is prompted first.
-inum N : Search for files with inode number ‘N’.
-links N : Search for files with ‘N’ links.
-name demo : Search for files that are specified by ‘demo’.
-newer file : Search for files that were modified/created after ‘file’.
-perm octal : Search for the file if permission is ‘octal’.
-print : Display the path name of the files found by using the rest of the
criteria.
-empty : Search for empty files and directories.
-size +N/-N : Search for files of ‘N’ blocks; ‘N’ followed by ‘c’can be used to
measure size in characters; ‘+N’ means size > ‘N’ blocks and ‘-N’ means size < ‘N’
blocks.
-user name : Search for files owned by user name or ID ‘name’.
\(expr \) : True if ‘expr’ is true; used for grouping criteria combined with OR
or AND.
! expr : True if ‘expr’ is false.
Ex. 1. Search a file with specific name.
$ find ./GFG -name sample.txt
2. Search a file with pattern.
$ find ./GFG -name *.txt
3. How to find and delete a file with confirmation.
$ find ./GFG -name sample.txt -exec rm -i {} \;
4. Search for empty files and directories.
$ find ./GFG -empty
6. Search text within multiple files.
$ find ./ -type f -name "*.txt" -exec grep 'Geek' {} \;
-----
find / -name '*.py'
Find files with the word "python" in the name.
find / -name '*python*'
Same as above but case-insensitive.
find / -iname '*python*'
Regex match, more flexible. Find both .py files and files with the word "python" in
the name.
find / -regex '.*python.*\|.*\.py'
------------- install .deb files ---------------
sudo apt install path_to_deb_file
sudo dpkg -i path_to_deb_file
----------- Keys -------------
--Create a password-protected, 2048-bit RSA private key
openssl genrsa -des3 -out domain.key 2048
--View private key content
openssl rsa -text -in yourdomain.key -noout
--Extract public key from private key to
openssl rsa -in yourdomain.key -pubout -out yourdomain_public.key
-------
--Extract private key from pfx file
openssl pkcs12 -in file.pfx -nocerts -out privatekey.pem -nodes
-- --Extract certificate from pfx file
openssl pkcs12 -in file.pfx -clcerts -nokeys -out certificate.crt
------------ keytool ---------------
--Generate keystore
keytool -genkeypair -alias samloktaservice -keypass samlauthokta -keystore saml-
keystore.jks
--Generate keystore specifying the algorithm infile
keytool -genkeypair -alias samloktaservice -keypass samlauthokta -keystore saml-
keystore.jks -keyalg RSA -sigalg SHA256withRSA -validity 10000
--Generate PCKS12 keys
keytool -genkeypair -alias baeldung -keyalg RSA -keysize 2048 -storetype PKCS12 -
keystore baeldung.p12 -validity 3650
Ex.
keytool -genkeypair -alias h2h_internal -keyalg RSA -keysize 2048 -storetype PKCS12
-keystore /home/dandaluz/Dev_INFO/Desarrollos_iNFO/H2H/Certificados/H2H_internal/
h2h_config_record.p12 -validity 7305
--Generate Java keystore
keytool -genkeypair -alias baeldung -keyalg RSA -keysize 2048 -keystore
baeldung.jks -validity 3650
--
-- Use private key to generate a p12 keystore then convert it to jks keystore:
<<<<<<<<<<<
openssl pkcs12 -export -in user.pem -inkey user.key -certfile user.pem -out
testkeystore.p12
keytool -importkeystore -srckeystore testkeystore.p12 -srcstoretype pkcs12 -
destkeystore wso2carbon.jks -deststoretype JKS
---- Importacion de certificados:
keytool -import -file <archivo de certificado> -alias <alias> -keystore <archivo
keystore>
Ej:
sudo keytool -import -file
/home/dandaluz/Dev_INFO/Desarrollos_iNFO/H2H/Certificados/CyberArk/Nuevo_2023_2/
portal/_socio.gs.der -alias socio.gs_portal_2_2023 -keystore /usr/lib/jvm/java-11-
openjdk-amd64/lib/security/cacerts
keytool -import -file e:\Users\DAndaluz\Dev_info\certs\sociogs_cert.cer -alias
sociogs -keystore "C:\Program Files\Java\jdk-17.0.6\lib\security\cacerts"
keytool -import -file e:\Users\DAndaluz\Dev_info\certs\elektra_cert.cer -alias
elektra -keystore "C:\Program Files\Java\jdk-17.0.6\lib\security\cacerts"
--PKCS12
keytool -importkeystore -srckeystore
/home/dandaluz/Keys/h2h/H2H_internal/h2h_config_record.p12 -srcstoretype PKCS12 -
destkeystore /usr/lib/jvm/jdk-11.0.17/lib/security/cacerts
OR <<< best
1. keytool -exportcert -keystore /home/sogadm/MB_copy/MB_client.p12 -storepass
123456 -storetype PKCS12 -alias p12_entry_alias -file
/home/sogadm/MB_copy/MB_client.cer
ex. keytool -exportcert -keystore
/home/dandaluz/Keys/h2h/H2H_internal/h2h_config_record.p12 -storepass
Cd8T34$mdi90_2396ui -storetype PKCS12 -alias h2h_internal -file
/home/dandaluz/Keys/h2h/H2H_internal/h2h_internal.cer
then
2. keytool -importcert -keystore /usr/java/default/jre/lib/security/cacerts -
storepass changeit -alias mb_client -file /home/sogadm/MB_copy/MB_client.cer
ex. keytool -importcert -keystore
/usr/lib/jvm/jdk-11.0.17/lib/security/cacerts -alias h2h_internal -file
/home/dandaluz/Keys/h2h/H2H_internal/h2h_internal.cer
---- Lista certificados
keytool -list -v -keystore "C:\Program Files\Java\jdk-17.0.6\lib\security\cacerts"
keytool -delete -alias digic1 -keystore "C:\Program Files\Java\jdk-17.0.6\lib\
security\cacerts"
SSLPOKE:
java -Djavax.net.debug=ssl SSLPoke
"https://aim.socio.gs/AIMWebService/api/Accounts?
AppID=APP_SISTINV&SAFE=BA_SIST_INV_KEY&Folder=Root&Object=10.54.90.118-
H2HEncryptor" 443
java -Djavax.net.debug=ssl SSLPoke "https://google.com" 443
------------ Build ----------------
1. download source
2. cd to dir
3. sudo make
----------- wrk --------------
--Load 12 threads (-t), keep 400 HTTP connections (-c) open, test time 30 seconds
(-d)
wrk -t12 -c400 -d30s http: //127.0.0.1:8080/index.html
-c, - connections: total number of HTTP connections to keep open with each thread
handling N = connections/threads
-d, - duration (test duration): duration of the test, eg 2s, 2m, 2h
-t, - threads: total number of threads to use
-s, - script: LuaJIT script, see SCRIPTING
-H, --header: HTTP header to add to request, eg "User-Agent: wrk"
- latency (response information): print detailed latency statistics
--timeout: record a timeout if a response is not received within this amount
of time .
------------- sdkman ---------------------
Instalation:
1. curl -s "https://get.sdkman.io" | bash
2. source "$HOME/.sdkman/bin/sdkman-init.sh"
3. sdk version
sdk list -- list available software
sdk install [sdk] -- install un sdk
sdk list [sdk] -- list available versions of sdk
sdk default [sdk] [version] -- set default version of sdk
sdk use [sdk] [version] -- change to specific version of sdk
sdk current [sdk] -- show current version
sdk current -- show all current versions in use
sdk uninstall [sdk] [version] -- uninstall
sdk flush archives -- clean cache
sdk flush temp -- clean temp folder
rm -rf ~/.sdkman -- remove sdkman
------------- curl -----------------------
-- Allow non secure connections
curl -k
curl http://localhost:8080/people/1
-- Call POST
curl -i -H "Content-Type:application/json" -d '{"firstName": "Frodo", "lastName":
"Baggins"}' http://localhost:8080/people
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/people/1
Content-Length: 0
Date: Wed, 26 Feb 2014 20:26:55 GMT
-i: Ensures you can see the response message including the headers. The URI of
the newly created Person is shown.
-H "Content-Type:application/json": Sets the content type so the application
knows the payload contains a JSON object.
-d '{"firstName": "Frodo", "lastName": "Baggins"}': Is the data being sent.
If you are on Windows, the command above will work on WSL. If you can’t install
WSL, you might need to replace the single quotes with double quotes and escape the
existing double quotes, i.e. -d
"{\"firstName\": \"Frodo\", \"lastName\": \"Baggins\"}".
-- Call PUT
curl -X PUT -H "Content-Type:application/json" -d '{"firstName": "Bilbo",
"lastName": "Baggins"}' http://localhost:8080/people/1
----------- Tools ----------------
---- Terminator --------
inti specifying a custom layout :
terminator --maximise --layout='four windows'
Key commands in Terminator
Toggle fullscreen: F11
Split terminals horizontally: Ctrl + Shift + O
Split terminals vertically: Ctrl + Shift + E
Close current Panel: Ctrl + Shift + W
Open new tab: Ctrl + Shift + T
Move to the terminal above the current one: Alt + ↑
Move to the terminal below the current one: Alt + ↓
Move to the terminal left of the current one: Alt + ←
Move to the terminal right of the current one: Alt +
------------- Netstat ---------------
sudo netstat -tulpn | grep LISTEN
--Search by port
netstat -ltnp | grep -w ':8087'
ss -ltnp | grep -w ':8086'
--------------- netcat / nc ------------
General purpose network tool
--Scan an ip
nc -zv ip port
-z scan without connecting
-v be vesbose
--Scan an port range
nc -zv ip port-port
----------- LSOF ------------------
-- Show by all listening
sudo lsof -i -P -n | grep LISTEN
------------ Trace url ---------------
--- linux
tracepath <ip>
traceroute <ip>
--- windows
tracert ip
-------- JOURNAL -----------
-- Show journal size
sudo journalctl --disk-usage
-- Delete journal files older than n days
sudo journalctl --vacuum-time=4d
---- GNOME ISSUES ---------
------ Reset Gnome ------
killall -3 gnome-shell
----- Gnome not working
--Reintall gmd3
sudo apt purge gdm3
sudo systemcrtl reboot
sudo apt install -y gdm3
--------- SAMBA ----------------
-- Access share
smbclient -U [domain/user] -L [host]
Ex.
smbclient -U horussv/UsrFindurAAZ //10.54.53.238/openlink --directory .
-- Send file
smbclient -U [domain/user] -L [host] --directory [path] -c 'put "file"'
Ex. smbclient -U horussv/UsrFindurAAZ -L 10.54.53.238/Openlink --directory
Tesoreria/log/H2HEncryptor -c 'put "/home/dandaluz/temp/prueba1.txt"'
-------- Search processes -------------
-- Show processes
ps -e | less
-- Search for specific process ID
ps -e | grep shutter
-- Search process by substring in name
pgrep subq
then kill it
pkill subq
-- Search process by user and part of process name
ps -u dave | grep subq
--------- Kill procceses ---------------
-- Kill a process
kill 2099
----------------------------------
Unresponsive / Emergency cheat sheet
This is my "linux emergency cheat sheet":
1. Non responsive application
SUPER --> type in System Monitor --> RETURN --> find process --> right click -->
Kill Process
or
ALT + F2 --> type in xkill --> x marks the spot (or in this case frozen app)
or
CTRL + ALT + T --> type in top --> find process ID --> k PID where PID = process ID
Effect: This kills the program.
---------------------
2. Non responsive desktop
CTRL + ALT + F1 --> type in sudo service lightdm restart
Effect: This kills the session and starts a new one.
3. Non responsive system
3.1
Hold ALT + SysRq + K , (Kills most RAM demanding procceses)
LAST RESORT. ONLY USE WHEN EVERYTHING ELSE FAILS:
Hold ALT + SysRq down and hit the following keys in the given order:
R --> E --> I --> S --> U -->B
This is where you find the magic SysRq key:
----------- Remove / uninstall packages ----------------
sudo apt-get remove --purge |program name|
----------- Search installed packages ----------------
apt list --installed
---------- Snap installer ----------------
#Install package
sudo snap install intellij-idea-community --classic
#Remove package
sudo snap remove intellij-idea-community
#Get package version info
snap info intellij-idea-community
#Install specific version
sudo snap install intellij-idea-community --classic --channel=2023.1/stable
----------- Json querier -----------
-- Get a property from file
jq .fruit.name fruit.json
--Get multiple properties head
jq '.fruit.color,.fruit.price' fruit.json
-- Get property from array
jq '.[] | .name' manyfruits.json
-- Get property by index in array
jq '.[1].price' fruits.json
--Slice an array
echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[6:9]'
---------- Creating desktop shurtcuts ------------
1. Open /usr/share/applications
2. Create app.desktop file with body like :
[Desktop Entry]
Name=Eclipse
Type=Application
Exec=/home/dandaluz/Tools/eclipse/eclipse
Terminal=false
Icon=/opt/eclipse/icon.xpm
Comment=Integrated Development Environment
NoDisplay=false
Categories=Development;IDE;
Name[en]=Eclipse
Name[en_US]=Eclipse
X-Desktop-File-Install-Version=0.24
2. Copy the application shortcut to desktop
3. Right click on the shortcut on the desktop and select Allow Launching
--------- Check ports -----------
-- Scan port zero i/o and be verbose
nc -zv localhost 29092