Category: Scripts

Connect and disconnect Windows PowerShell to the Service (Live@edu Office 365)

Connect

PS> $LiveCred = Get-Credential

PS> $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection

PS> Import-PSSession $Session

Disconnect

PS> Remove-PSSession

PS> Remove-PSSession $Session

Powershell Get-QADUser extracts Name and Email from an active directory OU organization unit

PS> Get-QADUser -SearchRoot “simonalsa.com/Users/PowerUsers” -SearchScope Subtree | select Name, Email

The value of SearchScope can be:

  ‘Base’     Limits the search to the base (SearchRoot) object. The result contains a maximum of one object.
  ‘OneLevel’ Searches the immediate child objects of the base (SearchRoot) object, excluding the base object.
  ‘Subtree’  Searches the whole sub-tree, including the base (SearchRoot) object and all its child objects.

Check the Domain OU list with

PS> Get-QADObject -Type OrganizationalUnit

How To manage Office 365 / Live edu Security Groups and Users usign Powershell

Make a new Security Group

PS C:\> New-DistributionGroup -Name WL-Test -Type Security

Assign User to the Security Group

PS C:\> Add-DistributionGroupMember -Identity WL-Test -Member id@simonalsa.com

Remove User from the Security Group

PS C:\> Remove-DistributionGroupMember -Identity WL-Test -Member id@simonalsa.com

Remove Security Group from AD

PS C:\> Remove-DistributionGroup -Identity WL-Test

Extract all AD users account from an Organizational Unit and remove them from a AD Group

Preload Powershell Quest AD Tools

set-Location c:\
Add-PSSnapin Quest.ActiveRoles.ADManagement
Get-PSsnapin
Set-QADPSSnapinSettings -DefaultSizeLimit 0
Get-Command Get-QAD*

Extract all AD users account from an Organizational Unit and Save the target in a Powershell variable

$Ou = "Ou=Users,dc=simonalsa,dc=com"
$Target = Get-QADUser -searchroot $Ou | select SamAccountName

For each AD user remove them from the AD Group

remove-QADGroupMember PowerGroup SIMONALSA\User

Try and debug this lines for your purposes to automate the process

$Ou = "Ou=Users,dc=simonalsa,dc=com"
$Target = Get-QADUser -searchroot $Ou -searchScope 'OneLevel'
foreach ($Person in $Target) 
{
	remove-QADGroupMember -identity "CN=PoweGroup,$Ou" -member $Person.dn
}

Filesystem, MySQL and Crontab Backup application system

I have used two proffesional scripts for backup the application filesystem and database.

Filesystem

# (c) 2001 Chris Arrowood (GNU LGPL V2.1)
# You may view the full copyright text at:
# <a href="http://www.opensource.org/licenses/lgpl-license.html">http://www.opensource.org/licenses/lgpl-license.html</a>
# <a href="http://simplebashbu.sourceforge.net/">http://simplebashbu.sourceforge.net/</a>
# DESCRIPTION:
# A simple BASH script to do nightly backups to tarballs
# on a hard drive (not to tape)  Ideal for home linux users
# to easily backup thier system, provided they have an extra
# hard drive.
#

Basic configuration:

###############################################
#              User Variables                 #
###############################################
#
# Modify these variables to suit your needs
#
# Which day of the week do we want to do full backups? 0=Sunday
  LEVEL0DAY=0
# Where to create the backups; It should already exist
  BACKUP_DIR=/backup/fs
# Filesystems to backup seperated by spaces and the entire string in double quotes; each must start with /
  FILESYSTEMS="/var/www/www.simonalsa.com"
# Should we email results? Also should we email critical errors?  0=false, 1=true
  EMAIL=1
# EMAIL address to send results to
  EMAILADDRESS=simonalsa@simonalsa.com
# Email Subject
  EMAILSUBJECT="$HOSTNAME www.simonalsa.com Filesystem Backup"
# Only keep last weeks level0 backup (0) or keep all lvl 0 backups (1).  Keeping all data may take a lot of space!
  KEEPALL=0
# Do we wnat to compress the backup file using gzip? 0=false, 1=true
  COMPRESS=1
# Should we compress the log file when we are done?  0=false, 1=true
  COMPRESSLOG=1
# If we are compressing, what level do we use?
  COMPRESSLEVEL=6
# Determines whether we see all output to screen. It will still go to log regardless of this value.   0=false, 1=true
  QUIET=1
# Would you like to get detailed information from tar and gzip? 0=false, 1=true  
  VERBOSE=1

Script: backup_www.simonalsa.com.sh

Database 

# MySQL Backup Script
# VER. 2.5.1 - <a href="http://sourceforge.net/projects/automysqlbackup/">http://sourceforge.net/projects/automysqlbackup/</a>
# Copyright (c) 2002-2003 wipe_out@lycos.co.uk
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
Script: <a href="http://www.simonalsa.com/wp-content/uploads/2011/05/backup_mysql.simonalsa.com_.zip">backup_mysql.simonalsa.com</a>

Basic configuration:

 
### START CFG ###
 # Username to access the MySQL server e.g. dbuser
 USERNAME=dbo
 
 # Password to access the MySQL server e.g. password
 PASSWORD=
 
 # Host name (or IP address) of MySQL server e.g localhost
 DBHOST=db.simonalsa.com
 
 # List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3"
 DBNAMES="db"
 
 # Backup directory location e.g /backups
 BACKUPDIR="/backup/db"
 
 # Mail setup
 # What would you like to be mailed to you?
 # - log   : send only log file
 # - files : send log file and sql files as attachments (see docs)
 # - stdout : will simply output the log to the screen if run manually.
 # - quiet : Only send logs if an error occurs to the MAILADDR.
 MAILCONTENT="log"
 
 # Set the maximum allowed email size in k. (4000 = approx 5MB email [see docs])
 MAXATTSIZE="4000"
 
 # Email Address to send mail to? (<a href="mailto:user@domain.com">user@domain.com</a>)
 MAILADDR="simonalsa@simonalsa.com"

Crontab

File: crontab_backup

Content:

1 1 * * * /script/backup_www.simonalsa.com.sh
30 1 * * * /script/backup_mysql.simonalsa.com.sh

Add a new column to a MySQL table alter add after

SQL Syntax> alter table tablename add column columnname varchar(10) after lastcolumnname

Where:

tablename is the table which is going to be modified.

columnname is the new column which is going to be added.

lastcolumnname is the position which the new column is going to be placed

Reference manual: http://dev.mysql.com/doc/refman/5.0/en/alter-table.html 



Alter Active Directory user properties with Powershell QAD Tools Get-QADUser Set-QADUser PasswordNeverExpires User-Change-Password

Follow these instructions:

Firstly load the powershell console from the commandline cmd>Powershell
Next one…

set-Location c:\
Add-PSSnapin Quest.ActiveRoles.ADManagement
Get-PSsnapin
Set-QADPSSnapinSettings -DefaultSizeLimit 0
Get-Command Get-QAD*

List users

Get-QADUser | select-object ClassName, Name, SamAccountName, PrimarySMTPAddress, whenCreated, LastLogon, PasswordNeverExpires, AccountIsDisabled | Where { $_.PasswordNeverExpires -match "True" } | Format-Table
Disable password never expire user property from an active directory
Get-QADUser -Identity &lt;sAMAccountName&gt; | Set-QADUser -passwordNeverExpires $false

Disable user can not change password user property from an active directory

Get-QADUser &lt;sAMAccountName&gt; | Get-QADPermission -Account SELF,Everyone -ExtendedRight 'User-Change-Password' | Remove-QADPermission

Make a new task in W2k3 from the command line

From the command line:

cmd>schtasks /create /tn "New Task" /tr "C:\PROGRA~1\INTERN~1\IEXPLORE.EXE http://www.simonalsa.com" /sc hourly
The task will be created under current logged-on user name ("APOLO\administrator").
Please enter the run as password for APOLO\administrator: ***************
 
SUCCESS: The scheduled task "New Task" has successfully been created.

Simple parse registers and format the output screen with AWK

Script

filter_01.bash

#!/bin/bash
 
#Filter data file 01
 
if [ $# -ne 1 ]
then
  echo "Usage: $0 datafile.txt";
  exit -1;
fi
 
if [ -f $1 ]
then
  echo "File $1 exists";
else
  echo "File $1 does not exists";
  exit -2;
fi
 
if [ -r $1 ]
then
  echo "File $1 can be read";
else
  echo "File $1 can not be read";
  exit -3;
fi
 
#Gets the total number of lines of data file
lines=$(cat $1 | wc -l);
 
#Minus 1
let "lines = lines - 1";
 
echo "Number of registers: $lines";
echo "";
#Parse the register and format the output screen
tail -n $lines $1 | awk -F ';' '{ print $1 $2 " is from " $3 " (" $4 ")" }';

Data file

filter_01.txt

Name;Surname;City;Country
John;Dere;Chicago;USA
Pepe;Gotera;Madrid;Spain
Rompe;Techos;Madrid;Spain

Execute:

salonso@linux-01:~/war/bash/filter_01$ ./filter_01.bash filter_01.txt
File filter_01.txt exists
File filter_01.txt can be read
Number of registers: 3

JohnDere is from Chicago (USA)
PepeGotera is from Madrid (Spain)
RompeTechos is from Madrid (Spain)

MySQL version & startup variables

MySQL Commands:
sql> SELECT VERSION();
Output:
5.0.51-log

sql> SHOW VARIABLES();

Output:

Variable_name Value
auto_increment_increment 1
auto_increment_offset 1
automatic_sp_privileges ON
back_log 50
basedir D:\MySQL_BIN\
binlog_cache_size 32768
bulk_insert_buffer_size 8388608
character_set_client utf8
character_set_connection utf8
character_set_database latin1
character_set_filesystem binary
character_set_results utf8
character_set_server latin1
character_set_system utf8
character_sets_dir D:\MySQL_BIN\share\charsets\
collation_connection utf8_general_ci
collation_database latin1_swedish_ci
collation_server latin1_swedish_ci
completion_type 0
concurrent_insert 1
connect_timeout 5
datadir D:\MySQL_DATA\Data\
date_format %Y-%m-%d
datetime_format %Y-%m-%d %H:%i:%s
default_week_format 0
delay_key_write ON
delayed_insert_limit 100
delayed_insert_timeout 300
delayed_queue_size 1000
div_precision_increment 4
keep_files_on_create OFF
engine_condition_pushdown OFF
expire_logs_days 0
flush OFF
flush_time 1800
ft_boolean_syntax + -><()~*:”"&|
ft_max_word_len 84
ft_min_word_len 4
ft_query_expansion_limit 20
ft_stopword_file (built-in)
group_concat_max_len 1024
have_archive YES
have_bdb NO
have_blackhole_engine YES
have_compress YES
have_crypt NO
have_csv NO
have_dynamic_loading YES
have_example_engine NO
have_federated_engine YES
have_geometry YES
have_innodb YES
have_isam NO
have_merge_engine YES
have_ndbcluster NO
have_openssl DISABLED
have_ssl DISABLED
have_query_cache YES
have_raid NO
have_rtree_keys YES
have_symlink YES
hostname sek-sql-server
init_connect
init_file
init_slave
innodb_additional_mem_pool_size 1048576
innodb_autoextend_increment 8
innodb_buffer_pool_awe_mem_mb 0
innodb_buffer_pool_size 4194304
innodb_checksums ON
innodb_commit_concurrency 0
innodb_concurrency_tickets 500
innodb_data_file_path ibdata1:10M:autoextend
innodb_data_home_dir
innodb_doublewrite ON
innodb_fast_shutdown 1
innodb_file_io_threads 4
innodb_file_per_table OFF
innodb_flush_log_at_trx_commit 1
innodb_flush_method
innodb_force_recovery 0
innodb_lock_wait_timeout 50
innodb_locks_unsafe_for_binlog OFF
innodb_log_arch_dir
innodb_log_archive OFF
innodb_log_buffer_size 1048576
innodb_log_file_size 5242880
innodb_log_files_in_group 2
innodb_log_group_home_dir .\
innodb_max_dirty_pages_pct 90
innodb_max_purge_lag 0
innodb_mirrored_log_groups 1
innodb_open_files 300
innodb_rollback_on_timeout OFF
innodb_support_xa ON
innodb_sync_spin_loops 20
innodb_table_locks ON
innodb_thread_concurrency 8
innodb_thread_sleep_delay 10000
interactive_timeout 28800
join_buffer_size 258048
key_buffer_size 8388600
key_cache_age_threshold 300
key_cache_block_size 1024
key_cache_division_limit 100
language D:\MySQL_BIN\share\english\
large_files_support ON
large_page_size 0
large_pages OFF
lc_time_names en_US
license GPL
local_infile ON
log ON
log_bin ON
log_bin_trust_function_creators OFF
log_error D:\MySQL_LOG\ca_error.log
log_queries_not_using_indexes OFF
log_slave_updates OFF
log_slow_queries ON
log_warnings 1
long_query_time 10
low_priority_updates OFF
lower_case_file_system ON
lower_case_table_names 1
max_allowed_packet 16776192
max_binlog_cache_size 4294967295
max_binlog_size 1073741824
max_connect_errors 10
max_connections 100
max_delayed_threads 20
max_error_count 64
max_heap_table_size 94371840
max_insert_delayed_threads 20
max_join_size 4294967295
max_length_for_sort_data 1024
max_prepared_stmt_count 16382
max_relay_log_size 0
max_seeks_for_key 4294967295
max_sort_length 1024
max_sp_recursion_depth 0
max_tmp_tables 32
max_user_connections 0
max_write_lock_count 4294967295
multi_range_count 256
myisam_data_pointer_size 6
myisam_max_sort_file_size 2147483647
myisam_recover_options OFF
myisam_repair_threads 1
myisam_sort_buffer_size 8388608
myisam_stats_method nulls_unequal
net_buffer_length 16384
net_read_timeout 30
net_retry_count 10
net_write_timeout 60
new OFF
old_passwords OFF
open_files_limit 500
optimizer_prune_level 1
optimizer_search_depth 62
pid_file D:\MySQL_DATA\Data\sek-sql-server.pid
port 3308
preload_buffer_size 32768
profiling OFF
profiling_history_size 15
protocol_version 10
query_alloc_block_size 8192
query_cache_limit 1048576
query_cache_min_res_unit 4096
query_cache_size 49999872
query_cache_type ON
query_cache_wlock_invalidate OFF
query_prealloc_size 8192
range_alloc_block_size 2048
read_buffer_size 131072
read_only OFF
read_rnd_buffer_size 262144
relay_log_purge ON
relay_log_space_limit 0
rpl_recovery_rank 0
secure_auth OFF
secure_file_priv
shared_memory OFF
shared_memory_base_name MYSQL
server_id 1
skip_external_locking ON
skip_networking OFF
skip_show_database OFF
slave_compressed_protocol OFF
slave_load_tmpdir C:\WINDOWS\TEMP\
slave_net_timeout 3600
slave_skip_errors OFF
slave_transaction_retries 10
slow_launch_time 2
sort_buffer_size 2097144
sql_big_selects ON
sql_mode
sql_notes ON
sql_warnings OFF
ssl_ca
ssl_capath
ssl_cert
ssl_cipher
ssl_key
storage_engine MyISAM
sync_binlog 0
sync_frm ON
system_time_zone Romance Standard Time
table_cache 64
table_lock_wait_timeout 50
table_type MyISAM
thread_cache_size 4
thread_stack 196608
time_format %H:%i:%s
time_zone SYSTEM
timed_mutexes OFF
tmp_table_size 94371840
tmpdir C:\WINDOWS\TEMP\
transaction_alloc_block_size 8192
transaction_prealloc_size 4096
tx_isolation REPEATABLE-READ
updatable_views_with_limit YES
version 5.0.51-log
version_comment Source distribution
version_compile_machine ia32
version_compile_os Win32
wait_timeout 28800

WordPress Themes