domingo, 25 de março de 2018

Como Alterar o uuid do disco da VirtualBox para que ele seja utilizado novamente


Depois de criar uma máquina virtual no VirtualBox queremos copiar o HD de mentira e subir outra máquina, ou seja, queremos clonar uma máquina.
Simplesmente copiamos o *.vdi e tentamos configurar uma nova máquina usando a imagem copiada e nos deparamos com um erro de UUID.
Para resolver isso basta alterar o UUID com o comando abaixo:
VBoxManage internalcommands setvdiuuid [nome do disco virtual]
Exemplo:
VBoxManage internalcommands setvdiuuid meu_hd_virtual.vdi
Nas na versão 4.3 ou superior mudou para:
VBoxManage internalcommands sethduuid “endereco_mais_nome_do_hd.vid

terça-feira, 20 de março de 2018

How to install Tomcat 8.5 on Debian 9 / Ubuntu 16.04 / Linux Mint 18

Requirement

First, switch to the root user.
su -
OR
sudo su -
Tomcat requires Java JDK to be installed on the machine. You can either install Oracle JDK or OpenJDK.
For this demo, I am going with OpenJDK.
apt-get -y install openjdk-8-jdk
Once Java is installed, you can verify the Java version by using the following command.
java -version
Output:
openjdk version "1.8.0_141"
OpenJDK Runtime Environment (build 1.8.0_141-8u141-b15-1~deb9u1-b15)
OpenJDK 64-Bit Server VM (build 25.141-b15, mixed mode

For best practice, Tomcat should never be run as privileged user (root). So, create a low-privilege user for running the Tomcat service.
groupadd tomcat
mkdir /opt/tomcat
useradd -g tomcat -d /opt/tomcat -s /bin/nologin tomcat
or
useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat

Download & Configure Apache Tomcat

You can download the latest version of the Apache Tomcat from the official website.
wget http://www-us.apache.org/dist/tomcat/tomcat-8/v8.5.27/bin/apache-tomcat-8.5.27.tar.gz
Extract the tomcat on to your desired (/opt/tomcat) directory.
tar -zxvf apache-tomcat-*.tar.gz
mv apache-tomcat-8.5.27/* /opt/tomcat/
Change the ownership of the extracted directory so that tomcat user can write files to it.
chown -R tomcat:tomcat /opt/tomcat/

chmod +x /opt/tomcat/bin/*.sh 

Change the add in /etc/bash.bashrc  and /etc/profile  and /etc/environment
# Variaveis Java
JAVA_HOME=/usr/lib/jvm/java-8-oracle
CATALINA_HOME=/opt/tomcat
export JAVA_HOME
JRE_HOME=$JAVA_HOME/jre
export JRE_HOME
#PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin:
#export PATH
export CATALINA_HOME


Controlling Apache Tomcat

Manual

You can start and stop the Tomcat using the script which comes along with the package.
To start Tomcat service, go to the Tomcat directory and run:
cd /opt/tomcat/bin/
sh startup.sh
Output:
Using CATALINA_BASE:   /opt/tomcat
Using CATALINA_HOME:   /opt/tomcat
Using CATALINA_TMPDIR: /opt/tomcat/temp
Using JRE_HOME:        /usr
Using CLASSPATH:       /opt/tomcat/bin/bootstrap.jar:/opt/tomcat/bin/tomcat-juli.jar
Tomcat started.
To stop Tomcat service, run:
sh shutdown.sh

Change the ownership of the extracted directory so that tomcat user can write files to it.


chown -R tomcat:tomcat /opt/tomcat/

Systemd

We can also configure systemd to start the Tomcat service. Skip the below step in case you do not want to use systemd for managing Tomcat service.
Create a tomcat systemd service file. Green ones depend on the environmentso change them accordingly.
nano /etc/systemd/system/tomcat.service
Add the below information to Tomcat systemd service file.
[Unit]
Description=Apache Tomcat 8.x Web Application Container
Wants=network.target
After=network.target

[Service]
Type=forking

Environment=JRE_HOME=/usr/lib/jvm/java-8-oracle/jre
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1G -Djava.net.preferIPv4Stack=true'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/opt/tomcat/bin/shutdown.sh
SuccessExitStatus=143

User=tomcat
Group=tomcat
UMask=0007
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target
Reload systemd daemon.
systemctl daemon-reload
To start the Tomcat service; run:
systemctl start tomcat
Check the status of Tomcat, run:
systemctl status tomcat
Enable the auto start of Tomcat service on system boot:
systemctl enable tomcat

Verify Apache Tomcat
By default, Tomcat runs on port 8080. Use can use the netstat command to check the port status.
netstat -antup | grep 8080
or
netstat -plntu | grep 8080
Output:
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      12224/java


Firewall

You may need to allow Tomcat server requests in the firewall so that we can access the application from the external network.
ufw allow 8080

Configure Apache Tomcat Web UI

Tomcat comes with the web-manager and Host Manager for managing Tomcat. Both Host Manager and Web Manager are password protected, and it requires a username and password to access.
Only the user with the manager-gui and admin-gui role is allowed to access web manager and host-manager respectively. Those two roles are defined in tomcat-users.xml file.
nano /opt/tomcat/conf/tomcat-users.xml
Place the following two lines (role and user definition) just above the last line.
manager-gui,admin-gui"/>
tomcat" password="admin" roles="manager-gui,admin-gui"/>

For security reason, Web Manager and Host Manager is accessible only from the localhost, ie, from the server itself.
If you want to access managers from the remote system then you need to add your source network in allow list. To do that, edit the below two files.
nano /opt/tomcat/webapps/manager/META-INF/context.xml

nano /opt/tomcat/webapps/host-manager/META-INF/context.xml
Update the below line on both files with source IP from which your accessing the Web and Host Manager. .* will allow everyone to have access to managers.
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|.*" />
OR
You can allow only part of your network. For example, to allow only 192.168.0.0/24 network, you can use the below values.
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|192.168.*" />
Restart the Tomcat service.
systemctl restart tomcat


netstat Command not found on Debian 9 / Ubuntu / Linux Mint – Quick Fix


netstat is a command line tool to view the network connection statistics to/from the machine. With netstat, you can see network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
Are you facing netstat command not found issue after the installation Debian 9 / Ubuntu / Linux Mint.
-bash: netstat: command not found
Here is the small guide to install the necessary package for getting netstat command. Let us see which package provides us netstat command.
apt-file search --regexp '/netstat$'
Output:
net-tools: /bin/netstat
From the above command, you can see that net-tools package provides you netstat command. So, install the net-toolspackage using the apt-get command.
apt-get install -y net-tools
Output:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
 net-tools
0 upgraded, 1 newly installed, 0 to remove and 98 not upgraded.
Need to get 248 kB of archives.
After this operation, 963 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian stretch/main amd64 net-tools amd64 1.60+git20161116.90da8a0-1 [248 kB]
Fetched 248 kB in 0s (422 kB/s)
Selecting previously unselected package net-tools.
(Reading database ... 131147 files and directories currently installed.)
Preparing to unpack .../net-tools_1.60+git20161116.90da8a0-1_amd64.deb ...
Unpacking net-tools (1.60+git20161116.90da8a0-1) ...
Processing triggers for man-db (2.7.6.1-2) ...
Setting up net-tools (1.60+git20161116.90da8a0-1) ...
Once the installation is complete. Run netstat to see whether it is available or not.
netstat
Output:
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 mydebian:ssh            192.168.1.5:55051       ESTABLISHED
tcp        0      0 mydebian:ssh            192.168.1.6:55368       ESTABLISHED
tcp        0     64 mydebian:ssh            192.168.1.6:55660       ESTABLISHED
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ]         DGRAM                    16007    /run/user/119/systemd/notify
unix  2      [ ]         DGRAM                    9360     /run/systemd/journal/syslog
unix  2      [ ]         DGRAM                    17319    /run/user/1000/systemd/notify
unix  3      [ ]         DGRAM                    9176     /run/systemd/notify
unix  2      [ ]         DGRAM                    9178     /run/systemd/cgroups-agent
unix  28     [ ]         DGRAM                    9190     /run/systemd/journal/dev-log
unix  8      [ ]         DGRAM                    9208     /run/systemd/journal/socket
unix  3      [ ]         STREAM     CONNECTED     23927    /run/user/1000/bus
unix  3      [ ]         STREAM     CONNECTED     22423    /run/systemd/journal/stdout
unix  3      [ ]         STREAM     CONNECTED     26620    /run/user/1000/bus
unix  3      [ ]         STREAM     CONNECTED     25601
unix  3      [ ]         STREAM     CONNECTED     23390    /run/systemd/journal/stdout
unix  3      [ ]         STREAM     CONNECTED     23284    /run/user/1000/bus
unix  3      [ ]         STREAM     CONNECTED     23270
unix  3      [ ]         STREAM     CONNECTED     23043
unix  3      [ ]         STREAM     CONNECTED     24356    /var/run/dbus/system_bus_socket
unix  3      [ ]         STREAM     CONNECTED     131096   /var/run/dbus/system_bus_socket
unix  3      [ ]         STREAM     CONNECTED     23046    /run/user/1000/bus
netstat Command not found on Debian - netstat command output
netstat Command not found on Debian – netstat command output
That’s All. You now have netstat command on your machine.

How to Install Java 8 on Debian GNU/Linux 9 (Stretch)





In this article, I will go through the process of installation of Java 8 on Debian 9 Stretch. Java comes in two flavors and we install both. OpenJDK is open source version that is compatible with most software.  And Oracle JavaSE is the proprietary version that should be used if your java application is incompatible with OpenJDK. There is also a neat mechanism for switching default Java in case you have both of them installed. In one of our earlier article we have explained java installation on rpm based system and this time we will have on Debian.

Installing OpenJDK

We will start from installing the OpenJDK. There are two packages that we can install, a JRE and JDK. Those familiar with Java already know what this means, but for other lets mention what it means.  JRE means Java Runtime Environment and JDK means Java Development Kit. So the first one is used if you are going only to start Java program, while JDK packs a javac compiler. Meaning if you are developer, you need JDK, otherwise JRE is ok.
To install JRE use this command after getting root access with su:
apt-get install default-jre
Depending on what kind of Debian install you did (CD, DVD, USB drive), this might or might not be already installed. On the other hand, JDK is most probably not installed. To install it, type:
apt-get install default-jdk
And you are set to go.

Installing Oracle Java

To install Oracle java we can use Webupd repository that is made for Ubuntu, but it also works for Debian. To add repository you first need to add add-apt-repository command if it is not installed (and that depends upon install options you selected).
apt-get install software-properties-common dirmngr
After installing this, we can add repository
add-apt-repository "deb http://ppa.launchpad.net/webupd8team/java/ubuntu yakkety main"
Repository is still not ready to use, we need to add key, we will see what key is missing after we run update command
apt update
Next we add key:
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C2518248EEA14886
And now we can install Oracle Java 8
apt-get install oracle-java8-installer
This will start install process, it will download newest Java 8 from Oracle site and install it. You will also get prompted by ncurses environment to accept the Oracle EULA for Java.
After it is done, you can run following command to see which exact version you have installed
java -version
Should get output similar to this
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
If we need Java 9 (development version as of time of writing) or Java 7 or 6 (legacy versions), we can install those as well. We need to re-run above command, except we will change number 8 for 6, 7 or 9.

Managing which Java will be using by default

Of you installed Oracle Java 6, 7, 8 and 9, plus OpenJDK, then you have 5 java installations. If you are developing for the legacy environment, you would want to set your system to use only one Java version, and to do that you dont need to remove all other java versions. Instead, you need to use following command:
update-alternatives --config java
It will give you output similar to this
Here you only need to enter the number that is shown before Java entry that you want to use as default. The asterisk signifies which one is used currently. After you changed the java alternative, the java -version command should give you different output.
You could also select default java compiler with following command
update-alternatives --config javac
Any other tool like javaws can be also set simply by changing last word in this command to appropriate tool name.

Setting the Environment Variable

If you are using some Java Application server like JBoss or Tomcat, then you will need $JAVA_HOME variable set. To set it use above update-alternatives --config java command to see where java is installed.
Then edit following file in nano
nano /etc/environment
If you just installed Java, file is empty, so add some line like this
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"
That is if you want OpenJDK to be your $JAVA_HOME.
Save file and run source command to load new variable
source /etc/environment
Now check if it works
echo $JAVA_HOME
it should give you output like this to this
/usr/lib/jvm/java-8-openjdk-amd64
That means that environment variable has been successfully set.

Conclusion

We have successfully installed OpenJDK and Oracle Java SE and now have the environment set up so you can on top of it install some Java EE application servers like Red Hat JBoss, Oracle WebLogic, WildFly or Apache Tomcat. On top of that you can develop and deploy your application. Or you simply want to have plain Java SE desktop applications on your Debian 9 desktop. Either way,  now you can do it.
Autor: https://linoxide.com/debian/install-java-8-debian-gnulinux-9-stretch/ 

segunda-feira, 19 de março de 2018

Cor Color Bash Prompt Debian


Green Prompt for your user


Edit ”~/.bashrc” and change:
#force_color_prompt=yes
to:
force_color_prompt=yes
To change it for all new users make the same in ”/etc/skel/.bashrc”.

Red Prompt for root


Edit ”/root/.bashrc” and change ”force_color_prompt=yes” like for your user.
Now change the color to red. Search this line:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
and change it to:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
Note: For this change to take effect, you must log out then log in again.

Debian (older versions)

Green Prompt for your user

Open ”~/.bashrc” and append:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

Red Prompt for root

Edit ”/root/.bashrc” and append:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]$ '

Other colors

Color Code
Black 30
Red 31
Green 32
Brown 33
Blue 34
Purple 35
Cyan 36
Light Gray 37 

Here are the rest of the colour equivalences:

Black       0;30     Dark Gray     1;30
Blue        0;34     Light Blue    1;34
Green       0;32     Light Green   1;32
Cyan        0;36     Light Cyan    1;36
Red         0;31     Light Red     1;31
Purple      0;35     Light Purple  1;35
Brown       0;33     Yellow        1;33
Light Gray  0;37     White         1;37

sexta-feira, 2 de março de 2018

Script PHP para forçar download de arquivos TXT e OPVN


Os navegadores de internet atualmente estão cheios de recursos, sçao capases de executar arquivos em diversos formatos como imagens, vídeos, músicas arquivos de texto como PDF, e diversos outros arquivos, porém ocorre que por necessidade do desenvolvedor e para facilitar a vida do usuário as veses precisamos que o arquivo seja baixado para o computador do usuário e não aberto no navagador, pois muitos usuários não saberam salvar um arquivo aberto no navegador, abaixo apresentarei um método de resolver esse problema.

Em um arquivo download.php coloque o seguinte conteúdo:

   $arquivo = $_GET["arquivo"];
   if(isset($arquivo) && file_exists($arquivo)){ //testa se o arquivo e a variavel não esta vazia e se o arquivo realmente existe
      switch(strtolower(substr(strrchr(basename($arquivo),"."),1))){ // verifica a extensão do arquivo para pegar o tipo
         case "pdf": $tipo="application/pdf"; break;
         case "exe": $tipo="application/octet-stream"; break;
         case "zip": $tipo="application/zip"; break;
         case "doc": $tipo="application/msword"; break;
         case "xls": $tipo="application/vnd.ms-excel"; break;
         case "ppt": $tipo="application/vnd.ms-powerpoint"; break;
         case "gif": $tipo="image/gif"; break;
         case "png": $tipo="image/png"; break;
         case "jpg": $tipo="image/jpg"; break;
         case "mp3": $tipo="audio/mpeg"; break;
         case "txt": $tipo="text/plain"; break;
         case "ovpn": $tipo="text/plain"; break;                  case "php": // deixar vazio por seurança
         case "htm": // deixar vazio por seurança
         case "html": // deixar vazio por seurança
      }
      header("Content-Type: ".$tipo); // informa o tipo do arquivo ao navegador
      header("Content-Length: ".filesize($arquivo)); // informa o tamanho do arquivo ao navegador
      header("Content-Disposition: attachment; filename=".basename($arquivo)); // informa ao navegador que é tipo anexo e faz abrir a janela de download, tambem informa o nome do arquivo
      readfile($arquivo); // lê o arquivo
      exit; // aborta pós-ações
   }
?>
Como é possível ver acima um case ficar resposável por definir o tipo do arquivo à partir da extensão, caso você queira adicionar mais tipos, é só adicionar mais um case com a extensão e o tipo do arquivo.
Depois faça um arquivo com o nome index.html e coloque nele o seguinte conteúdo.



Baixar Arquivo

No código acima passamos como um parâmetro via GET o diretório do arquivo que se deseja baixar.
Como foi dito se você quiser adicionar mais algum case segue abaixo uma lista te extensões e tipos que são chamados de Mime types.

ai     application/postscript
aif     audio/x-aiff
aifc     audio/x-aiff
aiff     audio/x-aiff
asc     text/plain
atom     application/atom+xml
au     audio/basic
avi     video/x-msvideo
bcpio     application/x-bcpio
bin     application/octet-stream
bmp     image/bmp
cdf     application/x-netcdf
cgm     image/cgm
class     application/octet-stream
cpio     application/x-cpio
cpt     application/mac-compactpro
csh     application/x-csh
css     text/css
dcr     application/x-director
dif     video/x-dv
dir     application/x-director
djv     image/vnd.djvu
djvu     image/vnd.djvu
dll     application/octet-stream
dmg     application/octet-stream
dms     application/octet-stream
doc     application/msword
dtd     application/xml-dtd
dv     video/x-dv
dvi     application/x-dvi
dxr     application/x-director
eps     application/postscript
etx     text/x-setext
exe     application/octet-stream
ez     application/andrew-inset
gif     image/gif
gram     application/srgs
grxml     application/srgs+xml
gtar     application/x-gtar
hdf     application/x-hdf
hqx     application/mac-binhex40
htm     text/html
html     text/html
ice     x-conference/x-cooltalk
ico     image/x-icon
ics     text/calendar
ief     image/ief
ifb     text/calendar
iges     model/iges
igs     model/iges
jnlp     application/x-java-jnlp-file
jp2     image/jp2
jpe     image/jpeg
jpeg     image/jpeg
jpg     image/jpeg
js     application/x-javascript
kar     audio/midi
latex     application/x-latex
lha     application/octet-stream
lzh     application/octet-stream
m3u     audio/x-mpegurl
m4a     audio/mp4a-latm
m4b     audio/mp4a-latm
m4p     audio/mp4a-latm
m4u     video/vnd.mpegurl
m4v     video/x-m4v
mac     image/x-macpaint
man     application/x-troff-man
mathml     application/mathml+xml
me     application/x-troff-me
mesh     model/mesh
mid     audio/midi
midi     audio/midi
mif     application/vnd.mif
mov     video/quicktime
movie     video/x-sgi-movie
mp2     audio/mpeg
mp3     audio/mpeg
mp4     video/mp4
mpe     video/mpeg
mpeg     video/mpeg
mpg     video/mpeg
mpga     audio/mpeg
ms     application/x-troff-ms
msh     model/mesh
mxu     video/vnd.mpegurl
nc     application/x-netcdf
oda     application/oda
ogg     application/ogg
pbm     image/x-portable-bitmap
pct     image/pict
pdb     chemical/x-pdb
pdf     application/pdf
pgm     image/x-portable-graymap
pgn     application/x-chess-pgn
pic     image/pict
pict     image/pict
png     image/png
pnm     image/x-portable-anymap
pnt     image/x-macpaint
pntg     image/x-macpaint
ppm     image/x-portable-pixmap
ppt     application/vnd.ms-powerpoint
ps     application/postscript
qt     video/quicktime
qti     image/x-quicktime
qtif     image/x-quicktime
ra     audio/x-pn-realaudio
ram     audio/x-pn-realaudio
ras     image/x-cmu-raster
rdf     application/rdf+xml
rgb     image/x-rgb
rm     application/vnd.rn-realmedia
roff     application/x-troff
rtf     text/rtf
rtx     text/richtext
sgm     text/sgml
sgml     text/sgml
sh     application/x-sh
shar     application/x-shar
silo     model/mesh
sit     application/x-stuffit
skd     application/x-koan
skm     application/x-koan
skp     application/x-koan
skt     application/x-koan
smi     application/smil
smil     application/smil
snd     audio/basic
so     application/octet-stream
spl     application/x-futuresplash
src     application/x-wais-source
sv4cpio     application/x-sv4cpio
sv4crc     application/x-sv4crc
svg     image/svg+xml
swf     application/x-shockwave-flash
t     application/x-troff
tar     application/x-tar
tcl     application/x-tcl
tex     application/x-tex
texi     application/x-texinfo
texinfo     application/x-texinfo
tif     image/tiff
tiff     image/tiff
tr     application/x-troff
tsv     text/tab-separated-values
txt     text/plain
ustar     application/x-ustar
vcd     application/x-cdlink
vrml     model/vrml
vxml     application/voicexml+xml
wav     audio/x-wav
wbmp     image/vnd.wap.wbmp
wbmxl     application/vnd.wap.wbxml
wml     text/vnd.wap.wml
wmlc     application/vnd.wap.wmlc
wmls     text/vnd.wap.wmlscript
wmlsc     application/vnd.wap.wmlscriptc
wrl     model/vrml
xbm     image/x-xbitmap
xht     application/xhtml+xml
xhtml     application/xhtml+xml
xls     application/vnd.ms-excel
xml     application/xml
xpm     image/x-xpixmap
xsl     application/xml
xslt     application/xslt+xml
xul     application/vnd.mozilla.xul+xml
xwd     image/x-xwindowdump
xyz     chemical/x-xyz
zip     application/zip