0

Check if http/https webserver is responding bat file script

Posted by paris on Jun 20, 2017 in Code
@if (@CodeSection == @Batch) @then
 
@echo off
setlocal
 
set "servers=dev1 dev2 dev3 test1 test2 test2:8080 prod prod:443"
 
for %%I in (%servers%) do (
    for /f "tokens=1,2 delims=:" %%a in ("%%I") do (
        set "port=%%~b"
        if not defined port set "port=80"
        setlocal enabledelayedexpansion
        cscript /nologo /e:JScript "%~f0" "%%~a" "!port!" && (
            echo %%a port !port!: OK
        ) || (
            echo %%a port !port!: Error
        )
        endlocal
    )
)
 
goto :EOF
 
@end // end batch / begin JScript chimera
 
var server = WSH.Arguments(0),
    port = WSH.Arguments(1),
    protocol = port == 443 ? 'https' : 'http',
    URL = protocol + '://' + server + ':' + port + '/',
    XHR = WSH.CreateObject('Microsoft.XMLHTTP');
 
XHR.open('GET', URL);
XHR.setRequestHeader('User-Agent','XMLHTTP/1.0');
XHR.send('');
while (XHR.readyState != 4) WSH.Sleep(25);
WSH.Quit(XHR.status - 200);

 

Kudos to Rojo for this

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , , , , ,

 
0

Securing Apache to use Certificate Authentication auth_x509

Posted by paris on Apr 16, 2017 in Code, Random

 

Query to see if Certificate Exists via  x509 based logins

<?php
include(__DIR__."/auth_mysql.php");
 
/**
 * Mysql based authentication
 * The standard username/password based authentication library
 *
 * @package CMS
 * @author Sid Karunaratne
 **/
class auth_x509 extends auth_mysql
{
	public function pre_login()
	{
		foreach($_SERVER as $key => $value)
		{
			if (!$value || strncmp($key, 'SSL_CLIENT_S_DN_Email', 21) !== 0)
				continue;
			$user = $this->_check_email_is_valid($value);
			if ($user)
				return $user;
		}
		return false;
	}
 
	protected function _check_email_is_valid($email)
	{
		$user = $this->db->select("
					u.id,
					u.name,
					GROUP_CONCAT(g.id SEPARATOR ',') as team_ids,
					u.username as email,
					GROUP_CONCAT(g.name SEPARATOR ', ') as teams,
					permission_last_set
				")
			->from("_auth_user u")
			->join("_auth_user_group_xrefs aux", "aux.user_id = u.id")
			->join("_auth_group g", "g.id = aux.group_id")
			->where("u.username", $email)
			->group_by("u.id")
			->get()->result();
		if (!$user)
			return false;
 
 
		// The user is valid
		$user = array_shift($user);		
		$user = $this->_finalise_user_login($user);
		return $user;
	}
 
	public function login($credentials)
	{
		return false;
	}
}
// END class auth_x509

 

 

httpd-ssl.conf

Listen 443
 
SetEnvIf User-Agent ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
 
<VirtualHost *:443>
DocumentRoot "/srv/http/"
ServerName website.domain.com:443
ServerAdmin email@address.com
ErrorLog /var/log/httpd/ssl.error.log
TransferLog /var/log/httpd/ssl.access.log
BrowserMatch ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
 
SSLEngine on
SSLProtocol -all +TLSv1 +SSLv3
SSLCipherSuite HIGH:MEDIUM
SSLProxyEngine off
# The certificate CACert signed
SSLCertificateFile /etc/httpd/conf/ssl/dev.zealothost.net.crt
# The private key
SSLCertificateKeyFile /etc/httpd/conf/ssl/dev.zealothost.net.key
# CACert's certificate - Seems to not be required
SSLCertificateChainFile /etc/httpd/conf/ssl/ca.crt
# CACert's certificate - The CA I require certificates to be signed with
SSLCACertificateFile /etc/httpd/conf/ssl/ca-dskort.crt
SSLOptions +StrictRequire +OptRenegotiate +StdEnvVars +ExportCertData
 
SSLVerifyClient require
SSLVerifyDepth 1
</VirtualHost>

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , ,

 
0

Bash Script for creating virtual hosts (along with the unix user, the db etc)

Posted by paris on Apr 16, 2017 in Code

Synopsis

This is the documentation for the create-website script I’ve created. The results of passing the -h parameter print out the following help:

SYNOPSIS:
create-website -u USER -w WEBSITE [-s|-f|-d|-h|-i <ip>]
DESCRIPTION:
Creates a new web site for a new user on the system. This
includes creating the user, the FTP account, the Database and
the virtual host

USER is the username of the owner of the web site. If the
account name doesn’t exist it will be created. Must be a valid
UNIX and MySQL username

WEBSITE is the url of the site to be created. Must be a FQDN,
should not include the www prefix. Preferably should be lower-
case.

-s Allow SSH based logins for the user [default = false]
-f Allow FTP based logins for the user [default = false]
-d Create a database for the user [default = false]
-i The IP the virtual host will listen on, by default the IP of eth0
-h Show this help message

That should be pretty self explanatory.
Configuration and execution

This script needs root privileges to run, so it is important that only root is able to edit the script. The script is stored in /usr/sbin/create-website.

This script does pull in a configuration file from /etc/.create-website. This file should be owned by root and chmodded to 400 (only readable by root). The contents of that configuration file should be something like:

<?php
$config = array(
‘mysql_username’ => ‘builder’,
‘mysql_password’ => ‘some_password’,
‘mysql_host’ => ‘localhost’
);
?>

This MySQL account need full privileges in order to be allowed to create accounts and give out the correct privileges itself.

Log rotation configurations are put into place that will rotate the access.log and error.log on a weekly basis, keeping 52 weeks of log files for each web site.
Files this script potentially touches:

Files Trigger
/etc/passwd Creating User
/etc/groups Creating User
/etc/shadow Creating User
/etc/apache2/sites-available/$website Creating Website
/etc/apache2/sites-enabled/$website Creating Website
/etc/logrotate.d/apache2_$website Creating Website
/etc/vsftpd.user_list When user is granted FTP access
/etc/ssh/sshd_config When user is granted SSH access
/home/$user/$website/ Directory where public facing web content resides
/home/$user/log/www/$website Directory where Apache log files reside

Note that this script has made specifically for the Ubuntu server with all the software installed where apt-get installs them by default. This script will need tweaking if used on a different set up.

 

#!/usr/bin/php
<?php
/**
 * Create Website
 * 
 * Entirely in house, very system dependent. Works on an Ubuntu installation with Apache and Mysql at pretty much default preferences.
 * If you're moving this to a new server you will very likely have to re-write parts of it (paths etc)
 * 
 * @license Public Domain
 * @author Sid Karunaratne
 */
 
error_reporting(0);
// Options: user, website, has_ssh, has_ftp, has_db
$opts		= getopt('u:w:sfdhi:');
$user		= $opts['u'];
$website	= $opts['w'];
$ip			= array_key_exists('i',$opts) ? $opts['i'] : get_ip();
$has_ssh	= (bool) array_key_exists('s',$opts);
$has_ftp	= (bool) array_key_exists('f',$opts);
$has_db		= (bool) array_key_exists('d',$opts);
$help		= (bool) array_key_exists('h',$opts);
 
$err = fopen('php://stderr','w');
$out = fopen('php://stdout','w');
$db = null;
 
if ($help || (!$user || !$website))
{
	display_help();
	exit;
}
 
if (posix_getuid() !== 0)
{
	_err('I need to be run as root');
	exit(1);
}
 
if (site_exists($website))
{
	_err('The website already exists, if you want to add more users to control this site you are going to have to do it manually');
	exit(1);
}
 
# Check with the user we are doing the right thing
_err("About to create the account $user with the website $website with the virtual host listening on $ip");
$str = $has_ssh ? '' : 'NOT ';
_err($str. "allowing SSH login");
$str = $has_ftp ? '' : 'NOT ';
_err($str. "allowing FTP login");
$str = $has_db ? '' : 'NOT ';
_err($str. "creating a database");
_err("Press y/n to confirm action: ", false);
if (!in_array(_in(), array('y', 'Y', 'yes', 'true')))
{
	_err('Exiting');
	exit(1);
}
 
require('/etc/.create-website');
connect_db();
 
if (!user_exists($user))
{
	_out("User '$user' does not exist and will be created");
	`adduser --gecos "" $user`;
}
if ($has_ssh && !user_has_ssh($user))
{
	_out("User '$user' is being given SSH access");
	`echo 'AllowUsers $user' >> /etc/ssh/sshd_config`;
}
if ($has_ftp && !user_has_ftp($user))
{
	_out("User '$user' is being given chrooted FTP access");
	`echo $user >> /etc/vsftpd.user_list`;
}
if ($has_db)
{
	# Create DB
	global $db;
	_out("Database being created (or already exists), user being created and access to database being given");
	$mysql_password = prompt_silent("Please enter a MySQL password: ");
	$db_name = str_replace('.', '_', $website);
	mysql_query("CREATE DATABASE IF NOT EXISTS `$db_name`");
	mysql_query("CREATE USER '$user'@'%' IDENTIFIED BY '".mysql_real_escape_string($mysql_password)."'");
	mysql_query("GRANT USAGE ON * . * TO '$user'@'%' IDENTIFIED BY '".mysql_real_escape_string($mysql_password)."'");
	mysql_query("GRANT ALL PRIVILEGES ON `$db_name` . * TO '$user'@'%'");
	mysql_query("FLUSH PRIVILEGES");
 
}
_out("Virtual host for $website is being created");
# Create vhost
 
mkdir("/home/$user/$website", 0755, true);
chown("/home/$user/$website", $user);
chgrp("/home/$user/$website", $user);
mkdir("/home/$user/log/www/$website", 0755, true);
chown("/home/$user/log/www/$website", $user);
chgrp("/home/$user/log/www/$website", $user);
$vhost = "<VirtualHost {$ip}:80>
    ServerAdmin $user@keepthinking.it
    DocumentRoot /home/$user/$website
    ServerName $website
    ServerAlias www.$website
    ErrorLog /home/$user/log/www/$website/error.log
    CustomLog /home/$user/log/www/$website/access.log combined
</VirtualHost>";
file_put_contents("/etc/apache2/sites-available/$website", $vhost);
symlink("/etc/apache2/sites-available/$website", "/etc/apache2/sites-enabled/$website");
 
_out("Configuration for the logrotation are being put in place");
# Adding logrotate
$logrotate = "/home/$user/log/www/$website/*.log {
	weekly
	missingok
	rotate 52
	compress
	notifempty
	copytruncate
}
";
file_put_contents("/etc/logrotate.d/apache2_{$user}_{$website}", $logrotate);
 
_err("Services are being reloaded for the changes to take effect");
`service apache2 reload`;
`service vsftpd reload`;
`service ssh reload`;
 
 
/**************************
/* HERE ARE THE FUNCTION THAT YOU SHOULDN'T NEED TO TOUCH
**************************/
 
function user_exists($user)
{
	$users = file('/etc/passwd', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
	foreach ($users as $line)
	{
		$components = explode(':', $line);
		if ($components[0] === $user)
			return true;
	}
	return false;
}
 
function site_exists($website)
{
	return file_exists("/etc/apache2/sites-enabled/$website");
}
 
function user_has_ssh($user)
{
	$config = file('/etc/ssh/sshd_config', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
	foreach ($config as $line)
	{
		if (strncasecmp($line, 'AllowUsers', 10) === 0)
			if (in_array($user, explode(' ', $line)))
				return true;
	}
	return false;
}
 
function user_has_ftp($user)
{
	$users = file('/etc/vsftpd.user_list', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
	foreach ($users as $line)
	{
		if ($line === $user)
			return true;
	}
	return false;
}
 
function connect_db()
{
	global $db;
	global $config;
	$db = mysql_connect($config['mysql_host'], $config['mysql_username'], $config['mysql_password']);
	mysql_select_db('mysql', $db);
	echo mysql_error();
}
 
function display_help()
{
	$help = "
	SYNOPSIS:
		create-website -u USER -w WEBSITE [-s|-f|-d|-h|-i <ip>]
	DESCRIPTION:
		Creates a new web site for a new user on the system. This 
		ncludes creating the user, the FTP account, the Database and
		the virtual host
 
		USER is the username of the owner of the web site. If the
		account name doesn't exist it will be created. Must be a valid
		UNIX and MySQL username
 
		WEBSITE is the url of the site to be created. Must be a FQDN,
		should not include the www prefix. Preferably should be lower-
		case.
 
		-s	Allow SSH based logins for the user [default = false]
		-f	Allow FTP based logins for the user [default = false]
		-d	Create a database for the user [default = false]
		-i	The IP the virtual host will listen on, by default the IP of eth0
		-h	Show this help message";
	_err($help);
}
 
/**
 * Interactively prompts for input without echoing to the terminal.
 * Requires a bash shell and won't work with safe_mode settings (Uses `shell_exec`)
 * from: http://www.sitepoint.com/blogs/2009/05/01/interactive-cli-password-prompt-in-php/
 */
function prompt_silent($prompt = "Enter Password:")
{
	$command = "/usr/bin/env bash -c 'echo OK'";
	if (rtrim(shell_exec($command)) !== 'OK')
	{
		trigger_error("Can't invoke bash");
		return;
	}
	$command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'";
	$password = rtrim(shell_exec($command));
	_out('');
	return $password;
}
 
function get_ip()
{
	return substr(`ifconfig | grep 'addr:' | head -n1 | awk '{print $2}' | sed 's/addr://'`, 0, -1);
}
 
 
function _err($msg, $nl=true) { global $err; if($nl) $msg.=PHP_EOL; fwrite($err, $msg); }
function _out($msg) { global $out; fwrite($out, $msg . PHP_EOL); }
function _in() { return trim(fgets(STDIN)); }
 
?>

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , ,

 
0

PHP to Read Keyword, Title and Description

Posted by paris on Apr 16, 2017 in Code
<?php
if ($_POST)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	echo "
	<table border='1'>
		<thead>
			<tr>
				<th>URL</th>
				<th>Title</th>
				<th>Description</th>
				<th>Keywords</th>
			</tr>
		</thead>
		<tbody>";
	foreach (explode(PHP_EOL, $_POST['textarea']) as $url)
	{
		$url = trim($url);
		if (!preg_match("/^https?:\/\//i", $url))
		{
			continue;
		}
		else
		{
			curl_setopt($ch, CURLOPT_URL, $url);
			$html = curl_exec($ch);
			if (!$html)
				continue;
			$data = parse_page($html);
 
			// secure the data for printing
			$url = htmlentities($url, ENT_QUOTES);
			foreach ($data as $key => $value)
				$data[$key] = htmlentities($value, ENT_QUOTES, "UTF-8");
			echo "<tr>";
			echo "<td>{$url}</td>";
			echo "<td>{$data['title']}</td>";
			echo "<td>{$data['description']}</td>";
			echo "<td> {$data['keywords']}</td>";
			echo "</tr>";
		}
	}
	curl_close($ch);
	echo "
		</tbody>
	</table>";
}
 
 
function parse_page($html)
{
     /* get page's title */
     preg_match("/<title>(.+)<\/title>/siU", $html, $matches);
     $title = $matches ? $matches[1] : null;
     /* get page's keywords */
 
$re="<meta\s+name=['\"]??keywords['\"]??\s+content=['\"]??(.+)['\"]??\s*\/?>";
     preg_match("/$re/siU", $html, $matches);
     $keywords = $matches ? $matches[1] : null;
 
     /* get page's description */
 
$re="<meta\s+name=['\"]??description['\"]??\s+content=['\"]??(.+)['\"]??\s*\/?>";
     preg_match("/$re/siU", $html, $matches);
     $desc = $matches ? $matches[1] : null;
 
     /* parse links */
     $re="<a\s[^>]*href\s*=\s*(['\"]??)([^'\">]*?)\\1[^>]*>(.*)<\/a>";
     preg_match_all("/$re/siU", $html, $matches);
     $links = $matches ? $matches[2] : null;
 
	return array(
		"title" => $title,
		"description" => $desc,
		"keywords" => $keywords,
	);
}
?>
 
<form method="post" action="?">
<textarea name="textarea" cols="45" rows="5"><?php echo @htmlentities($_POST['textarea'], ENT_QUOTES, "UTF-8")?></textarea><br />
<input type="submit" name="button" id="button" value="Submit" />
</form>

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

WordPress Split Description\Tagline into Multiple Lines

Posted by paris on Feb 8, 2017 in Code

Add the Following Code to your Functions.php theme file ( under Appearance ) 

/*
 * Split Description\TagLine
 */
    function get_split_description() {
        $title = get_bloginfo( 'description', 'display' );;
        $lines = explode(' &#8211; ', $title);
        $output = false;
        $count = 0;
 
        foreach( $lines as $line ) {
            $count++;
            $output .= '<span class="line-'.$count.'">'.$line.'</span><br> ';
        }
 
        return $output;
    }

 

 

Change in your header.php file to use the following :

<p class="site-description"><?php echo get_split_description(); ?></p>
					<?php endif; ?

 

 

Then change your Tagline to line 1 – line 2 ( with a slash and space in between ) 

VN:F [1.9.22_1171]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

VMware PowerCLi Powershell Script to get VMWare Tools out of Date and Virtual Machine Hardware Versions

Posted by paris on Jan 5, 2016 in Code
New-VIProperty -Name ToolsVersion -ObjectType VirtualMachine -ValueFromExtensionProperty 'Config.tools.ToolsVersion' -Force
 
New-VIProperty -Name ToolsVersionStatus -ObjectType VirtualMachine -ValueFromExtensionProperty 'Guest.ToolsVersionStatus' -Force
 
Get-VM | Select Name, Version, ToolsVersion, ToolsVersionStatus | Export-Csv -NoTypeInformation -UseCulture -Path C:\VMHWandToolsInfo.csv
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

New User Powershell Script

Posted by paris on Sep 28, 2015 in Code

To copy 

################################## Import ActiveDirectory ##############################################
 
Import-Module ActiveDirectory
 
################################## Import Exchange snap-in #############################################
 
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
 
########################################################################################################
 
#Clear-host
 
# Gets all of the users info to be copied to the new account
#Checking the user to copy if it exist
	do {
$nameds = Read-Host "Copy From Username"
if (dsquery user -samid $nameds){"AD User Found"
}
 
elseif ($nameds = "null") {"AD User not Found"}
}
while ($nameds -eq "null")
 
#Checking if the new user exist
 
do {
 
$NewUserds = Read-Host "New Username"
 
While ( $NewUserds -eq "" ) { $NewUserds = Read-Host "New Username"}
$NewUser = $Newuserds
 
#check if AD user exist	
if (dsquery user -samid $NewUserds){"Ad User Exist"}
 
#check imanage user exist
$SQLServer = "imanagesqlserver" #use Server\Instance for named SQL instances! 
$SqlQuery = "SELECT sum(A+B) FROM (select COUNT(1) as A FROM [imanagedatabase].[MHGROUP].DOCUSERS where [USERID]='$NewUserds') a
CROSS JOIN (select COUNT(1) as B FROM [imanagedatabase2].[MHGROUP].DOCUSERS where [USERID]='$NewUserds') b"
 
 
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Integrated Security = True"
 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
 
$DataSet = New-Object System.Data.DataSet
[void]$SqlAdapter.Fill($DataSet)
 
$SqlConnection.Close()
 
$UserExist = $DataSet.Tables[0]| select -expand Column1
 
if ($UserExist -gt 0) {
$NewUserds -eq ""
"iManage User Found"
}
 
elseif ($NewUserds = "no") {"Validation OK"}
}
 
while ($Newuserds -ne "no")
 
 
# Gets all of the users info to be copied to the new account
 
$name = Get-AdUser -Identity $nameds -Properties *
 
$DN = $name.distinguishedName
$OldUser = [ADSI]"LDAP://$DN"
$Parent = $OldUser.Parent
$OU = [ADSI]$Parent
$OUDN = $OU.distinguishedName
$NewUser = Read-Host "New Username"
$firstname = Read-Host "First Name"
$Lastname = Read-Host "Last Name"
$Extention = Read-Host "Users Extension"
$Password = Read-Host "New Password"
$SecurePassword = ConvertTo-SecureString $Password –asplaintext –force
$NewName = "$firstname $lastname"
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() 
$newuserfinitial = $firstname.substring(0,1)
$pager = $name.Pager
$newusernumber= $pager.Substring(0,$pager.Length-3)+$Extention
$OldNotes = $name.info
 
#Remove Spaces for Make Email Alias Correct
$Lastnamens = $Lastname -replace '\s',''
 
# Creates the user from the copied properties
 
New-ADUser -SamAccountName $NewUser -Name $NewName -GivenName $firstname -Surname $lastname -EmailAddress $newuserfinitial$Lastnamens@domain.com  -Instance $DN -Path "$OUDN" -AccountPassword $SecurePassword –userPrincipalName $NewUser@$domain -Company $name.Company -Department $name.Department -Manager $name.Manager -title $name.Title -Description $name.Description -HomePage $name.HomePage  -Office $name.Office -City $name.city -PostalCode $name.postalcode -Country $name.country -OfficePhone $newusernumber -Fax $name.fax -State $name.State -StreetAddress $name.StreetAddress  -homedrive "H" -homedirectory "\\domain.local\dfs\home\$NewUser" -Enabled $true
 
#Copy Signature
Set-ADUser $NewUser -Replace @{info="$OldNotes"}
Set-ADUser $NewUser -Replace @{pager="$newusernumber"}
 
# Set Profile Location
$NewUserAdDetails = Get-AdUser -Identity $NewUser -Properties *
$DN = $NewUserAdDetails.distinguishedName
$NewUserLdap = [ADSI]"LDAP://$DN"
$NewUserLdap.psbase.invokeset(“terminalservicesprofilepath”,”\\domain.local\dfs\profiles\$NewUser)
$NewUserLdap.setinfo()
 
 
# gets groups from the Copied user and populates the new user in them
 
write-host "Copying Group Membership"
 
$groups = (GET-ADUSER –Identity $name –Properties MemberOf).MemberOf
foreach ($group in $groups) { 
 
Add-ADGroupMember -Identity $group -Members $NewUser
}
 
$count = $groups.count
 
#Check to see if new user is member of group and do things - Use Windows 2000 Name
$newusergroups = (GET-ADUSER –Identity $NewUser –Properties MemberOf).MemberOf
if ($newusergroups -match '#ADGROUP') { 
 
$currentuser = [Environment]::UserName
 
#Give the user who is running the script full permissions to the user Mailbox but don't add to Outlook
Add-MailboxPermission -Identity $NewUser -User $currentuser  -AccessRights FullAccess -Automapping $false
 
#Create the Folders
C:\scripts\Folders.ps1 $NewUser
 
#Remove Permissions
Remove-MailboxPermission -Identity $NewUser -User $currentuser -AccessRights FullAccess
 
}
 
# List of Mailbox DB
 
$databases = Get-MailboxDatabase
$Count = 0
 
Foreach ($database in $databases){
 
    Write-Host $Count "." $database.Name
    $Count ++
 
}
 
$Choice = Read-Host "Please choose a Database to list databases from"
 
$db = $databases[$Choice].Name
 
# After some testing it seems that sometimes ad don't have time to process everything and while trying to access the user for exchange it gave error.
 
write-host "Waiting time for Ad to process earliers operations"
 
Start-Sleep -s 30
 
#Clear-host
 
# Creates the New users mailbox 
 
Enable-Mailbox -Identity $NewUser@$domain -alias "$NewUser" -ManagedFolderMailboxPolicyAllowed -Database "$db"
 
# Sets secondary smtp adress while specifying the Primary smtp adress(1st address with the SMTP is the primary one).
 
Start-Sleep -s 15
 
Set-Mailbox "$NewUser" -EmailAddressPolicyEnabled $false -EmailAddresses SMTP:"$newuserfinitial$Lastnamens@domain.com"
 
#Does the user have a value for custom attribute e.g. Partner? if so copy to new user
 
if(Get-Mailbox -Identity $user | Select -Expand CustomAttribute1) { Set-Mailbox -Identity $newuser -CustomAttribute1 (Get-Mailbox -Identity $user | Select -Expand CustomAttribute1) }
 
#clear-host
 
# Creates the New user Profile Folder
New-item \\domain.local\dfs\profiles\"$newuser" -type directory
$acl = Get-Acl \\domain.local\dfs\profiles\"$NewUser"
$acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount])
$acl.SetAccessRuleProtection($true, $true)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule "domain\$NewUser","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow"
$acl.addAccessRule($rule)
Set-Acl \\domain.local\dfs\profiles\"$NewUser" $acl
 
# Creates the New user Home Folder
New-item \\domain.local\dfs\home\"$newuser" -type directory
$acl = Get-Acl \\domain.local\dfs\home\"$NewUser"
$inheritanceFlags = ([Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit) 
$propagationFlags = [Security.AccessControl.PropagationFlags]::None 
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule "domain\$NewUser","FullControl",$inheritanceFlags, $propagationFlags,"Allow"
$acl.addAccessRule($rule)
Set-Acl \\domain.local\dfs\home\"$NewUser" $acl
 
Set-AdUser -Identity $NewUser -Replace @{HomeDirectory="\\domain.local\dfs\home\$NewUser"}
 
$homedrivereadded = Read-Host "Now can you reset the homedrive as the script doesn't do a very good job"
 
#Logging in as user to create redirected
$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$Process = New-Object System.Diagnostics.Process
 
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\cmdkey.exe"
$ProcessInfo.Arguments = "/generic:TERMSRV/TERMINALSERVERNAME /user:$NewUser /pass:$Password"
$Process.StartInfo = $ProcessInfo
$Process.Start()
 
$ProcessInfo.FileName = "$($env:SystemRoot)\system32\mstsc.exe"
$ProcessInfo.Arguments = "$MstscArguments /v $Computer"
$Process.StartInfo = $ProcessInfo
$Process.Start()

 

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , ,

 
0

Send a Robocopy Job notification via Powershell

Posted by paris on Sep 10, 2015 in Code
# Change these values
$Logfile = “C:\Scripts\Logs\AffSql_” + (Get-Date).tostring(“yyyyMMdd”) + “.log”
 
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction silentlyContinue
 
# Copy Folder with Robocopy
$command = 'Robocopy.exe "\\unc\path\" "E:\localpath" /S /MIR /R:10 /W:5 /LOG+:$Logfile /NP /TS /FP /COPY:DAT'
iex $command
 
# Send E-mail message with log file attachment
$smtpServer = "smtpserver"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "from@domain.com"
$msg.To.Add("to@domain.com")
$msg.Subject = "SQL Backup"
$msg.Body = get-content $Logfile | out-string
$smtp.Send($msg)
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

Search for folder in iManage

Posted by paris on Sep 9, 2015 in Code

It seems the iManage Inbox has difficulties filing items in a folder with a Custom24 Attribute attached to it. Here’s how to search imanage folders and list Workspaces/Folders with this attribute to remove where required.

SELECT PF.PRJ_NAME AS 'Folder Name', PWS.PRJ_NAME AS 'Workspace Name', PN.VALUE AS 'Cust 24 Value'
FROM MHGROUP.PROJECTS PF
JOIN MHGROUP.PROJECT_NVPS PN ON PF.PRJ_ID = PN.PRJ_ID
JOIN MHGROUP.PROJECTS PWS ON PF.TREE_ID = PWS.PRJ_ID AND PWS.PRJ_ID <> PF.PRJ_ID 
JOIN MHGROUP.DOCMASTER DWS ON DWS.DOCNUM = PWS.DOCNUM
WHERE PN.NAME = 'iMan___48'
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , ,

 
0

Worksite iManage History SQL Search Query

Posted by paris on Jul 24, 2015 in Code

Worksite/Imanage Monitor can export a document list based on History using the History search but it’s limited in the way it can display comments as well as duplicate Document Numbers. Below is SQL of how to get this direct in SSSM

Change the WorksiteDB to your DB and APPName to your application

SELECT DISTINCT [WORKSITEDB].[MHGROUP].[DOCHISTORY].[DOCNUM]
     ,[WORKSITEDB].[MHGROUP].[DOCHISTORY].[VERSION]
	 ,[WORKSITEDB].[MHGROUP].[DOCMASTER].DOCNAME
	 ,[WORKSITEDB].[MHGROUP].[DOCMASTER].T_ALIAS
      ,[ACTIVITY]
      ,[ACTIVITY_CODE]
      ,[ACTIVITY_DATETIME]
      ,[DURATION]
      ,[DOCUSER]
      ,[APPNAME]
      ,[LOCATION]
	  , CAST([WORKSITEDB].[MHGROUP].[DOCHISTORY].[COMMENTS] AS NVARCHAR(MAX))
  FROM [WORKSITEDB].[MHGROUP].[DOCHISTORY] JOIN [WORKSITEDB].[MHGROUP].[DOCMASTER] ON [WORKSITEDB].[MHGROUP].[DOCHISTORY].[DOCNUM]=[WORKSITEDB].[MHGROUP].[DOCMASTER].[DOCNUM] WHERE (APPNAME = 'APPLICATIONNAME') AND (ACTIVITY = 'Checkin')
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Tags: , , , , , ,

Copyright © 2017 Welcome to Pariswells.com All rights reserved. Theme by Laptop Geek. Privacy Policy