Linux Collection

$> sudo su

$> sync ; echo 1 > /proc/sys/vm/drop_caches
$> sync ; echo 2 > /proc/sys/vm/drop_caches
$> sync ; echo 3 > /proc/sys/vm/drop_caches
#install tools qemu-kvm (debian based distros)
$ sudo apt-get install qemu-kvm

#load module
$ sudo modprobe nbd

#create loopback dev for the image
$ sudo qemu-nbd -c /dev/nbd0 <path to virtual disk>.vdi

#mount the partitions, that are exposed as /dev/nbd0pXXX
$ sudo mount  -o noatime,noexec /dev/nbd0p1 /tmp/vdi/

#in the end unmount && shutdown the ndb
$ sudo umount /tmp/vdi/
$ sudo qemu-nbd -d /dev/nbd0
#install debian based:

sudo apt-get install nbtscan

#windows and others: download at http://www.unixwiz.net/tools/nbtscan.html

nbtscan 192.168.0.1-254 //IP Range
nbtscan 192.168.0.0/24  //whole C-class network
nbtscan 192.168.1.0/24  //whole C-class network
nbtscan 172.16.0.0/16   //Whole B-class network
nbtscan 10.0.0.0/8      //whole A-class network
wkhtmltopdf <url1> <url2> ... <urln> <output-pdf-path-filename>
/* SQL Command within postgres: */

SELECT now() - pg_postmaster_start_time() uptime

/* using psql command line utility deployed with Postgres: */
 
$> psql -c "SELECT now() - pg_postmaster_start_time() uptime"
#Setup the rate control and delay
sudo tc qdisc add dev lo root handle 1: htb default 12 
sudo tc class add dev lo parent 1:1 classid 1:12 htb rate 33kbps ceil 56kbps 
sudo tc qdisc add dev lo parent 1:12 netem delay 400ms
 
#Remove the rate control/delay
sudo tc qdisc del dev lo root
 
#To see what is configured on an interface, do this
sudo tc -s qdisc ls dev lo
 
#Replace lo with eth0/wlan0 to limit speed at lan
sudo route ip route add <ip range> gw <gateway ip address> dev <interface>
sudo ip addr flush dev <interface>
sudo /etc/init.d/networking restart

#Ex:

route ip route add 192.168.32.0/24 gw 192.168.32.1 dev eth0
sudo ip addr flush dev eth0
sudo /etc/init.d/networking restart
$> ssh <remote user>@<remote server ip> [-p <remote ssh port>] -L <remote server port>:<internal target ip>:<internal target port> -fN

#Ex:
#Redirect web traffic throughout myremoteserver.com, port 9999, to local machine 192.168.0.1, port 80.

$> ssh operator@myremoteserver.com -L 9999:192.168.0.1:80 -fN

#So you can access: "http://localhost:9999/"
#This url will respond as it was "http://192.168.0.1:80/"
$> find ./ -name "<filename/wild cards>" | xargs grep -i "<text to find>"

#Ex:

$> find ./ -name "*.txt" | xargs grep -i "Examples"

#Find all text files (*.txt) containing text 'Examples' from current path (./) and inner.
#Merge file1.pdf and file2.pdf into merged.pdf:

$> gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=merged.pdf file1.pdf file2.pdf
$> sudo crontab -e

#then add a line like this:

* * * * * find /path/to/files/ -type f -mtime +<n> -exec rm -rf {} \;

#Ex:
#Delete "*.txt" files older than 1 day from /tmp folder every day at 2:00am:

0 2 * * * find /tmp/* -type f -mtime +1 -exec rm {} \;       #files
0 2 * * * find /tmp/* -type d -mtime +1 -exec rm -rf {} \;   #folders
$> wget -qO- ipecho.net/plain
$> dig +short myip.opendns.com @resolver1.opendns.com
$> wget -qO- shtuff.it/myip/short
$> wget -qO- whatismyip.akamai.com
$> sudo apt-get install freetds-bin

#At Lazarus:
#Put TZConnection component (ZConnection1) and set LibraryLocation as shown:

#  ZConnect1.LibraryLocation:=libsybdb.so.5;

#  and we're done!
$ comm -13 \
  <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort) \
  <(comm -23 \
    <(dpkg-query -W -f='${Package}\n' | sed 1d | sort) \
    <(apt-mark showauto | sort) \
  )
#disable ping to your station:

sudo echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all 

#enable ping back:

sudo echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all
$ sudo apt install dcmtk

#Service:

$ storescp -v +xa -pm +uf -fe .dcm -sp --fork -aet MARCO -od ./test_storescp 4006

#Store:

$ storescu -xs localhost 4006 dicom_file.dcm
#!/bin/sh

#----------------------------------------------------------------
# Put this file at /usr/local/bin:
#
#     $> sudo cp verify_nr /usr/local/bin
#
# Set executing permissions:
#
#     $> sudo chmod +x /usr/local/bin/verify_nr
#
# Then create crontab (cada minuto):
#
#     $> sudo crontab -e
#     #(Go to end and append:)
#     * * * * * /usr/local/bin/verify_nr
#     #(Save)
#----------------------------------------------------------------
SERVICE="nrservice"
if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null
then
    echo "$SERVICE service running, everything is fine" > /dev/null
else
    sudo service nrservice.sh restart
fi
#!/bin/bash
#
#/etc/init.d/oracledb
#
#Run-level Startup script for the Oracle Listener and Instances
#It relies on the information on /etc/oratab

export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=/u01/app/oracle/product/11.2.0/dbname_1
export ORACLE_OWNR=oracle
export PATH=$PATH:$ORACLE_HOME/bin

if [ ! -f $ORACLE_HOME/bin/dbstart -o ! -d $ORACLE_HOME ]
then
  echo "Oracle startup: cannot start"
  exit 1
fi

case "$1" in
  start)
    #Oracle listener and instance startup
    echo -n "Starting Oracle: "
    su $ORACLE_OWNR -c "$ORACLE_HOME/bin/lsnrctl start"
    su $ORACLE_OWNR -c "$ORACLE_HOME/bin/dbstart $ORACLE_HOME"
    touch /var/lock/oracle
    echo "OK"
    ;;
  stop)
    #Oracle listener and instance shutdown
    echo -n "Shutdown Oracle: "
    su $ORACLE_OWNR -c "$ORACLE_HOME/bin/lsnrctl stop"
    su $ORACLE_OWNR -c "$ORACLE_HOME/bin/dbshut $ORACLE_HOME"
    rm -f /var/lock/oracle
    echo "OK"
    ;;
  reload|restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: `basename $0` start|stop|restart|reload"
    exit 1
esac

exit 0
##################################################
#Use udisks utility
#sudo apt-get install udisks

$> udisks --show-info /dev/sr0 | grep -c "blank: *1"

#this will return 0:if not blank/present; or 1:blank disk present
*> sudo visudo

#find 'root ALL(...' and append this line below:

www-data ALL=NOPASSWD:/usr/local/bin/myscript.sh

#Save

*> sudo cp myscript.sh /usr/local/bin/
*> sudo chmod 777 /usr/local/bin/myscript.sh

#at php script:

<?php

$cmd = shell_exec("/usr/local/bin/myscript.sh params");
echo $cmd;

?>
#Using dcm4che:

#capture:
$ ffmpeg -an -f video4linux2 -s 640x480  -r 30 -i /dev/video0 -vcodec mpeg4 -vtag DIVX my_test.avi

# convert:
$ jpg2dcm -c mpg2dcm.cfg -ts 1.2.840.10008.1.2.4.100 <mpegfile> <dcmfile>

//---------------------------------------------------------------------

#Send to pacs: dcmtk:
$ dcmsend -d -aec AETITLE <ip address> <dicom port> <dcmfile>

//---------------------------------------------------------------------

#Video props:

$ mplayer video.wmv -identify -vo null -ao null -frames 0 2>&1 /dev/null | egrep "(^ID|VIDEO|AUDIO)"

//---------------------------------------------------------------------

# Use/compare mpg2dcm.config: (at DCM4CHE/BIN/JPG2DCM)

//---------------------------------------------------------------------

# jpg2dcm Sample Configuration for encapsulating MPEG2 MP@ML streams into
# DICOM Video Photographic Image objects
# (s. DICOM Part 3, A.32.7 Video Photographic Image IOD)
# Usage: jpg2dcm -c mpg2dcm.cfg -ts 1.2.840.10008.1.2.4.100 <mpegfile> <dcmfile>

# Patient Module Attributes
# Patient's Name
00100010:
# Patient ID
00100020:
# Issuer of Patient ID
#00100021:
# Patient's Birth Date
00100030:
# Patient's Sex
00100040:

# General Study Module Attributes
# Study Instance UID
#0020000D:
# Study Date
00080020:
# Study Time
00080030:
# Referring Physician's Name
00080090:
# Study ID
00200010:
# Accession Number
00080050:
# Study Description
#00081030:

# General Series Module Attributes
# Modality
00080060:XC
# Series Instance UID
#0020,000E:
# Series Number
00200011:1

# General Equipment Module Attributes
# Manufacturer
00080070:

# General Image Module Attributes
# Instance Number
00200013:1

# Cine Module Attributes
# Frame Time [525-line NTSC]
#00181063:33.33
# Frame Time [625-line PAL]
00181063:40.0
# Multiplexed Audio Channels Description Code Sequence
003A0300

# Multi-frame Module Attributes
#Number of Frames (use dummy value, if unknown)
00280008:1500
# Frame Increment Pointer
00280009:00181063

# Image Pixel Module Attributes (MUST be specified for encapsulating MPEG2 streams)
# (s. DICOM Part 5, 8.2.5 MPEG2 MP@ML IMAGE COMPRESSION for details)
# Samples per Pixel
00280002:3
# Photometric Interpretation
00280004:YBR_PARTIAL_420
# Planar Configuration
00280006:0
# Rows
00280010:480
# Columns
00280011:640
# Bits Allocated
00280100:8
# Bits Stored
00280101:8
# High Bit
00280102:7
# Pixel Representation
00280103:0

# Acquisition Context Module Attributes
# Acquisition Context Sequence
00400555

# VL Image Module Attributes
# Image Type
00080008:ORIGINAL\\PRIMARY
# Lossy Image Compression
00282110:01

# SOP Common Module Attributes
# SOP Class UID
00080016:1.2.840.10008.5.1.4.1.1.77.1.4.1
# SOP Instance UID
#00080018

#----------------------------------------------------------------------------
#convert video to frames:

$ ffmpeg -i test.mp4 -r 24 -f image2 test_files/%05d.png

#----------------------------------------------------------------------------
$ find <folderpath> -name <filemask> -exec <command> <extra parameters> {} \;
$ sudo apt-get install tcpflow
$ sudo tcpflow -p -c -i <netinterface> port <portnum>

# Example: tcpflow -p -c -i eth0 port 80
$ rsync -avz -e "ssh -p <ssh port number>" <user>@<remote addr>:<remote path/folder> <local path/folder>
#!/bin/bash

sudo apt-get install postgresql conquest-common conquest-postgres

sudo su postgres -c "createdb dicomserver"
sudo su postgres -c "createuser dicomserver"
sudo su postgres -c "psql -c \"ALTER USER dicomserver WITH ENCRYPTED PASSWORD 'dicomserver'\""
sudo su postgres -c "psql -c \"GRANT ALL PRIVILEGES ON DATABASE dicomserver TO dicomserver\""

sudo sed -i 's/CONQUESTSRV1/DICOMSERVER/g' /etc/conquest-dicom-server/dicom.ini
sudo sed -i 's/CONQUESTSRV1/DICOMSERVER/g' /etc/conquest-dicom-server/acrnema.map

sudo sed -i 's/SQLServer\s*\=\ conquest/SQLServer\ =\ dicomserver/g' /etc/conquest-dicom-server/dicom.ini
sudo sed -i 's/Username\s*\=\ postgres/Username\ =\ dicomserver/g' /etc/conquest-dicom-server/dicom.ini
sudo sed -i 's/Password\s*\=\ postgres/Password\ =\ dicomserver/g' /etc/conquest-dicom-server/dicom.ini

sudo sed -i 's/DGATE_ENABLE\=false/DGATE_ENABLE\=true/g' /etc/default/dgate

sudo service dgate stop
sudo service postgresql restart
sudo dgate -v -r
sudo service dgate start

#when installed: AET=DICOMSERVER, PORT=11112
$> pdfinfo document.pdf | grep "Pages\:" | grep -o "[0-9]"
#split the file into pieces:

  $> split --bytes=10M /path/to/bigfile.ext /path/to/image/prefixForPieces

#then put'em together again when necessary

  $> cat prefixForPieces* > bigfile.ext
#iptables -A INPUT -s <ipaddress> -j DROP

iptables -A INPUT -s 65.55.44.100 -j DROP
iptables-save

#un-block

iptables -D INPUT -s xx.xxx.xx.xx -j DROP
iptables -D INPUT -s xx.xxx.xx.xx/yy -j DROP
iptables-save
#> sudo apt-get install nethogs
#> sudo nethogs <network interface>

#example:

$> sudo nethogs eth0
#iptables -A OUTPUT -d <ipaddress> -j DROP

iptables -A OUTPUT -d 119.140.145.206 -j DROP
iptables-save
find ./ -name <filemask>* -exec dcmodify \
  -m "(0010,0010)=MOLINA^HERNAN" \
  -m "(0010,0020)=3207639" \
  -m "(0010,0030)=19411128" \
  -m "(0010,0040)=M" \
  -m "(0008,0050)=" \
  -m "(0040,0275)[0].(0032,1060)=RMN HOMBRO IZQUIERDO" \
  -m "(0040,0275)[0].(0040,0007)=RMN HOMBRE IZQUIERDO" {} \;
#for not running docker, use save:
docker save <dockernameortag> | gzip > mycontainer.tgz

#for running or paused docker, use export:
docker export <dockernameortag> | gzip > mycontainer.tgz

#load
gunzip -c mycontainer.tgz | docker load
sudo su
cat /dev/null > /etc/apt/apt.conf
echo 'Acquire::http::Proxy "false";' > /etc/apt/apt.conf.d/proxy
apt-get update 
#!/bin/bash
# Delete all containers

$ docker rm $(docker ps -a -q)

# Delete all images

$ docker rmi $(docker images -q)
convert -density 144 myfile.pdf[0] -resize 10% -background white -alpha remove -strip -quality 90 mypreview.jpg
#this command shows a list of supported encodings:
#pdftotext -listenc 

#this command convert pdf to html:
#pdftohtml -c -s -enc <encoding> <pdf to convert> <output html file>

#Ex:

pdftohtml -c -s -enc Latin1 test.pdf test.html
# let's create a backup from remote postgresql database using pg_dump:
#
#   pg_dump -h [host address] -Fc -o -U [database user] <database name> > [dump file]
#
# later it could be restored at the same remote server using:
#
#   sudo -u postgres pg_restore -C mydb_backup.dump
#
#Ex:

pg_dump -h 67.8.78.10 -p 5432 -Fc -o -U myuser mydb > mydb_backup.dump

pg_restore -C mydb_backup.dump



#complete (all databases and objects)

pg_dumpall -U myuser -h 67.8.78.10 -p 5432 --clean --file=mydb_backup.dump


#restore from pg_dumpall --clean:

psql -f mydb_backup.dump postgres #it doesn't matter which db you select here
# warning: this is not script, it's a set of instructions.
#these steps create pptp vpn server so all clients can reach all others clients.

##################### SERVER SIDE (UBUNTU SERVER 16.04+) ######################

sudo apt-get install pptpd
sudo update-rc.d pptpd defaults

# I had to use this on 16.04... it fixes autostart problem:
sudo systemctl enable pptpd 

#edit file "/etc/pptpd.conf": example using nano: $> sudo nano /etc/pptpd.conf
#add the following lines:
    
    localip 10.20.0.1
    remoteip 10.20.1.100-200 #100 clients
#save it
        
#edit file "/etc/ppp/chap-secrets": example using nano: $> sudo nano /etc/ppp/chap-secrets
#add all clients with fixed ip addresses (change user1, user2... and password1, password2,.. according to your preference):

    user1 pptpd password1 10.20.1.100 
    user2 pptpd password2 10.20.1.101
    user3 pptpd password3 10.20.1.200
    :
#save it

#edit/add this line at "/etc/systl.conf":
    net.ipv4.ip_forward = 1
#save change:
sudo sysctl -p

#Configure iptables for forwarding (let clients see all each other):

iptables --table nat --append POSTROUTING --out-interface ppp0 -j MASQUERADE
iptables -I INPUT -s 10.20.0.0/16 -i ppp0 -j ACCEPT
iptables --append FORWARD --in-interface enp0s8 -j ACCEPT
iptables-save

#restart your service:

sudo service pptpd restart


##################### CLIENT SIDE FOR UBUNTU SERVER ######################

## Start client side (Ubuntu Server (w/o GUI)):
##
## ============================================================
## 1) Configure pptp: (Change your <vpn server address>)
##   (in this example we named the provider as "pptpserver")
## ============================================================

sudo apt-get install pptp-linux

sudo nano /etc/ppp/peers/pptpserver

# add the following lines:

pty "pptp <vpn server address> --nolaunchpppd"
lock
noauth
nobsdcomp
nodeflate
name server
password 13132828
remotename pptpserver
persist
maxfail 0
holdoff 5
require-mppe-128

# and save (ctrl-o ctrl-x)

# ==================================================================
# 2) Create config file for adding route automatically when startup:
#    this is necessary in order to not use vpn internet connection
#    (use same name of provider, in my case "pptpserver")
# ==================================================================

sudo nano /etc/ppp/ip-up.d/pptpserver

# add the wollowings lines:

#!/bin/bash
# This script is called with the following arguments:
# Arg Name
# $1 Interface name
# $2 The tty
# $3 The link speed
# $4 Local IP number
# $5 Peer IP number
# $6 Optional ''ipparam'' value foo
/sbin/route add -net 10.20.0.0 netmask 255.255.0.0 dev ppp0


# and save (ctrl-o ctrl-x)
#... then set execute permission:

sudo chmod +x /etc/ppp/ip-up.d/pptpserver

# ============================================================
#   STARTUP CONNECTION
# ============================================================

# ------------------------------------
# 1) Manual startup:
# ------------------------------------

sudo pon pptpserver

# ------------------------------------
# 2) Auto startup on boot:
# ------------------------------------

#
# a) USING INTERFACES: Edit interfaces file:
#

sudo nano /etc/network/interfaces

# add the following lines to the end:

auto tunnel
iface tunnel inet ppp
  provider pptpserver

# and save (ctrl-o ctrl-x)
# then restart networking:

sudo /etc/init.d/networking restart

#
# b) USING SERVICE SYSTEMCTL
#

sudo nano /etc/systemd/system/pppoe.service

# add these lines:

[Unit]
Description=PPPoE connection
 
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/usr/bin/pon pptpserver
ExecStop=/usr/bin/poff -a
 
[Install]
WantedBy=default.target

# and save
# then change permissions:

sudo chmod +x /etc/systemd/system/pppoe.service

# then reload daemons:

systemctl daemon-reload

# and it will connect on boot.

#start:
sudo systemctl start pppoe

#stop:
sudo systemctl stop pppoe
##sudo nano /etc/udev/rules.d/95-monitor-hotplug.rules

SUBSYSTEM=="drm", RUN+="/usr/local/bin/fix_tv_state.sh"

##---------------------



##sudo nano /usr/local/bin/fix_tv_state.sh

#!/bin/sh
#Fix TV state when HDMI link is lost.

export XAUTHORITY=/home/marco/.Xauthority

OUTPUT="HDMI1"
BAD_MODE="1280x720"
GOOD_MODE="1920x1080"

for MODE in $BAD_MODE $GOOD_MODE; do
 sleep 2
 DISPLAY=:0 xrandr --output $OUTPUT --mode $MODE
 sleep 2
done

##--------------------

sudo chmod +x /usr/local/bin/fix_tv_state.sh
sudo udevadm control --reload-rules

# Edit your /etc/postgresql/9.3/main/postgresql.conf, and change the lines as follows:

# Note: If you didn't find the postgresql.conf file, then just type 

$> locate postgresql.conf 

# in a terminal

1) change #log_directory = 'pg_log' to log_directory = 'pg_log'
2) change #log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' to log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
3) change #log_statement = 'none' to log_statement = 'all'
4) change #logging_collector = off to logging_collector = on

# Optional: SELECT set_config('log_statement', 'all', true);

sudo /etc/init.d/postgresql restart or sudo service postgresql restart

#Fire query in postgresql: select 2+2

# Find current log in /var/lib/pgsql/9.2/data/pg_log/

#The log files tend to grow a lot over a time, and might kill your machine. For your safety, write a bash script that'll delete logs and restart postgresql server.
#changes in /etc/nginx/sites-available/default

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # blah blah
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}
1) Instalar php7.0 y php7.0-fpm

2) modificar:

  /etc/nginx/conf.d/onlyoffice-documentserver.conf

y colocar dentro de Server 

location /myfolder {
        alias /var/www/html/myfolder;
        index index.php index.html index.htm;
        location ~ \.php$ {
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_param SCRIPT_FILENAME $request_filename;
                include fastcgi_params;
        }

  }
 
3) reiniciar los servicios nginx y php7-0-fpm
# remote linux computer: 192.168.0.62 / example user: mybackup

# fist create user on remote machine: (don't forget password).

sudo adduser mybackup

# then, on local machine, generate public rsa key of our user. 
# using local user (to be conected to remote) at user's home do:

ssh-keygen -t rsa

# to answer each question just press [ENTER].

# then from local folder user's home (/home/mybackup):

# 1) Create .ssh directory on remote machine:

ssh mybackup@192.168.0.62 mkdir -p .ssh

# 2) Copy generated key:

cat .ssh/id_rsa.pub | ssh mybackup@192.168.0.62 'cat >> .ssh/authorized_keys'

# 3) Change permissions:

ssh mybackup@192.168.0.62 "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"

# 4) Test your login: (it must work without password):

ssh mybackup@192.168.0.62
# NGINX: add <folder> in /etc/nginx/sites-available/default: 

server {
    :
    location /<folder>/ {
        proxy_pass http://<host>:<port>/;
        proxy_set_header X-Original-Host $http_host;
        proxy_set_header X-Original-Scheme $scheme;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
    :
}
    
# APACHE2: add <folder> in /etc/apache2/sites-available/00-default.conf

<VirtualHost *:80>
    :
        ProxyPass /<folder> http://<host>:<port>/
        ProxyPassReverse /<folder> http://<host>:<port>/

        ProxyRequests Off
        ProxyPreserveHost On

        <proxy>
            Order deny,allow
            Allow from all
        </proxy>
    :
</VirtualHost>


#examples: folder "http://192.168.11.45/demo -> http://192.168.11.45:8080/"

server {
    :
    location /demo/ {
        proxy_pass http://localhost:8080/;
        proxy_set_header X-Original-Host $http_host;
        proxy_set_header X-Original-Scheme $scheme;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
    :
}

<VirtualHost *:80>
    :
        ProxyPass /demo http://localhost:8080/
        ProxyPassReverse /demo http://localhost:8080/

        ProxyRequests Off
        ProxyPreserveHost On

        <proxy>
            Order deny,allow
            Allow from all
        </proxy>
    :
</VirtualHost>

/* other configuration for nginx:
    
server {
    listen        80;
    server_name   example.com *.example.com;
    location / {
        proxy_pass         http://127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}
*/
#install unison

$ sudo apt install unison

# synchronizing from local folder "/home/user/sync/" with remote "ssh://user@remotehost.com/" folder "/home/user/sync/" (ssh port 22000)


$ unison -silent -auto -batch /home/user/sync/ ssh://user@remotehost.com//home/user/sync/ \
  -nodeletion ssh://user@remotehost.com//home/user/sync/ \
  -sshargs '-p22000' -logfile /tmp/mylog.txt
#bypassing [n] files, (we must use [n+1]):

$ find <folder> -maxdepth 1 -type f -printf "%T@ %Tc %p\n" | grep -v '/\.' | sort -r | tail -n +60 | grep -Po "\./.*"

$ for f in "`find -maxdepth 1 -type f -print0 | xargs -r0 stat -c %y\ %n | grep -v '\.\/\.' | sort -r | grep -Po '\./.*' | tail -n +61`"; do 
    printf "$f\n"
$ done
#
# first you must stablish iptables rule for keeping port 22 closed
# and ports to use as combination. I used 3030, 55050 and 7070 (is very important
# to use unsorted ports)
#
#  #-- rules to keep open combination ports:
#

sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

#
#  #-- rules to keep ssh port (22) closed:
#

sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j DROP

#
#  #-- then we save iptables
#

sudo iptables-save

#
#  #-- if you want to know how to make this rules "persistent" search info on google about
#      iptables-persistent package or look at this url 
#
#      http://askubuntu.com/questions/119393/how-to-save-rules-of-the-iptables
#
#      it helped me.
#

# debian and derived distros... install knockd:

sudo apt-get install knockd

# we edit /etc/default/knockd: (knockd confif file)

sudo nano /etc/default/knockd

# and set:

    START_KNOCKD=0
    
# to

    START_KNOCKD=1
    
# let's create our ports sequence: let's say 3030,55050,7070 = open, and 7070,55050,3030 = close.
# for this we edit /etc/knockd.conf:

sudo nano /etc/knockd.conf:
    
[options]
  UseSyslog

[openSSH]
  sequence    = 3030,55050,7070
  seq_timeout = 1
# add our input access to iptables  
  command     = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j DROP
  tcpflags    = syn

[closeSSH]
  sequence    = 7070,55050,3030
  seq_timeout = 1
# delete our input access to iptables
  command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j DROP
  tcpflags    = syn
  
# we start service:

sudo /etc/init.d/knockd start

# That's all, we're done.
# .. and now... How can I open my host's ssh port (22) from remote location?
# ... just like this (using telnet):

# OPEN:
telnet 192.168.1.33 3030; telnet 192.168.1.33 55050; telnet 192.168.1.33 7070

# you'll this output at syslog (example with 192.168.1.33):

#  knockd: 192.168.1.33: openSSH: Stage 1
#  knockd: 192.168.1.33: openSSH: Stage 2
#  knockd: 192.168.1.33: openSSH: Stage 3
#  knockd: 192.168.1.33: openSSH: OPEN SESAME
#  knockd: openSSH: running command: /sbin/iptables -I INPUT -s 192.168.1.33...



# and then we CLOSE it:
telnet 192.168.1.33 7070; telnet 192.168.1.33 55050; telnet 192.168.1.33 3030

# you'll this output at syslog (example with 192.168.1.33):

#  knockd: 192.168.1.33: closeSSH: Stage 1
#  knockd: 192.168.1.33: closeSSH: Stage 2
#  knockd: 192.168.1.33: closeSSH: Stage 3
#  knockd: 192.168.1.33: closeSSH: OPEN SESAME
#  knockd: closeSSH: running command: /sbin/iptables -D INPUT -s 192.168.1.33...

#This will report the percentage of memory in use

% free | grep Mem | awk '{print $3/$2 * 100.0}'

#Ex:23.8171

#This will report the percentage of memory that's free

% free | grep Mem | awk '{print $4/$2 * 100.0}'

#Ex:76.5013

#You could create an alias for this command or put this into a tiny shell script. The specific output could be tailored to your needs using formatting commands for the print statement along these lines:

% free | grep Mem | awk '{ printf("free: %.4f %\n", $4/$2 * 100.0) }'
#Using a single line of GhostScript command on my Ubuntu’s terminal, I was able to reduce the size of a  PDF file from 6 MB to approximately 1 MB:

$ gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -sOutputFile=output.pdf input.pdf

# You can use the following parameters for -dPDFSETTINGS instead of /screen:

# /screen – Lowest quality, lowest size (ugly)
# /ebook – Moderate quality
# /printer – Good quality
# /prepress – Best quality, highest size
#just add this line at the end of /etc/ssh/sshd_config

AllowUsers <thelogin> 

pgrep -af <name of running process>

#who is running last created binary in /usr/bin (attack): (sudo apt-get install inotify-tools)
inotifywait -e create /usr/bin | echo $(awk '{print $3}') | xargs pgrep -af

#which process is calling this ID?
ls -l /proc/<ID>/exe
/etc/php/7.0/fpm/pool.d/www.conf:

pm = dynamic
pm.max_children = 30 (original: 5)
pm.start_servers = 3 (original: 1)
pm.min_spare_servers = 2 (original: 1)
pm.max_spare_servers = 4 (original: 3)
pm.max_requests = 500 (originally commented)
$ sudo nano /etc/environment

#
# (Append these lines at the end of file:)

http_proxy="http://myproxy.server.com:8080/"
https_proxy="http://myproxy.server.com:8080/"
ftp_proxy="http://myproxy.server.com:8080/"
no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
HTTP_PROXY="http://myproxy.server.com:8080/"
HTTPS_PROXY="http://myproxy.server.com:8080/"
FTP_PROXY="http://myproxy.server.com:8080/"
NO_PROXY="localhost,127.0.0.1,localaddress,.localdomain.com"

#
# (save and... )

$ source /etc/environment

# To unset proxies:

# sudo nano /etc/environment
#
# (Remove proxies lines (see above))
#
# (save and them...) 

unset http_proxy
unset https_proxy
unset ftp_proxy
unset no_proxy
unset HTTP_PROXY
unset HTTPS_PROXY
unset FTP_PROXY
unset NO_PROXY

# (that's all)


# ========== using proxies for apt (it does not obey proxy configuration):

# (we create a new file at /etc/apt/apt.conf.d/)
#

$ sudo nano /etc/apt/apt.conf.d/95proxies

# (now append this lines...)

Acquire::http::proxy "http://myproxy.server.com:8080/";
Acquire::ftp::proxy "ftp://myproxy.server.com:8080/";
Acquire::https::proxy "https://myproxy.server.com:8080/";

# (save and run "sudo apt update" for trying...)
#
diff -r dir1 dir2 | grep dir1 | awk '{print $4}' > difference1.txt; clear; cat difference1.txt
# duration time of file:
#   ej: sox --i -D test.ogg

  sox --i -D <sound file>

# play sound to default output
#    Linux/OSX?: 

  sox <sound file> -d

#    Windows: 

  sox <sound file> -t waveaudio
  
# record sound from default input:
#    Linux/OSX?: 

  sox -t alsa <output file>
  
#    Windows:
  
  sox -t waveaudio -d <output file>
  
# play sound from starting time (secs) (trim):
#    Linux/OSX?:

  sox <sound file> -d trim <n secs>
  
#    Windows:

  sox <sound file> -t waveaudio trim <n secs>
  
# split big file into small files with equal time fraction:
#    %1n = autoincremental: 1,2,3...

  sox <input file> <output file>_%1n.ogg trim 0 <secs> : newfile : restart
  
# concatenate small files into one:

  sox <input file1> <input file2> ... <input filen> <output file>

# cut silences with tolerance:

  sox in.wav out.wav silence -l 1 0.1 1% -1 2.0 1%
#convert VDI to RAW:
$ vboxmanage clonehd --format RAW ubuntu.vdi ubuntu.img

#mount RAW:
$ mount -t ext3 -o loop,rw ./ubuntu.img /mnt
find /src/dir/ -mtime -<n days> -printf %P\\0|rsync --files-from=- --from0 /src/dir/ /dst/dir/
# create mount folder:

mkdir /tmp/my10mbvirtualdisk

# create file system (filename=filesyst in current folder) (10Mb):

dd if=/dev/zero of=./filesyst bs=10485760 count=1
sudo losetup /dev/loop0 ./filesyst
sudo mkfs.ext3 /dev/loop0

sudo mount /dev/loop0 /tmp/my10mbvirtualdisk


# now you can use /tmp/my10mbvirtualdisk as disk



# destroy:

sudo umount /tmp/my10mbvirtualdisk
sudo losetup -d /dev/loop0
sudo rm ./filesyst
sudo vgdisplay #ver vg/lvm
sudo pvcreate /dev/sdX /dev....
sudo vgextend <name-vg> /dev/sdX
sudo lvextend -l +100%FREE /dev/<name-vg>/root
sudo resize2fs /dev/<name-vg>/root
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
requires:

1) Install Linux dependences (search for specific linux distro instructions for this):
python-dev, python-pip, freetds-dev, freetds-bin, libaio1

2) Install instantclient-basic-lite
follow these instructions:

http://www.oracle.com/technetwork/database/features/linuxx86-64soft-092277.html?printOnly=1
(go to "Installation of ZIP files" section at the bottom of document)

3) Install python includes:

sudo -H pip install cx_Oracle
sudo -H pip install pymssql

"""

import cx_Oracle
import pymssql

""" ====== let's connect to Oracle DB Server ====="""

orcl_host = "host1"
orcl_port = 1521
orcl_user = "user1"
orcl_pwd  = "password1"
orcl_dbn  = "service_name"

connstr = orcl_user+"/"+orcl_pwd+"@"+orcl_host+":"+str(orcl_port)+"/"+orcl_dbn
orcl = cx_Oracle.connect(connstr)

#If all is correct we will see and object print:

print(orcl)

"""===== let's connect to sqlsvr: ====="""

sql_host = "host2"
sql_user = "user2"
sql_pwd  = "password2"
sql_dbn  = "database_name"

conexion_sql = pymssql.connect(sql_host, sql_user, sql_pwd, sql_dbn)

#If all is correct we will see and object print:

print(conexion_sql)

#just install samba with

$ sudo apt install samba

#and go to this file:

$ sudo nano /etc/samba/smb.conf

#and just at the bottom add these lines:

    [share]
    comment = Ubuntu File Server Share
    path = /path/to/the/folder  #for example /home/user_name/public
    browsable = yes
    guest ok = yes
    read only = no
    create mask = 0755

#restart the samba service

$ sudo service smbd restart
$ sudo service nmbd restart
$ ifconfig -a | grep "inet\s" | awk -F'[: ]+' '{ print $4 }'

$ ip addr  | grep "inet\s" | awk -F'[: ]+' '{ print $3 }'
$> sudo apt-get install cifs-utils

$> sudo mkdir /mnt/shared

$> sudo mount -t cifs -o username=guest,password=,rw,iocharset=utf8,file_mode=0777,dir_mode=0777,noperm //<windows address>/the_folder /mnt/shared/
$> cd <folder>

$> perl -e 'for(<1.*>){((stat)[9]<(unlink))}'

$> find ./ -name "1.*" -exec rm {} \;

$> for i in 1.*; do rm -rf $i; done
$ sudo ip route add prohibit <ip address to block>/32

#Ex: sudo ip route add prohibit 58.15.238.31/32
# Create Channel
# Create new Bot and get Bot TOKEN (to replace TOKEN_OF_BOT)
# and edit:
# /etc/ssh/sshrc

ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

logger -t ssh-wrapper $USER login from $ip

curl -s -X POST https://api.telegram.org/botTOKEN_OF_BOT/sendMessage \
     -d text="Hello world!" -d chat_id=@autanaChannel > /dev/null
#!/bin/bash
# create_barcode.sh
# sudo apt-get install barcode imagemagick

CODE=$1 #the code ... first parameter
FNAME=$2  #the filename .png .... second parameter (without file extension)

# let's create postscript:
barcode -E -b "$CODE" | convert -density 600 ps:- png:- > $FNAME

# use:
#   
#   bash create_barcode.sh 123456789 output.png  #it autodetect's the preferable encoding
#
#   this creates "output.png"
#
# Security Error:
#
# if you get security error: convert not authorized (ps/png) do this:
#
# edit /etc/ImageMagick-6/policy.xml
#
# disable this:

  <!--policy domain="coder" rights="none" pattern="PS" />-->

# and append this:

  <policy domain="coder" rights="read/write" pattern="PNG,PS" />
#from bash command line
#first create folder to save python dependencies:

    > sudo mkdir /var/www/.local
    > sudo mkdir /var/www/.cache
    > sudo chown www-data.www-data /var/www/.local
    > sudo chown www-data.www-data /var/www/.cache

# then install dependencies (imports):

    > sudo -H -u www-data pip install <dep1>
    > sudo -H -u www-data pip install <dep2>
    :
    
# then set user permissions to run your script to www-data user:
# creating a file at /etc/sudoers.d/:

    > sudo nano /etc/sudoers.d/mysudoerfile
    
    www-data ALL=(ALL) NOPASSWD: /usr/bin/python <path of your script here>

# then set execute permissions to your script:

    sudo chmod +x <path of your script here>

# then run your script 
upstream newserver {
  server 172.16.0.1:80;  # this is new server, by IP address
}

server {
  listen 80;
  server_name subdomain.site.com;
  location / {
    proxy_set_header Host $host;
    proxy_pass http://newserver;
  }
}
Over the last few days we've had a couple of issues with Imagick and processing PDFs on our servers. As it turns out, these issues are caused by automatic security updates. Let's look into the issue and its solution.

In Bugsnag, our error reporting service, the following exceptions have been popping up a lot:

not authorized `/path/to/some-pdf.pdf` @ error/constitute.c/ReadImage/412

convert: not authorized `/path/to/some-pdf.pdf` @ error/constitute.c/WriteImage/1028

not authorized `/path/to/some-image.png` @ error/convert.c/ConvertImageCommand/3015

unable to create temporary file `/some/path` Permission denied @ error/pdf.c/ReadPDFImage/465
Upon further investigation it looks like most of our sites and applications dealing with PDFs were actually experiencing issues. The weird thing is, some of these applications are quite old and haven't been updated or even touched for months, whilst others are recent and running the latest versions of packages and OS.

I don't care about your problems, just give me the fix!
A recent ImageMagick security update adds some extra policies regarding PDFs (or more specifcally: Ghostscript). We can actually see the diff for this update right here. Luckily, we can edit the policy.xml file ourselves and loosen up security for working with PDFs.

In /etc/ImageMagick-6/policy.xml (or /etc/ImageMagick/policy.xml) find the following line

<policy domain="coder" rights="none" pattern="PDF" />
and change it to allow reading and writing by the PDF coder in ImageMagick:

<policy domain="coder" rights="read|write" pattern="PDF" />
Finally, don't forget to restart your PHP-FPM and optionally queue workers:

sudo service php7.2-fpm restart
If you're experiencing issues with other file types or manipulations, you might need to change some of the other policies as well. The policy.xml file contains some good documentation in the comments. You can read more about the security policy file on ImageMagick's website.
#!/bin/sh

#----------------------------------------------------------------
# Para que funcione colocar en /usr/local/bin:
#
#     $> sudo cp verifica_nr /usr/local/bin
#
# Dar permiso de ejecución:
#
#     $> sudo chmod +x /usr/local/bin/verifica_nr
#
# Luego se agrega en crontab (cada minuto):
#
#     $> sudo crontab -e
#     (ir al final y agregar:)
#     * * * * * /usr/local/bin/verifica_nr
#     (Guardar)
#----------------------------------------------------------------
SERVICE="nrservice"
if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null
then
    echo "$SERVICE service running, everything is fine" > /dev/null
else
    sudo service nrservice.sh restart
fi
$ find [folder] -type f -exec gdcmscu -L [log] -D --store --call [Target AET] [HOST] [PORT] {} \; &

#Ej:

$ find /mnt/images/dicom/ -type f -exec gdcmscu -L /tmp/output.log -D --store --call AUTANA localhost 11112 {} \; & 
$ sudo nano /etc/fstab

#add line:

//<remote host>/<share>  <mount>  cifs  username=<user>,password=<password>,uid=nobody,noperm,file_mode=0777,dir_mode=0777  0  0  

#Ex:
//200.200.0.124/images_autana  /mnt/nas  cifs  username=autana,password=*****,uid=nobody,noperm,file_mode=0777,dir_mode=0777  0  0  
# =============== first let''s create user/password:
# 1: user

$> sudo sh -c "echo -n 'sammy:' >> /etc/nginx/.htpasswd"

# 2: passsord

$> sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"

# You can repeat this process for additional usernames. You can see how the usernames and encrypted passwords are stored within the file by typing:

# let's see what we did:

$> cat /etc/nginx/.htpasswd

# Output (something like)
# sammy:$apr1$wI1/T0nB$jEKuTJHkTOOWkopnXqC1d1

# then, we need to add configuration:
# at /etc/nginx/sites-available/default (or whatever your configuration is):

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    server_name localhost;
    
    location /myrestrictedfolder {                  #<--- new here
        rewrite ^(.*[^/])$ $1/ permanent;           #<--- new here
        auth_basic "Restricted Content";            #<--- new here
        auth_basic_user_file /etc/nginx/.htpasswd;  #<--- new here
    }                                               #<--- new here

    location / {
        try_files $uri $uri/ =404;
    }
}

# then restart nginx daemon:

$> sudo service nginx restart


#you will be asked for basic user/password when entering: http://localhost/myrestrictedfolder/
# Backup:
docker exec -t -u postgres your-db-container pg_dumpall -c > dump_`date +%d-%m-%Y"_"%H_%M_%S`.sql

# Restore:
cat your_dump.sql | docker exec -i your-db-container psql -U postgres
#add this lines to /etc/mosquitto/mosquitto.conf

listener 1883
protocol mqtt

listener 9001
protocol websockets

#then restart service:  $> sudo service mosquitto restart
<?php

// sudo apt install php7.0-sybase


header("content-type: text/plain; charset=iso-8859-1");
ini_set("display_errors","1");
error_reporting(E_ALL);

$host="localhost";
$db="test";
$uid="sa";
$pwd="mypassword";

$query = "select top 10 * from testtable";

$conn = new PDO( "dblib:host=$host:1433;dbname=$db;", $uid, $pwd);
$stmt = $conn->prepare( $query );
$stmt->execute();

while ($r=$stmt->fetch(PDO::FETCH_ASSOC)){
	print_r($r);
}

?>
#!/bin/bash
#exit

#detect if port 11111 is open, if not do action:

netstat -ln | grep ":11111 " 2>&1 > /dev/null

if [ $? -eq 1 ]; then
    echo "Port is closed. Doing action..."
fi
<?php

shell_exec("php Server.php > /dev/null 2>/dev/null &");
ls -lct /etc | tail -1 | awk '{print $6, $7, $8}'
$> pdftk file1.pdf file2.pdf file3.pdf cat output outputfile.pdf
wget -U "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" -qO - "https://example.com"

# Example
# wget -U "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" -qO - "https://www.infodolar.com.do/precio-dolar-entidad-banco-popular.aspx" | grep colCompraVenta | grep -Eo "([0-9.]+)" | head -1
<?php

/*==========  install at ubuntu: ==============

sudo apt install php-sybase


//==================================

append this into /etc/freetds/freetds.conf:
(192.168.0.250:2638 is an example:)

//==================================

sudo nano /etc/freetds/freetds.conf

[connName]
    host = 192.168.0.250  
    port = 2638
    tds version = 7.4
    database = MYDB
    
//======  php: */

$connName = "connName";
$user = "myuser";
$pass = "mypass";

$st="dblib:host=$connName;charset=iso8859-1";
$conn = new PDO($st,$user,$pass);

/* $conn->prepare($sql_query);
...etc
*/
# edit /etc/environment
# 
# add:
#
# LANG=es_DO.utf-8
# LC_ALL=es_DO.utf-8

# Then: logout ... login, then run this command:

$ sudo dpkg-reconfigure locales
#!/bin/bash

#--- xvfb
sudo apt install -y xvfb

#-- add this into /etc/rc.local:

    #!/bin/sh -e
    Xvfb -ac :99 -screen 0 1024x768x16 &
    exit 0

#-- save & first run:
Xvfb -ac :99 -screen 0 1024x768x16 &

#--- wine
sudo dpkg --add-architecture i386

wget -O- -q https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04/Release.key | sudo apt-key add -
echo "deb http://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04 ./" | sudo tee /etc/apt/sources.list.d/wine-obs.list

sudo apt update
sudo apt install --install-recommends winehq-stable winetricks

wine --version
wine --help

wineboot -u

winetricks allfonts

#-- install my app at /opt
sudo mkdir -p /opt/report/cache
sudo chmod -R 777 /opt/report
cp ReportService5.exe /opt/report
cd /opt/report

#-- and test it:
DISPLAY=:99 wine ReportService5.exe </dev/null &>/dev/null &

#-- create systemd service:

sudo nano /lib/systemd/system/report-service.service

[Unit]
Description=Reporting service

[Service]
Environment="DISPLAY=:99"
WorkingDirectory=/opt/report
ExecStart=/usr/bin/wine "/opt/report/ReportService5.exe" </dev/null &>/dev/null &
ExecStop=/opt/report/stop.sh
User=autana

[Install]
WantedBy=graphical.target

#-- save.

#-- create stop.sh

nano /opt/report/stop.sh

#!/bin/bash
kill $(pgrep ReportService5.exe)
kill -9 $(pgrep winedevice.exe)

#-- save.

sudo chmod +x /opt/report/stop.sh

#-- start service:
sudo systemctl enable report-service
sudo systemctl start report-service

DISPLAY=:99 import -window root -quality 90 /tmp/screenshot.jpg

docker ps -q | xargs -n 1 docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} {{ .Name }}' | sed 's/ \// /'
#!/bin/bash
printf "%-10s%-15s%-15s%s\n" "PID" "MEMORY" "OWNER" "COMMAND"

function sysmon_main() {
        RAWIN=$(ps -o pid,user,%mem,command ax | grep -v PID | awk '/[0-9]*/{print $1 ":" $2 ":" $4}') 
        for i in $RAWIN
        do
                PID=$(echo $i | cut -d: -f1)
                OWNER=$(echo $i | cut -d: -f2)
                COMMAND=$(echo $i | cut -d: -f3)
                MEMORY=$(pmap $PID | tail -n 1 | awk '/[0-9]K/{print $2}')

                printf "%-10s%-15s%-15s%s\n" "$PID" "$OWNER" "$MEMORY" "$COMMAND"
        done
}

sysmon_main | sort -bnr -k3 | head -20
$ mkdir /var/www/html/vscode

$ htpasswd -c /var/www/html/vscode/pass marco
#for updating: htpasswd /var/www/html/vscode/pass marco

$ docker pull linuxserver/code-server

$ docker run -d \
  --name=code-server \
  -e PUID=1000 \
  -e PGID=1000 \
  -e TZ=America/Caracas \
  -e FILE__PASSWORD=/var/www/html/vscode/pass \
  -p 8943:8443 \
  -v /var/www/html/vscode-config:/config \
  --restart unless-stopped \
  linuxserver/code-server

$ docker start code-server
gsec -user sysdba -pass masterkey -add billyboy -pw sekrit66 -admin yes
location /worklist/ {
    try_files $uri $uri/ /worklist/index.php$is_args$args;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    fastcgi_index worklist/index.php;
}

#
# from php you can use and index.php getting path as $_SERVER["REQUEST_URI"]
#
#backup

gbak -t -v -user <username> -password "<password>" <host>:/path/to/db.fdb path/to/file.gbk

#restore

gbak -c -v -user <username> -password "<password>" path/to/file.gbk <host>:/path/to/db.fdb
# go to path where .git is

# new branch:

$> git checkout -b "<name_of_new_branch>"

# change branch:

$> git checkout "<name_of_branch>"



$> git add <folder1> ... <foldern>

$> git commit -m "<commentn>"
    
#example: <branch> = main:

$> git push origin <branch>

#---------------------------------------------------------

# download last changes from branch:

$> git pull origin <branch>
$> docker pull haskell
$> docker run -it haskell stack <parameters>


$> git clone https://github.com/jean-lopes/dfm-to-json.git

$> cd dfm-to-json

$> stack setup
$> stack install
$> dfm-to-json --version
sudo mkdir -p /your/custom/path/oracle-19c/oradata/
sudo chmod -R 777 /your/custom/path/

docker run -d --name oracle19db \
  -p 1521:1521 \
  -e ORACLE_SID=ORCL \
  -e ORACLE_PDB=ORCLDB \
  -e ORACLE_PWD=Oracle123 \
  -e ORACLE_CHARSET=AL32UTF8 \
  -v /your/custom/path/oracle-19c/oradata:/opt/oracle/oradata \
  banglamon/oracle193db:19.3.0-ee

# Charset Value: WE8MSWIN1252, AL16UTF8

# ALTER SESSION SET NLS_DATE_FORMAT = 'RRRR-MM-DD';
# ALTER SESSION SET NLS_TIME_FORMAT = 'HH24:MI:SS';
# ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'RRRR-MM-DD HH24:MI:SS';
# ALTER SESSION SET NLS_TIME_TZ_FORMAT = 'HH24:MI:SS TZR';
# ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT = 'RRRR-MM-DD HH24:MI:SS TZR';

# docker exec -it oracle19db bash -c "source /home/oracle/.bashrc; sqlplus /nolog”
# connect sys as sysdba;

# alter session set "_ORACLE_SCRIPT"=true;
# create user sistemas identified by las36horas;
# GRANT CONNECT, RESOURCE, DBA TO sistemas;
# GRANT UNLIMITED TABLESPACE TO sistemas;
docker run -e 'ACCEPT_EULA=Y' \
    -e 'MSSQL_SA_PASSWORD=<YourStrong!Passw0rd>' \
    -p 1433:1433 -v <host directory>/data:/var/opt/mssql/data \
    -v <host directory>/log:/var/opt/mssql/log \
    -v <host directory>/secrets:/var/opt/mssql/secrets \
    -d mcr.microsoft.com/mssql/server:2019-latest
$> sudo visudo

www-data ALL=NOPASSWD: /usr/bin/docker

<?php
    echo '<pre>';
    $content = system('sudo docker images', $ret);
    echo '</pre>';
?>

// si se necesita executar exec, hacerlo sin el "-it"
docker run -d --restart=always \
        --name oracle \
        --privileged  \
        -e ORACLE_SID=<custom sid> \
        -v /srv/oradata:/u01/app/oracle \
        -p 8080:8080 -p 1521:1521 \
 absolutapps/oracle-12c-ee
export ORACLE_SID=$1
export NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P9
export USUARIO=system/org24h
export PATHBACKUP=/respaldo/o24/export
export FILENAME=CMLGDB`date +%d%m%Y%H%M`.DMP
export FILENAMELOG=CMLGDB`date +%d%m%Y%H%M`.log
echo  $PATHBACKUP

rm $PATHBACKUP/*.* -rf

if [ -a $PATHBACKUP ] ; then
	expdp $USUARIO FULL=yes DUMPFILE=dpump_dir1:$FILENAME LOGFILE=dpump_dir1:$FILENAMELOG
	#exp $USUARIO file=$PATHBACKUP/$FILENAME full=yes compress=yes indexes=no consistent=yes log=$PATHBACKUP/$FILENAMELOG
else
	echo "ERROR: Export no encontro el directorio de Respaldo"
	exit 1
fi
#Increment timeout and max_children:

/etc/php/7.0/fpm/php.ini  =>   default_socket_timeout = 60000
/etc/php/7.0/fpm/php.ini  =>   pm.max_children = 20
/etc/php/7.0/fpm/pool.d/www.conf  =>   request_terminate_timeout = 60000

#Increment timeout on /etc/nginx/nginx.conf:
keepalive_timeout 65000;

#After Restart php-fpm and nginx:

sudo service php7.0-fpm restart
sudo service nginx restart
1) instala lazarus normal

2) instala estas dependencias:

sudo apt-get install msttcorefonts
sudo apt-get install gsfonts
sudo apt-get install sqlite3 libsqlite3-dev
sudo apt-get install libcanberra-gtk-module

3) abre lazarus

4) ve a "packages=> open package file .lpk"

5) en la ventana de busqueda ubica la carpeta donde tienes los fuentes de fast report, yo lo hice con el 6.6

6) vas a buscar el archivo fs_lazarus.lpk y le vas a dar a open

7) en la ventana nueva dale a "compile" y cuando termine vas a "use=>install" en la misma ventanita

8) vas a repetir el mismo proceso del 4 al 7 para estos otros archivo:
fr6_lazarus.lpk
frxchartlazarus.lpk
frxlazdbf.lpk
frxe6_lazarus.lpk
frxlazsqlite.lpk 
fswatch -r --event=Created --event=Updated --event=Renamed --format=%p -0 MYFOLDER/ | xargs -0 -n1 -I{} mycommand "{}"
docker run -d -e ACCEPT_EULA=Y -e "SA_PASSWORD=P@ssW0rd" -p 1433:1433 \
  --restart unless-stopped \
  -v /var/opt/mssql/data:/var/opt/mssql/data \
  -v /tmp/:/backups/ \
  --name sqlserver \
  mcr.microsoft.com/mssql/server

#backup:

# /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P P@ssW0rd -Q "BACKUP DATABASE [dbname] TO DISK = N'/tmp/dbname-full.bak' WITH NOFORMAT, NOINIT, NAME = 'dbname-bak-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"

# /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P P@ssW0rd -Q "BACKUP LOG [dbname] TO DISK = N'/tmp/dbname-log.bak' WITH NOFORMAT, NOINIT, NAME = N'dbname-bak-log', NOSKIP, NOREWIND, NOUNLOAD, STATS = 5"

#restore:

# /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P P@ssW0rd -Q "RESTORE DATABASE [dbname] FROM DISK = N'/tmp/dbname-full.bak' WITH FILE = 1, NOUNLOAD, REPLACE, NORECOVERY, STATS = 5"

# /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P P@ssW0rd -Q "RESTORE LOG [dbname] FROM DISK = N'/var/opt/mssql/data/dbname-log.bak'"


#create login myuser with password ='strongPass';
#create user myuser for login myuser;
#ALTER LOGIN [myuser] enable;
docker run -v /home/marco:/backup --rm svarcoe/mssql-scripter mssql-scripter -S 172.18.0.3 -d CMUCE -U sa -P CMuce1970@ --schema-and-data -f /backup/mssql-scripter-CMUCE.sql

# BACKUP: 
BACKUP DATABASE [YourDB] TO  DISK = N'C:\xxxxx or /var/opt/mssql/backup/YourDB.bak'
WITH NOFORMAT, NOINIT, NAME = N'YourDB-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO

# RESTORE:
sqlcmd -S localhost -U SA

RESTORE DATABASE YourDB
FROM DISK = '/var/opt/mssql/backup/YourDB.bak'
WITH MOVE 'YourDB' TO '/var/opt/mssql/data/YourDB.mdf',
MOVE 'YourDB_Log' TO '/var/opt/mssql/data/YourDB_Log.ldf'
GO
# Enable:

xdg-screensaver activate

# disable 

export DISPLAY=:0.0; xdotool key 27
You can determine the version of the primary MDF file of a database by looking at the two bytes at offset 0x12064

SQL Server Version	    Internal DB Version     DB Compat Level	    Supported DB Compatibility Levels
SQL Server 2022             ?                           160	                       ?
SQL Server 2019 CTP 3.2 / RC 1 / RC 1.1 / RTM	
                            904	                        150	        150,140,130,120,110,100
SQL Server 2019 CTP 3.0 / 3.1	
                            902	                        150	        150,140,130,120,110,100
SQL Server 2019 CTP 2.3 / 2.4 / 2.5	
                            897	                        150	        150,140,130,120,110,100
SQL Server 2019 CTP 2.1 / 2.2	
                            896	                        150	        150,140,130,120,110,100
SQL Server 2019 CTP 2.0	    895	                        150	        150,140,130,120,110,100
SQL Server 2017	            868 / 869	                140	        140,130,120,110,100
SQL Server 2016	            852	                        130         130,120,110,100
SQL Server 2014	            782	                        120	        120,110,100
SQL Server 2012	            706	                        110	        110,100,90
SQL Server 2012 CTP1
(a.k.a. SQL Server 2011 Denali)	
                            684	                        110	        110,100,90
SQL Server 2008 R2	        660 / 661	                100	        100,90,80
SQL Server 2008	            655	                        100	        100,90,80
SQL Server 2005 SP2+
with VarDecimal enabled	    612	                        90	        90,80,70
SQL Server 2005	            611	                        90	        90,80,70
SQL Server 2000	            539	                        80	        80,70
SQL Server 7.0	            515	                        70	        70
SQL Server 6.5	            408                     	65	        65
SQL Server 6.0	            406	                        60	        60
#Copy the image

$ docker pull doctorkirk/oracle-19c

#Create local directory

$ mkdir -p /your/custom/path/oracle-19c/oradata
$ cd /your/custom/path/
$ sudo chown -R 54321:54321 oracle-19c/

#Run the Container

docker run --name oracle-19c \
  -p 1521:1521 \
  -e ORACLE_SID=[ORACLE_SID] \
  -e ORACLE_PWD=[ORACLE_PASSWORD] \
  -e ORACLE_CHARACTERSET=[CHARSET] \
  -v /your/custom/path/oracle-19c/oradata/:/opt/oracle/oradata \
doctorkirk/oracle-19c

#Charset: WE8MSWIN1252(*default), AL16UTF8, US7ASCI
#* If omitted in docker run , the default characterset for this build will be WE8MSWIN1252.
#Backup

gbak -b -v -user SYSDBA -password "masterkey" D:\database.FDB E:\database.fbk

#Restore

gbak -c -user SYSDBA -password masterkey E:\database.fbk E:\database_restore.fdb
server {
  server_name cmlg.com;

  location / {
        #rewrite ^/(.*) $1 break;
        #proxy_set_header Host $host;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://cmlg.dyndns.info:8888/;
  }

}
From server console:

$> nano /etc/pve/lxc/{machine id, ex:100}.conf

add: 

lxc.cgroup2.devices.allow: c 10:200 rwm
lxc.mount.entry: /dev/net dev/net none bind,create=dir

$> chown 100000:100000 /dev/net/tun
$> chmod 666 /dev/net/tun

$> ls -l /dev/net/tun

Restart machine
sudo adduser brsmt
sudo usermod -aG sudo brsmt
#sudo apt install poppler-utils

curl -s "<url of pdf file>" | pdftotext -layout - -

Similiar Collections

Python strftime reference pandas.Period.strftime python - Formatting Quarter time in pandas columns - Stack Overflow python - Pandas: Change day - Stack Overflow python - Check if multiple columns exist in a df - Stack Overflow Pandas DataFrame apply() - sending arguments examples python - How to filter a dataframe of dates by a particular month/day? - Stack Overflow python - replace a value in the entire pandas data frame - Stack Overflow python - Replacing blank values (white space) with NaN in pandas - Stack Overflow python - get list from pandas dataframe column - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to lowercase a pandas dataframe string column if it has missing values? - Stack Overflow How to Convert Integers to Strings in Pandas DataFrame - Data to Fish How to Convert Integers to Strings in Pandas DataFrame - Data to Fish create a dictionary of two pandas Dataframe columns? - Stack Overflow python - ValueError: No axis named node2 for object type <class 'pandas.core.frame.DataFrame'> - Stack Overflow Python Pandas iterate over rows and access column names - Stack Overflow python - Creating dataframe from a dictionary where entries have different lengths - Stack Overflow python - Deleting DataFrame row in Pandas based on column value - Stack Overflow python - How to check if a column exists in Pandas - Stack Overflow python - Import pandas dataframe column as string not int - Stack Overflow python - What is the most efficient way to create a dictionary of two pandas Dataframe columns? - Stack Overflow Python Loop through Excel sheets, place into one df - Stack Overflow python - How do I get the row count of a Pandas DataFrame? - Stack Overflow python - How to save a new sheet in an existing excel file, using Pandas? - Stack Overflow Python Loop through Excel sheets, place into one df - Stack Overflow How do I select a subset of a DataFrame? — pandas 1.2.4 documentation python - Delete column from pandas DataFrame - Stack Overflow python - Convert list of dictionaries to a pandas DataFrame - Stack Overflow How to Add or Insert Row to Pandas DataFrame? - Python Examples python - Check if a value exists in pandas dataframe index - Stack Overflow python - Set value for particular cell in pandas DataFrame using index - Stack Overflow python - Pandas Dataframe How to cut off float decimal points without rounding? - Stack Overflow python - Pandas: Change day - Stack Overflow python - Clean way to convert quarterly periods to datetime in pandas - Stack Overflow Pandas - Number of Months Between Two Dates - Stack Overflow python - MonthEnd object result in <11 * MonthEnds> instead of number - Stack Overflow python - Extracting the first day of month of a datetime type column in pandas - Stack Overflow
MySQL MULTIPLES INNER JOIN How to Use EXISTS, UNIQUE, DISTINCT, and OVERLAPS in SQL Statements - dummies postgresql - SQL OVERLAPS PostgreSQL Joins: Inner, Outer, Left, Right, Natural with Examples PostgreSQL Joins: A Visual Explanation of PostgreSQL Joins PL/pgSQL Variables ( Format Dates ) The Ultimate Guide to PostgreSQL Date By Examples Data Type Formatting Functions PostgreSQL - How to calculate difference between two timestamps? | TablePlus Date/Time Functions and Operators PostgreSQL - DATEDIFF - Datetime Difference in Seconds, Days, Months, Weeks etc - SQLines CASE Statements in PostgreSQL - DataCamp SQL Optimizations in PostgreSQL: IN vs EXISTS vs ANY/ALL vs JOIN PostgreSQL DESCRIBE TABLE Quick and best way to Compare Two Tables in SQL - DWgeek.com sql - Best way to select random rows PostgreSQL - Stack Overflow PostgreSQL: Documentation: 13: 70.1. Row Estimation Examples Faster PostgreSQL Counting How to Add a Default Value to a Column in PostgreSQL - PopSQL How to Add a Default Value to a Column in PostgreSQL - PopSQL SQL Subquery - Dofactory SQL IN - SQL NOT IN - JournalDev DROP FUNCTION (Transact-SQL) - SQL Server | Microsoft Docs SQL : Multiple Row and Column Subqueries - w3resource PostgreSQL: Documentation: 9.5: CREATE FUNCTION PostgreSQL CREATE FUNCTION By Practical Examples datetime - PHP Sort a multidimensional array by element containing date - Stack Overflow database - Oracle order NULL LAST by default - Stack Overflow PostgreSQL: Documentation: 9.5: Modifying Tables PostgreSQL: Documentation: 14: SELECT postgresql - sql ORDER BY multiple values in specific order? - Stack Overflow How do I get the current unix timestamp from PostgreSQL? - Database Administrators Stack Exchange SQL MAX() with HAVING, WHERE, IN - w3resource linux - Which version of PostgreSQL am I running? - Stack Overflow Copying Data Between Tables in a Postgres Database php - How to remove all numbers from string? - Stack Overflow
Clear config cache Eloquent DB::Table RAW Query / WhereNull Laravel Eloquent "IN" Query get single column value in laravel eloquent php - How to use CASE WHEN in Eloquent ORM? - Stack Overflow AND-OR-AND + brackets with Eloquent - Laravel Daily Database: Query Builder - Laravel - The PHP Framework For Web Artisans ( RAW ) Combine Foreach Loop and Eloquent to perform a search | Laravel.io Access Controller method from another controller in Laravel 5 How to Call a controller function in another Controller in Laravel 5 php - Create a Laravel Request object on the fly php - Laravel 5.6 Upgrade caused Logging to break Artisan Console - Laravel - The PHP Framework For Web Artisans What to include in gitignore for a Laravel and PHPStorm project php - Create a Laravel Request object on the fly Process big DB table with chunk() method - Laravel Daily How to insert big data on the laravel? - Stack Overflow php - How can I build a condition based query in Laravel? - Stack Overflow Laravel Chunk Eloquent Method Example - Tuts Make Database: Migrations - Laravel - The PHP Framework For Web Artisans php - Laravel Model Error Handling when Creating - Exception Laravel - Inner Join with Multiple Conditions Example using Query Builder - ItSolutionStuff.com laravel cache disable phpunit code example | Newbedev In PHP, how to check if a multidimensional array is empty? · Humblix php - Laravel firstOrNew how to check if it's first or new? - Stack Overflow get base url laravel 8 Code Example Using gmail smtp via Laravel: Connection could not be established with host smtp.gmail.com [Connection timed out #110] - Stack Overflow
PostgreSQL POSITION() function PostgresQL ANY / SOME Operator ( IN vs ANY ) PostgreSQL Substring - Extracting a substring from a String How to add an auto-incrementing primary key to an existing table, in PostgreSQL PostgreSQL STRING_TO_ARRAY()function mysql FIND_IN_SET equivalent to postgresql PL/pgSQL Variables ( Format Dates ) The Ultimate Guide to PostgreSQL Date By Examples Data Type Formatting Functions PostgreSQL - How to calculate difference between two timestamps? | TablePlus Date/Time Functions and Operators PostgreSQL - DATEDIFF - Datetime Difference in Seconds, Days, Months, Weeks etc - SQLines CASE Statements in PostgreSQL - DataCamp SQL Optimizations in PostgreSQL: IN vs EXISTS vs ANY/ALL vs JOIN PL/pgSQL Variables PostgreSQL: Documentation: 11: CREATE PROCEDURE Reading a Postgres EXPLAIN ANALYZE Query Plan Faster PostgreSQL Counting sql - Fast way to discover the row count of a table in PostgreSQL - Stack Overflow PostgreSQL: Documentation: 9.1: tablefunc PostgreSQL DESCRIBE TABLE Quick and best way to Compare Two Tables in SQL - DWgeek.com sql - Best way to select random rows PostgreSQL - Stack Overflow How to Add a Default Value to a Column in PostgreSQL - PopSQL How to Add a Default Value to a Column in PostgreSQL - PopSQL PL/pgSQL IF Statement PostgreSQL: Documentation: 9.1: Declarations SQL Subquery - Dofactory SQL IN - SQL NOT IN - JournalDev PostgreSQL - IF Statement - GeeksforGeeks How to work with control structures in PostgreSQL stored procedures: Using IF, CASE, and LOOP statements | EDB PL/pgSQL IF Statement How to combine multiple selects in one query - Databases - ( loop reference ) DROP FUNCTION (Transact-SQL) - SQL Server | Microsoft Docs SQL : Multiple Row and Column Subqueries - w3resource PostgreSQL: Documentation: 9.5: CREATE FUNCTION PostgreSQL CREATE FUNCTION By Practical Examples datetime - PHP Sort a multidimensional array by element containing date - Stack Overflow database - Oracle order NULL LAST by default - Stack Overflow PostgreSQL: Documentation: 9.5: Modifying Tables PostgreSQL: Documentation: 14: SELECT PostgreSQL Array: The ANY and Contains trick - Postgres OnLine Journal postgresql - sql ORDER BY multiple values in specific order? - Stack Overflow sql - How to aggregate two PostgreSQL columns to an array separated by brackets - Stack Overflow How do I get the current unix timestamp from PostgreSQL? - Database Administrators Stack Exchange SQL MAX() with HAVING, WHERE, IN - w3resource linux - Which version of PostgreSQL am I running? - Stack Overflow Postgres login: How to log into a Postgresql database | alvinalexander.com Copying Data Between Tables in a Postgres Database PostgreSQL CREATE FUNCTION By Practical Examples php - How to remove all numbers from string? - Stack Overflow