NetProfiler - Um solução para quem passeia por várias redes.

Publicado por Laudivan Freire de Almeida 06/11/2008

[ Hits: 5.036 ]

Download netprofiler




Esse script tem por objetivo facilitar a configuração para diferentes redes.

A motivação nasceu após levar meu notebook de uma rede para outra, alguma com wpa, com enlace de par trançado ou wifi. Então experimentei algumas soluções (como o laptop-net) até que resolvi fazer uma que se adequa-se às minhas necessicades.

Contudo, tenho certeza que vai ajudar muitas pessoas por aí na mesma situação.

  



Esconder código-fonte

#!/bin/sh
####################################################################
#   NetProfiler - script para configuração de ambiente de rede.    #
# ---------------------------------------------------------------- #
#      Por: Laudivan Freire de Almeida <laudivan@gmail.com>        #
#      Em: Seg Nov 3 12:14:41 BRT 2008                             #
# ---------------------------------------------------------------- #
#   Distribuído no VivaOLinux.com.br                               #
#   Toda cópia e modificação fica autorizada pelo autor, bem como  #
# sua modificação e uso para qualquer fim.                         #    
####################################################################
PROFILESDIR="/usr/local/etc/netprofiler"

PID="/var/run/netprofiler"

WPASUPPLICANTD="/sbin/wpa_supplicant"
WPAPASSPHRASE="/usr/bin/wpa_passphrase"

DHCLIENTD="/sbin/dhclient3"

IFCONFIG="/sbin/ifconfig"
ROUTE="/sbin/route"

SUDO="/usr/bin/sudo"
USESUDO="sim"

#Teste da pasta de configuração
if [ ! -e ${PROFILESDIR} ]; then
   mkdir ${PROFILESDIR}
fi 

######################################################################
#                          Excluir profile                           #
######################################################################
function excluir_profile(){
   uid_teste
   
   if [ -z ${EXCLUIRPROFILE} ]; then
      echo "Voce deve selecionar um profile."
      echo "Use: $(basename ${0}) -d PROFILE"
      exit 1
   fi
   
   if [ -e ${PID} ]; then
      source ${PID}
      
      if [ ${PROFILE} == "${EXCLUIRPROFILE}" ]; then
         echo "Este profile esta em uso. Pare o NetProfiler e tente novamente"
         exit 1
      fi
   fi
   
   if [ -e ${PROFILESDIR}/${EXCLUIRPROFILE} ]; then
      rm -fr ${PROFILESDIR}/${EXCLUIRPROFILE}
   fi
}

######################################################################
#                          Criar profile                             #
######################################################################
function criar_profile(){
   uid_teste

   if [ -z ${PROFILE} ]; then
      echo "Voce deve especificar um nome para o profile."
      echo "Use: $(basename ${0}) -c PROFILE"
      exit 1
   fi

   if [ -e ${PROFILESDIR}/${PROFILE} ]; then
      echo "Ja existe um profile chamado ${PROFILE}. "
      exit 1
   fi

   PROFILEDIR="${PROFILESDIR}/${PROFILE}"
   PROFILEDIRTMP="/tmp/${PROFILE}"
   PROFILETMP="${PROFILEDIRTMP}/profile.conf"

   echo "Qual interface sera usada para essa rede?" 
   read -e DEVICE
   #TODO:Fazer teste de existência da interface
   if [ -z ${DEVICE} ]; then
      echo "Voce deve digitar uma interface."
      exit 1
   fi
   
   mkdir ${PROFILEDIRTMP}
   echo "DEVICE=\"${DEVICE}\"" > ${PROFILETMP}
   
   echo "Pretende usar ip automatico para essa rede? (sim/nao)" 
   read -e USEDHCP
   echo >> ${PROFILETMP}
  
     case ${USEDHCP} in
      sim)
         echo "USEDHCP=\"${USEDHCP}\"" >> ${PROFILETMP}
         ;;
      nao)
         echo >> ${PROFILETMP}

         echo "Qual sera o ip? (ie 192.168.0.24)" 
         read -e ADDRESS
         echo "ADDRESS=\"${ADDRESS}\"" >> ${PROFILETMP}
         
         echo "Qual sera a mascara de rede? (ie 255.255.255.0)"
         read -e NETMASK
         echo "NETMASK=\"${NETMASK}\"" >> ${PROFILETMP}

         echo "Qual sera o gateway da rede? (ie 192.168.0.1)" 
         read -e GATEWAY
         echo "GATEWAY=\"${GATEWAY}\"" >> ${PROFILETMP}         
         ;;
      *)
         echo "Deve ser digitado sim ou nao"
         rm -fr ${PROFILEDIRTMP}
         exit 1
         ;;
   esac

   echo "Entre com o mac se pretende mudar, ou ENTER caso o contrário." 
   read -e HWADDRESS
   if [ -n "${HWADDRESS}" ]; then
      echo "HWADDRESS=\"${HWADDRESS}\"" >> ${PROFILETMP}
   fi

   echo "Entre com os servidores DNS(separados por espaco) ou ENTER para nenhum." 
   read -e NAMESERVERS
   if [ -n "${NAMESERVERS}" ]; then
      echo "NAMESERVERS=\"${NAMESERVERS}\"" >> ${PROFILETMP}
      echo >> ${PROFILETMP}
   fi

   echo "USAR WPA SUPPLICANT?(sim/nao)" 
   read -e USEWPASUPPLICANT
   
   echo >> ${PROFILETMP}
   WPACONFTMP="${PROFILEDIRTMP}/wpa.conf"
   
   case ${USEWPASUPPLICANT} in
      sim)
         echo "USEWPASUPPLICANT=\"sim\"" >> ${PROFILETMP}
         echo "Qual é o SSID da rede?" 
         read -e SSID
      
         echo "Selecione o tipo de criptografia que sera usada (none, wep, wpa-psk, wpa2-psk):" 
         read -e CRIPT
         case ${CRIPT} in
            wpa-psk)
               echo "Entre com a frase:" 
               read -e PHRASE
               
               echo -e "network={" > ${WPACONFTMP}
               echo -e "\tssid=\"${SSID}\"" >> ${WPACONFTMP}
               ${WPAPASSPHRASE} ${SSID} ${PHRASE} | grep psk | tail -n 1 >> ${WPACONFTMP}
               echo -e "\tscan_ssid=1"  >> ${WPACONFTMP}
                 echo -e "\tkey_mgmt=WPA-PSK"  >> ${WPACONFTMP}
                 echo -e "\tproto=WPA"  >> ${WPACONFTMP}
                 echo -e "\tpairwise=CCMP TKIP"  >> ${WPACONFTMP}
                 echo -e "\tgroup=CCMP TKIP"  >> ${WPACONFTMP}   
               echo -e "}" >> ${WPACONFTMP}
               ;;
            wpa2-psk)
               echo "Entre com a frase:" 
               read -e PHRASE
               
               echo -e "network={" > ${WPACONFTMP}
               echo -e "\tssid=\"${SSID}\"" >> ${WPACONFTMP}
               ${WPAPASSPHRASE} ${SSID} ${PHRASE} | grep psk | tail -n 1 >> ${WPACONFTMP}
               echo -e "\tscan_ssid=1"  >> ${WPACONFTMP}
                 echo -e "\tkey_mgmt=WPA-PSK"  >> ${WPACONFTMP}
                 echo -e "\tproto=WPA2"  >> ${WPACONFTMP}
                 echo -e "\tpairwise=CCMP TKIP"  >> ${WPACONFTMP}
                 echo -e "\tgroup=CCMP TKIP"  >> ${WPACONFTMP}               
               echo -e "}" >> ${WPACONFTMP}
               ;;
            wep)
               echo "Entre com a primeira chave: "
               read KEY0
               echo "Entre com a segunda chave:"
               read KEY1
            
               echo -e "network={" > ${WPACONFTMP}
               echo -e "\tssid=\"${SSID}\"" >> ${WPACONFTMP}
               echo -e "\tkey_mgmt=NONE" >> ${WPACONFTMP}
               echo -e "\twep_key0=${KEY0}"  >> ${WPACONFTMP}
               echo -e "\twep_key1=${KEY1}"  >> ${WPACONFTMP}
               echo "}" >> ${WPACONFTMP}
               ;;
            *)
               echo -e "network={" > ${WPACONFTMP}
               echo -e "\tssid=\"${SSID}\"" >> ${WPACONFTMP}
               echo -e "\tkey_mgmt=NONE" >> ${WPACONFTMP}
               echo -e "}" >> ${WPACONFTMP}
               ;;
         esac
         
         echo "Qual o driver wpa supplicant para essa interface."
         echo "(hostap, hermes, madwifi, atmel, wext, ndiswrapper, broadcom, ipw, wired, bsd, ndis)"
         read -e DRVWPA
         if [ -n "${WPASUPPLICANTDRV}" ]; then
            echo "WPASUPPLICANTDRV=\"${WPASUPPLICANTDRV}\""  >> ${PROFILETMP}
         else
            echo "WPASUPPLICANTDRV=\"wext\""  >> ${PROFILETMP}
         fi
         echo "Altere o arquivo ${PROFILEDIR}/wpa.conf para ajusta-lo."
         ;;
      *)
         echo "O WPA SUPPLICANT nao sera iniciado para essa rede."
         ;;
   esac

   mv ${PROFILEDIRTMP} ${PROFILEDIR}
  
   exit 0
}

######################################################################
#        Executa o teste de permissão do usuário, e se estiver   #
# configurado executa o programa com o sudo.                         #
######################################################################
function uid_teste() {
   if [ $UID -eq 0 ]; then
      return
   fi

   if [ ${USESUDO}="sim" ]; then
      echo " **Assumindo permissões de ROOT**"
      sudo ${0} -${OPT} ${OPTARG}
      
      exit 0
   fi

   echo " Você deve executar como root"
   exit 1
}

######################################################################
#    Para o netprofiler fechando os programas envolvidos             #
######################################################################
function parar_netprofiler() {
   uid_teste

   echo "Parando NetProfiler"

   if [ -e ${PID} ]; then
      source ${PID}

      if [ -n "${USEWPASUPPLICANT}" ]; then
         killall ${WPASUPPLICANTD}
      fi

      if [ -n "${USEDHCP}" ]; then
         killall ${DHCLIENTD}
      fi

      ${ROUTE} del default
      ${IFCONFIG} ${DEVICE} down

      rm -f ${PID}
   fi
}

######################################################################
#    Para o netprofiler fechando os programas envolvidos         #
######################################################################
function mostrar_status() {
   if [ -e ${PID} ]; then
      source ${PID}

      echo "STATUS: O NetProfiler esta OnLine"
      echo "   PROFILE:${PROFILE}"
      echo "   DEVICE=${DEVICE}"
      echo "   USEDHCP=${USEDHCP}"
      echo "   USEWPASUPPLICANT=${USEWPASUPPLICANT}"
      echo
   else
      echo "   O NetProfiler não está rodando."
   fi
}

######################################################################
#               Lista os profiles escolhidos                     #
######################################################################
function listar_profiles () {
   echo "Listando profiles em ${PROFILESDIR}:"

   for PROFILEDIR in ${PROFILESDIR}/*; do
      PROFILE="$(basename ${PROFILEDIR})"
      if [ -d $PROFILEDIR ] ; then
         echo "   ${PROFILE}"
      fi
   done

   exit 0
}

######################################################################
#   Configura a rede conforme o profile escolhido                    #
######################################################################
function usar_profile () {
   uid_teste

   parar_netprofiler

   if [ -z ${PROFILE} ]; then
      echo "Voce deve selecionar um profile."
      echo "Use: $(basename ${0}) -u PROFILE"
      exit 1
   fi

   echo "Iniciando profile:  $PROFILE"
   source $PROFILESDIR/$PROFILE/profile.conf

   echo "PROFILE=${PROFILE}" > ${PID}
   echo "DEVICE=${DEVICE}" >> ${PID}
   
   if [ -n "${HWADDRESS}" ]; then
      ${IFCONFIG} ${DEVICE} hw ether ${HWADDRESS} up
   else
      ${IFCONFIG} ${DEVICE} up
   fi

   if [ -n "${USEWPASUPPLICANT}" ]; then
      echo "USEWPASUPPLICANT=${USEWPASUPPLICANT}" >> ${PID}
      ${WPASUPPLICANTD} -P /var/run/wpasupplicant -B -i ${DEVICE} -c ${PROFILESDIR}/${PROFILE}/wpa.conf -d -D ${WPASUPPLICANTDRV}
   fi

   if [ -n "${USEDHCP}" ]; then
      echo "USEDHCP=${USEDHCP}" >> ${PID}
      $DHCLIENTD ${DEVICE}
   else
      ${IFCONFIG} ${DEVICE} ${ADDRESS} netmask ${NETMASK}
      
      ${ROUTE} add default gw ${GATEWAY}
   fi

   #Caso esteja setada a variável NAMESERVERS modificar resolv.conf mesmo com dhcp
   if [ -n "${NAMESERVERS}" ]; then
      echo "#resolv.conf modificado pelo netprofiler" > /etc/resolv.conf
   
      for NAMESERVER in ${NAMESERVERS}; do
         echo "nameserver ${NAMESERVER}" >> /etc/resolv.conf
      done      
   fi
  
  exit 0
}

######################################################################
#                 Exibe a ajuda do sistema.                      #
######################################################################
function mostrar_ajuda () {
   echo "Utilize: "
   echo "   Usar um profile    : $(basename ${0}) -u PROFILE"
   echo "   Listar os profiles : $(basename ${0}) -l"
   echo "   Parar o NetProfiler: $(basename ${0}) -p"
   echo "   Mostrar status     : $(basename ${0}) -s"
   echo "   Criar um Profile   : $(basename ${0}) -c PROFILE"
   echo "   Apagar um Profile  : $(basename ${0}) -d PROFILE"
   echo "   Mostrar a ajuda    : $(basename ${0}) -h"
   echo

   exit 0
}

# Obtendo as opções de linha de comando.
getopts "u:lSsc:d:ph" OPT

case $OPT in 
   u)
      PROFILE=${OPTARG}
      usar_profile
      ;;
   l)
        listar_profiles
        ;;
     p)
        parar_netprofiler
        ;;
     s)
        mostrar_status
        ;;
     h)
        mostrar_ajuda
        ;;
     c)
        PROFILE=${OPTARG}
        criar_profile
        ;;
     d)
        EXCLUIRPROFILE=${OPTARG}
        excluir_profile
        ;;
     *)
        mostrar_ajuda
        exit 1
        ;; 
esac

exit 0

Scripts recomendados

apt-fast melhorado e empacotado

Mostrar IP da Internet

Configuração do Modem Sony Ericsson MD300 da Claro 3G no Linux

Papel de parede - Mudança automática no Ubuntu/Debian

burncd - programa para gravar ISOs


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts