22 jul

PowerCLI + PHP + CentOS

<!--?php
//run http://127.0.0.1/vmware_power.php?install=y to install and configure powercli to apache user
if(array_key_exists ( "install" ,$_GET ) && $_GET["install"]=="y")
{
	$PowerCliCommand='export HOME=/tmp/ && pwsh -c "& {Set-PowerCLIConfiguration -Scope User -ParticipateInCEIP \$false -Confirm:\$false; Import-Module \"VMware.VimAutomation.Core\"; Set-PowerCLIConfiguration -InvalidCertificateAction "Ignore" -Confirm:\$false; Set-PowerCLIConfiguration -DefaultVIServerMode multiple -Confirm:\$false}"';
	exec($PowerCliCommand, $Output, $ErrorReturned);
	echo(implode ( '<br-->' , $Output ));
}
else
{
	$vSphereIP = '192.168.1.200';
	$user = "myuser";
	$password = "mypassword";
 
	//$powercli_query = 'Get-VM | Select @{N=\'Name\';E={\$_.Name}},  @{N=\'UUID\';E={\$_.Config.Uuid}}   ';
	$powercli_query = 'Get-vm "XPTO-VM-MYMV" | %{\$m=\$_; \$v=Get-View \$_; \$h=Get-HardDisk \$_; \$t=Get-TagAssignment \$_; [pscustomobject] @{name=\$m.name;HostName=\$v.Guest.HostName;   Uuid=\$v.Config.Uuid; VMid=\$v.MoRef.Value;GuestId=\$v.Config.GuestId;CreateDate=\$v.Config.CreateDate;MemoryGB=\$h.Parent.MemoryGB;Numcpu=\$h.Parent.Numcpu;CapacityGB=\$h.CapacityGB;TagAssignment=(\$t | Select-object Tag -ExpandProperty Tag| select-object Category,Name,Id);Net=[pscustomobject] @{Network=\$v.Guest.Net.Network; MacAddress=\$v.Guest.Net.MacAddress; IpAddress=(\$v.Guest.Net.IpConfig.IpAddress | foreach-object {[pscustomobject] @{IpAddress=\$_.IpAddress;PrefixLength=\$_.PrefixLength }}); Connected=\$v.Guest.Net.Connected;}}}';
 
	$PowerCliCommand='export HOME=/tmp/ &amp;&amp; pwsh -c "&amp; {Import-Module VMware.VimAutomation.Core; \$teste=Connect-VIServer -Server (\"$vSphereIP\", \"$vSphereIP\") -User '.$user.' -Password \"'.$password.'\"; '.$powercli_query.'| ConvertTo-Json  -Depth 4} "';
	exec($PowerCliCommand, $Output, $ErrorReturned);
 
	header('Content-Type: application/json');
	echo(implode ( ' ' , $Output ));
}
?&gt;
20 jul

HyperV PowerShell Rest Service

ipmo 'virtualmachinemanager\virtualmachinemanager.psd1'
 
# Create a listener on port 8000
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add('http://+:8080/') 
$listener.Start()
Get-VMMServer vmm.redemapa.agro
'Listening ...'
 
# Run until you send a GET request to /end
while ($true) {
    $context = $listener.GetContext() 
    # Capture the details about the request
    $request = $context.Request
    # Setup a place to deliver a response
    $response = $context.Response
    # Break from loop if GET request sent to /end
    if ($request.Url -match '/end') { 
        break 
    } else {
        # Split request URL to get command and options
        $requestvars = ([String]$request.Url).split("/");        
        switch($requestvars[3])
        {
            "propriedadesCustomizadasGeral" 
            {
                # Get the class name and server name from the URL and run get-WMIObject
                $result = &amp; {
                    foreach ($propriedade in $(Get-SCCustomProperty | Where-Object -Property Name -notlike "Custom*"  | Where-Object -Property Name -ne "SupportedVmGenerationForVmRole"))
                    {
                        foreach ($objeto in $(Get-VM))
                        {
                            $temp = Get-SCCustomPropertyValue -InputObject $objeto -CustomProperty $propriedade;
                            If ($temp.Name -ne $null)
                            {
                                [pscustomobject] @{
                                    Property = $temp.Name
                                    Value = $temp.Value
                                }
                            }
                        }
                    }
                }
                # Convert the returned data to JSON and set the HTTP content type to JSON
                $message = $result | ConvertTo-Json; 
                $response.ContentType = 'application/json';
            }
            "propriedadesCustomizadasVM"
            {
                $result =  &amp;{foreach ($propriedade in $(Get-SCCustomProperty | Where-Object -Property Name -notlike "Custom*"  | Where-Object -Property Name -ne "SupportedVmGenerationForVmRole"))
                {
                    $temp = Get-SCCustomPropertyValue -InputObject (Get-VM $requestvars[4])[0] -CustomProperty $propriedade;
                    If ($temp.Name -ne $null)
                    {
                        [pscustomobject] @{
                            Property = $temp.Name
                            Value = $temp.Value
                        }
                    }
                 } }
                 $message = $result | ConvertTo-Json; 
                 $response.ContentType = 'application/json';
            }
            "VM"
            {
                $result =  &amp;{get-vm $requestvars[4]}
                $message = $result | ConvertTo-Json; 
                $response.ContentType = 'application/json';
            }
            "VMs"
            {
                $result =  &amp;{get-vm | select-object name,BiosGuid, vmid ,hostname, ComputerName,StatusString, @{Name="IPv4Addresses"; Expression={ $_.VirtualNetworkAdapters.IPv4Addresses}}}
                $message = $result | ConvertTo-Json; 
                $response.ContentType = 'application/json';
            }
            default
            {
                # If no matching subdirectory/route is found generate a 404 message
                $message = "This is not the page you're looking for.";
                $response.ContentType = 'text/html' ;
            }
        }
       # Convert the data to UTF8 bytes
       [byte[]]$buffer = [System.Text.Encoding]::UTF8.GetBytes($message)
 
       # Set length of response
       $response.ContentLength64 = $buffer.length
 
       # Write response out and close
       $output = $response.OutputStream
       $output.Write($buffer, 0, $buffer.length)
       $output.Close()
   }    
}
 
#Terminate the listener
$listener.Stop()
09 ago

Fedora 17 – Eclipse with fragmented plugin

#!/bin/bash
echo "" > reinstall_libs.txt
for arquivo in `find /usr/share/java -type f`
do
   echo $arquivo
   repoquery -f  --qf="%{name}" $arquivo >> reinstall_libs.txt
done
comando="yum reinstall -y "`sort reinstall_libs.txt | uniq -u | tr "\\n" " "`
echo ""
echo ""
echo $comando
18 out

Ruby – Backup automático (phpMyAdmin)

#!/usr/bin/ruby
#phpMyAdmin 2.11.4
 
require 'rubygems'
require 'mechanize'
 
agent = Mechanize.new
agent.user_agent_alias = 'Mac Safari'
page = agent.get('http://meuservidor/')
 
form = page.forms[1]
form['pma_username'] = "usuario"
form['pma_password'] = "senha"
 
agent.submit(form)
 
page2 = agent.get('http://meuservidor/server_export.php')
 
dump_form = page2.form('dump')
 
 
dump_form.checkboxes_with(:name => 'asfile')[0].check
dump_form.radiobuttons_with(:name => 'compression')[1].check
 
page3 = agent.submit(dump_form, dump_form.buttons.first)
 
d1=Date.today.to_s
filename= "#{d1}-meu_banco.sql.zip"
 
page3.save_as(filename)

Referências:

15 out

Ruby – WebCrawler / webbot / Spider

#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'nokogiri'
require 'open-uri'
require 'rubygems'
 
ano = ARGV[0]
de_dia = ARGV[1]
de_mes = ARGV[2]
ate_dia = ARGV[3]
ate_mes = ARGV[4]
nome = ((ARGV[5]).to_s).gsub(' ','+')
 
http = Net::HTTP.new('www.in.gov.br')
path = '/imprensa/pesquisa/pesquisa_resultado.jsp'
 
resp, data = http.get(path, nil)
cookie = resp.response['set-cookie']
 
data = 'texto_todas=%22'+nome+'%22&rbfonetica=0&idJornal=1&idJornal=2&idJornal=3&idJornal=5&dataPublicacaoInicial='+de_dia+'%2F'+de_mes+'&dataPublicacaoFinal='+ate_dia+'%2F'+ate_mes+'&ano='+ano
 
headers = {
  'Cookie' => cookie,
  'Referer' => 'http://www.in.gov.br/imprensa/pesquisa/pesquisa_resultado.jsp',
  'Content-Type' => 'application/x-www-form-urlencoded'
}
resp, data = http.post(path, data, headers)
doc = Nokogiri::HTML(data)
doc.xpath('//div/table[@id="ResultadoConsulta"]/tbody/tr/td/table[@bordercolor="#FFFFFF"]/tr/td[1]/span<pre lang="c">/div/a').each do |link|
puts ARGV[5]+","+ link['onclick'].gsub("redirecionaSelect('","").gsub("');","")
end

Use assim:

ruby DOU.rb 2011 15 10 15 10 "SEU NOME COMPLETO"

Referências:

17 ago

JavaScript – Argumento Inválido na função window.open() no Internet Explorer

JavaScript Error: Argumento inválido.

Evite utilizar espaço no segundo argumento da função windows.open() do JavaScript

ex:
<a href=”javascript:;” onclick=”window.open(‘http://www.thiagosiqueira.com.br’,’NÃO_USE_ESPAÇO_AQUI‘,
‘toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=0, resizeable=0, width=800, height=600’)” >Clique ai!</a>

Referências: