connect to online exchange

Lots of places explaining how to do this but in summary

you may have to change your execution policy settings ( Set-ExecutionPolicy bypass )

also remember if you have MFA enabled you will need to make an app password or use conditional MFA

# connect to exchange server online 
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -allowRedirection
Import-PSSession $Session

To save your password as a secure string

$credential = Get-Credential
$credential.Password | ConvertFrom-SecureString | Set-Content saved_encrypted_password1.txt

To read the password back and use it


$username="user@domain.com"
$secureStringPwd = get-Content saved_encrypted_password_1.txt  | ConvertTo-SecureString

Posted in Powershell, VBS, VBA and other scripting. | Comments Off on connect to online exchange

creating log files with date and time in their names.

Often want to create a log file from a cmd batch script which is unique for each day

for /F "tokens=1-6 delims=/ "  %%A in ('date /t') do ( set dt=%%D_%%C_%%B_)
for /F "tokens=1-6 delims=: "  %%A in ('time /t') do ( set tt=%%A_%%B_%%C)

set logfile="x:\LogFiles\%dt%_%tt%_nanotera.log"
echo %logfile%

@date /t  >> %logfile%
@time /t  >> %logfile%
@echo %0  >> %logfile%
@echo Backup Data folder. >> %logfile%
@echo ------------------- >> %logfile%
Posted in Powershell, VBS, VBA and other scripting. | Tagged | Comments Off on creating log files with date and time in their names.

Robocopy Scripts with logging.

Always struggle to remember this so put it here:

Point is to create logfile with todays date in the name so we get a new file each day


echo on
for /F "tokens=1-6 delims=/ " %%A in ('date /t') do ( set dt=%%D_%%C_%%B_)
set logfile=C:\it\logfiles\%dt%_copy_logfile.txt

echo %logfile%
date /t >> %logfile%
time /t >> %logfile%
echo %0 >> %logfile%
echo "************ Copy these files ************* >> %logfile%
robocopy \\server\files\applications\ "D:\Applications\" /s /r:0 /tee /log+:%logfile% /np /ndl /xo /purge

Posted in Hints and Tips, System Administration | Comments Off on Robocopy Scripts with logging.

Azure VMs to improve performance between sites.

Had a problem where the network access from a site in Africa to an Australian (Azure) based web site was very slow.

Instead created IPSEC links to a virtual Fortigate appliance in azure which was in a “close” geographic site (France Central), then used Microsoft premium peering between that Azure virtual network and one in Australia. Created an IPSEC link between the two Azure nets which meant we could use the web access from the Australian one from the African end of the chain.

This saved around 100ms in latency (with some other tweaks of the on site firewalls) and seems to have helped the performance of the web application.

Posted in System Administration | Tagged , , | Comments Off on Azure VMs to improve performance between sites.

VMWARE – esx standalone create new machines

Script to copy one VM and create new ones that are “similar”

<code>

newvm=PV009
cd /vmfs/volumes/p9-storage
mkdir $newvm
cd $newvm
cat ../PV004/PV004.vmx | sed "s/PV004/$newvm/g" | grep -v uuid > $newvm.vmx

vmkfstools -d thin -c 128g $newvm.vmdk


id=`vim-cmd solo/registervm   /vmfs/volumes/p9-storage/$newvm/$newvm.vmx`

vim-cmd vmsvc/power.on $id


</code>
Posted in Powershell, VBS, VBA and other scripting., System Administration | Comments Off on VMWARE – esx standalone create new machines

WordPress not allowing FILE links.

To allow you to use FILE:// Links in a wordpress menu you need to add the protocol to the wp_allowed_protocols function in wp_includes/functions.php

function wp_allowed_protocols() {
        static $protocols = array();

        if ( empty( $protocols ) ) {
                $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'file'  );

                /**
                 * Filters the list of protocols allowed in HTML attributes.
                 *
                 * @since 3.0.0
                 *
                 * @param array $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
                 */
                $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
        }

        return $protocols;
}
Posted in Hints and Tips, Powershell, VBS, VBA and other scripting. | Comments Off on WordPress not allowing FILE links.

Windows 10 and VPN connections.

Update coming but a lot of this has been fixed in windows 10 creator update

But the other issue where it tries to use the vpn username for all credentials after connecting isnt fixed.

no matter which vpn you choose to connect to from the task bar you have to choose it again from the windows 10 list of vpn connections.

I also find I have to pick another one and then repick the one I want to get the Connect or Disconnect options.

However this cmd file will log in and create the connection by just running it from a command prompt, it saves the username and password which could be a bit of a security issue.

rasdial "name_of_vpn Connection" username password

this one should disconnect it

rasdial "name_of_vpn Connection" /DISCONNECT
Posted in Hints and Tips, System Administration | Comments Off on Windows 10 and VPN connections.

Juniper log analysis – get host names from ip addresses.

import os
import re
from pprint import pprint
import socket
import M2Crypto
import ssl

ipsourcetable={}
iptargettable={}
ipsourcetargetcounttable={}
myfilename="192.168_logs_2017_05/192.168.96.43_log.txt"
myfilename="examine.log"
print myfilename
myipnames={'': ''}
for line in open(myfilename).readlines():
        parts=line.split(",")
        mytarget=parts[3]
        mytargetname=myipnames.get(mytarget,'notfound')
        mytargetcert='"",""'
        if mytargetname == 'notfound':
                print 'looking up ' + mytarget
                try:
                        mytargetname=socket.gethostbyaddr(mytarget)[0]
                        pprint(mytargetname)
                except socket.error, msg:
                        mytargetname=""
                # either found it or not - dont look again
                myipnames[mytarget]=mytargetname + "," + mytargetcert
                try:
                        cert = ssl.get_server_certificate((mytarget, 443))
                        x509 = M2Crypto.X509.load_cert_string(cert.encode('ascii','ignore'))
                        print x509.get_issuer()
                        print x509.get_subject()
                        mytargetcert='"'+ str(x509.get_issuer()) +'","'+ str(x509.get_subject()) + '"'
                        myipnames[mytarget]=mytargetname + "," + mytargetcert
                        mytargetname = myipnames[mytarget]
                except:
                        print 'couldnt get it'
                        #raise
                print 'added ' +'mytarget' + mytargetname
        else:
                print 'found ' + mytarget + ' ' + mytargetname
        #
        # make a line with comma seperators and quoted text
        mynewline=parts[0]+","+  parts[1]+ ","+ parts[2]+","+ mytargetname + ',' + parts[3]+","+  parts[5]+","+  parts[6]
        #pprint(mynewline)
        with open('withnames/'+parts[2]+'_with_name_log.txt', 'a') as the_file:
                the_file.write(mynewline)

myfile=open('myipaddresses.txt','w')
for f in myipnames.items():
        myfile.write( f[0] + ',' + f[1] + '\n' )
myfile.close()
Posted in Uncategorized | Comments Off on Juniper log analysis – get host names from ip addresses.

Python script to analyse Juniper firewall logs

Juniper firewalls create large syslog files showing all connections between internal/external hosts.

import os
import re
from pprint import pprint
import socket


# IP Addresses
rip=re.compile("([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/([0-9]+)[- ]")
#date time 2017-05-06 23:59:59\t
rdt=re.compile("^([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]) ([0-9][0-9]:[0-9][0-9]:[0-9][0-9])\t")
# description ?? JuniperSRX1500Perth RT_FLOW: RT_FLOW_SESSION_CLOSE: session closed response received N/A: 192.168."
rdesc=re.compile("(JuniperSRX1500Perth RT_.*[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/")
#rdesc=re.compile("(JuniperSRX1500Perth RT_.*): [0-9]+.")
ipsourcetable={}
iptargettable={}
ipsourcetargetcounttable={}
myfilename="/tmp/2017-05-29_SyslogCatchAll.txt"
myfilename="/tmp/2017-07-26_SyslogCatchAll.txt"
#myfilename="/tmp/test1.txt"
import os
#for myfilename in os.listdir('/mnt/pa_archives/pa_archives/IT/Syslog_Archives/') :
for myfilename in os.listdir('/tmp/2017_07_26_*.txt') :
        print myfilename
        if myfilename.startswith('2017-06'):
                myfilename='/mnt/pa_archives/pa_archives/IT/Syslog_Archives/'+myfilename
                for line in open(myfilename).readlines():
                    #parts=line.split(" ")
                    #pprint(line)
                    mydatetime=rdt.findall(line)
                    mydesc=rdesc.findall(line)
                    myips=(rip.findall(line))
                    #print len(mydesc)
                    #print len(myips)
                    if ( (len(mydesc) >= 1 ) and (len(myips) > 1 ) ) :
                        #pprint(myips[0][0])
                        #pprint(myips[1][0])
                        #pprint(myips[1][1])
                        mysource=myips[0][0]
                        mytarget=myips[1][0]
                        if mysource.startswith('192.168.'):
                                mytargetport=myips[1][1]
                                mytargetname=""
                                mynewline=(mydatetime[0][0]+ "," + mydatetime[0][1]+ "," + mysource + "," +  mytarget + "," + mytargetname + "," + mytargetport + ",\"" + mydesc[0] + "\""   )
                                #print mynewline
                                with open('logs/'+mysource+'_log.txt', 'a') as the_file:
                                    the_file.write(mynewline+'\n')
                    else:
                        with open('logs/errors_log.txt','a') as the_file:
                                the_file.write(line)

Posted in Uncategorized | Comments Off on Python script to analyse Juniper firewall logs

Powershell mailboxexportrequest creation and management.

To minimise impact on the server do mailboxexportrequests one at a time and move the completed PST files to a final location as each one is created.

# csv containing alias for each mailbox
$a = import-csv exports.csv

foreach ( $u in $a ) {
			echo "Export $u"
			$ua=$u.alias
			new-mailboxexportrequest $ua -filepath \\pesrv01\exportedemail\$ua.pst
                        #Now wait for it to complete
			do { 
			        sleep 30
                                get-mailboxexportrequest
				$s = Get-MailboxExportRequest -status "completed" | select status
				$s
			}
			until ( $s -ne $null )
			Get-MailboxExportRequest -status "completed" | remove-mailboxexportrequest -confirm:$false
			move  .\$ua.pst '\\OTHERLOCATION\SHARED'
			echo "do next one"
}


Posted in Powershell, VBS, VBA and other scripting., System Administration | Comments Off on Powershell mailboxexportrequest creation and management.