Powershell create share on current server - Grant permission to user/groups - networking

I'm having no problem creating a share or assigning permissions, but I'm having a really difficult time actually accessing this fully. I'm the administrator on the server, I'm trying to test prepping the server for other users to access and I'm trying to set the permission, for now, to full access to everyone.
The issue is that when I try to create a new file/folder in the share I get access denied.
Does anyone else encounter this error when making shares through powershell?
Here is the code I have been using:
function New-Share
{
param (
[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Mandatory=$true, HelpMessage="No folder name specified")]
[string]$FolderName,
[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Mandatory=$true, HelpMessage="No share name specified")]
[string]$ShareName,
[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Mandatory=$false, HelpMessage="No description specified")]
[string]$Description
)
$error.clear()
# Check for folder; Create it if it doesn't exist
If (!(Test-Path $FolderName))
{
New-Item $FolderName -type Directory | Out-Null
}
# Check for share; Create it if it doesn't exist
$Shares=[WMICLASS]"WIN32_Share"
if (!(Get-WMIObject Win32_share -filter "name='$ShareName'"))
{
$Shares.Create($FolderName,$ShareName,0,65535,$Description) | Out-Null
if (!($error))
{
# Share created
return $true
} else {
# Error
return $false
}
} else {
# Share Exists
return $false
}
}
I've been Invoking the function with this:
function bo.Share()
{
$domain = [Environment]::UserDomainName
$BDrive = "$boDrive" + ":\SYNintviewer"
New-Share -FolderName "$BDrive" -ShareName "SYNintviewer" -Description "SYNintviewer"
}

I actually got this working on my own...
Calling this function instead worked:
function bo.Share()
{
$domain = [Environment]::UserDomainName
$BDrive = "$boDrive" + ":\SYNintviewer"
echo "$boDrive is BoDRIVE"
echo "$BDrive is BDRIVE"
New-Share -Sharename "SYNintviewer" -Sharepath "$BDrive" -group "Authenticated Users" -auth FULL
}

Related

Where do you store user uploaded content within a Symfony 4 application?

I have a section within my site where the user can upload their own profile pictures which is stored in the output directory and tracked in the database like so:
$form = $this->createForm(ProfileUpdateForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$user = $this->getUser();
$firstname = $form->get('firstname')->getData();
$lastname = $form->get('lastname')->getData();
$picture = $form->get('profilepicture')->getData();
if($picture == null)
{
$user
->setFirstName($firstname)
->setLastName($lastname);
}
else
{
$originalFilename = pathinfo($picture->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = strtolower(str_replace(' ', '', $originalFilename));
$newFilename = $safeFilename.'-'.uniqid().'.'.$picture->guessExtension();
try {
$picture->move(
'build/images/user_profiles/',
$newFilename
);
} catch (FileException $e) {
$this->addFlash("error", "Something happened with the file upload, try again.");
return $this->redirect($request->getUri());
}
// updates the 'picture' property to store the image file name
// instead of its contents
$user
->setProfilePicture($newFilename)
->setFirstName($firstname)
->setLastName($lastname);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash("success", "Your profile was updated!");
return $this->redirectToRoute('account');
}
return $this->render('account/profile.html.twig', [
'profileform' => $form->createView()
]);
That issue I've found is that every time I compile my (local) project, the image is then deleted (because the public/build directory gets built by deleting and creating again).
If I'm not mistaken, isn't that how deployments work too? And if so, is that the right way to upload an image? What's the right way of going about this?
I'm not sure why, but your public/ directory shouldn't be deleted.
If you're using Webpack Encore, then public/build/ content is deleted and created again when you compile assets. But not public/ itself.
For uploads, we create public/upload/ directory.
Then, most of the time, we set some globals, which allow us to save the file name only.
Globals for Twig in config/packages/twig.yaml which "root" will be in your public/ directory
twig:
globals:
app_ul_avatar: '/upload/avatar/'
app_ul_document: '/upload/document/'
And globals for your controllers, repositories, etc in config/services.yaml
parameters:
app_ul_avatar: '%kernel.root_dir%/../public/upload/avatar/'
app_ul_document: '%kernel.root_dir%/../public/upload/document/'
It's handy because, as I just said, you only get to save the file name in the database.
Which mean that, if you got a public/upload/img/ folder, and want to also generates thumbnails, you can then create public/upload/img/thumbnail/ and nothing will change in your database, nor do you have to save an extra path.
Just create a new global app_ul_img_thumbnail, and you're set.
Then all you have to do is call your globals when you need them, and contact with the file name:
In Twig:
{{ app_ul_avatar~dbResult.filename }}
Or in Controller:
$this->getParameter('app_ul_avatar').$dbResult->getFilename();

Dump SNMP information into file using Nagios

Is there any plugin of Nagios which can capture information from multiple SNMP agents and will dump snmpwalk information in a certain interval .
It will be better if information will be dumped in JSON format .
Because of the well documented plugin development guidelines, this is something you could easily build yourself!
Let's build one right now. Let's say we have 2 IP addresses, 192.168.1.10 and 192.168.1.11. We'll build a simple plugin using PHP, although you can ideally write it in any language you like.
This plugin isn't going to conform completely to the guides, but it should give you a nice starting point!
#!/usr/bin/php
<?php
// check if we have at least the minimum required output
// (we need at least 1 argument)
if (count($argv) < 2) {
echo <<<USAGE
Usage:
{$argv[0]} <outputfile> <address1>,<snmpcommunity1>,<snmpversion1>,<mib1> <address2>,<snmpcommunity2>,<snmpversion2>,<mib2> ...
USAGE;
exit(1);
}
// prep the data
$hosts = array();
$output = array();
$output_file = '';
for ($i = 1; $i < count($argv); $i++) {
$host = explode(",", $argv[$i]);
// we need exactly 4 elements
if (count($host) != 4) {
// unless of course we are specifying the output file to write the data to!
if (count($host) == 1) {
$output_file = $argv[$i];
continue;
}
echo "{$argv[$i]} IS INVALID. YOU MUST SPECIFY ALL OF: <address>,<snmpcommunity>,<snmpversion>,<mib>\n";
exit(1);
}
$hosts[] = array(
'address' => $host[0],
'snmp_community' => $host[1],
'snmp_version' => $host[2],
'mib' => $host[3],
);
}
// cycle through each host and gather the data
// this may take a while
foreach($hosts as $host) {
$snmpwalk_array = get_snmpwalk_lines($host['address'], $host['snmp_community'], $host['snmp_version'], $host['mib']);
$snmp_array = walk_lines_to_snmp_array($snmpwalk_array);
$output[$host['address']] = $snmp_array;
}
// convert the output array to json and put it in the file!
$json = json_encode($output);
file_put_contents($output_file, $json);
$num_hosts = count($hosts);
echo "OK - {$num_hosts} PROCESSED\n";
exit(0);
// format an array in a sane way from snmp walk output
// this will return an array like:
// [oid][type] = 'Counter32'
// [oid][value] = 0011232
// etc.
function walk_lines_to_snmp_array($walk_arr) {
$snmp = array();
foreach ($walk_arr as $line) {
$oid = convert_snmpwalk_line_to_array($line, $arr);
if ($oid !== false)
$snmp[$oid] = $arr;
}
return $snmp;
}
// return an array of an executed snmpwalk output
function get_snmpwalk_lines($address, $snmp_community, $snmp_version, $mib) {
$cmd = "snmpwalk -c {$snmp_community} -v {$snmp_version} {$address} -m {$mib}";
exec($cmd, $output);
return $output;
}
// return the oid and pass the array by ref
// or return false on failure
function convert_snmpwalk_line_to_array($line, &$arr) {
if (preg_match('/(.*) = (.*): (.*)/', $line, $matches) === 1) {
$arr = array(
'type' => $matches[2],
'value' => $matches[3],
);
return $matches[1];
}
return false;
}
Now, you can put this in a file in your $USER1$ directory (/usr/local/nagios/libexec) named check_multi_snmpwalk.php and make sure it's executable chmod +x /usr/local/nagios/libexec/check_multi_snmpwalk.php.
Finally, all we need to do is define a command for Nagios to pick it up and use it! Something like the following should suffice:
define command {
command_name check_multi_snmpwalk
command_line $USER1$/check_multi_snmpwalk.php $ARG1$ $ARG2$ $ARG3$ $ARG4$
}
Now you should be able to specify the file you want the JSON to be output to in ARG1, and then each other argument needs to contain the host address, the snmp community, the snmp version and the mib you want to walk.
So, for example:
define service {
host_name localhost
service_description Multi SNMP Walk
use local-service
check_command check_multi_snmpwalk!/tmp/jsonfile!192.168.1.10,community,1,all!192.168.1.11,community,2c,all!!
register 1
}
Now you're saying "Okay, thats all great, but what does it do?!"
I'm glad you asked! This is what it does:
Grabbing some input from the user (what are we snmp walking?)
Executing an snmpwalk (and saving the output) for each host specified
Converting the snmpwalk output to an easy-to-read array
Aggregating each host's snmpwalk easy-to-read array into a giant array
Converting the giant array to JSON
Writing the JSON to the file specified
Returning an OK Status for Nagios with a message stating how many hosts we processed!
A few notes:
This plugin will take a while to run no matter how many hosts you specify, so you may want to consider running it from a cron job instead of a Nagios check
This plugin does NOT conform to the plugin guidelines I linked to earlier, but it was still a fun little project
Hope this helped!

How to list files in folder

How can I list all files inside a folder with Meteor.I have FS collection and cfs:filesystem installed on my app. I didn't find it in the doc.
Another way of doing this is by adding the shelljs npm module.
To add npm modules see: https://github.com/meteorhacks/npm
Then you just need to do something like:
var shell = Meteor.npmRequire('shelljs');
var list = shell.ls('/yourfolder');
Shelljs docs:
https://github.com/arturadib/shelljs
The short answer is that FS.Collection creates a Mongo collection that you can treat like any other, i.e., you can list entries using find().
The long answer...
Using cfs:filesystem, you can create a mongo database that mirrors a given folder on the server, like so:
// in lib/files.js
files = new FS.Collection("my_files", {
stores: [new FS.Store.FileSystem("my_files", {"~/test"})] // creates a ~/test folder at the home directory of your server and will put files there on insert
});
You can then access this collection on the client to upload files to the server to the ~test/ directory:
files.insert(new File(['Test file contents'], 'my_test_file'));
And then you can list the files on the server like so:
files.find(); // returns [ { createdByTransform: true,
_id: 't6NoXZZdx6hmJDEQh',
original:
{ name: 'my_test_file',
updatedAt: (Date)
size: (N),
type: '' },
uploadedAt: (Date),
copies: { my_files: [Object] },
collectionName: 'my_files'
}
The copies object appears to contain the actual names of the files created, e.g.,
files.findOne().copies
{
"my_files" : {
"name" : "testy1",
"type" : "",
"size" : 6,
"key" : "my_files-t6NoXZZdx6hmJDEQh-my_test_file", // This is the name of the file on the server at ~/test/
"updatedAt" : ISODate("2015-03-29T16:53:33Z"),
"createdAt" : ISODate("2015-03-29T16:53:33Z")
}
}
The problem with this approach is that it only tracks the changes made through the Collection; if you add something manually to the ~/test directory, it won't get mirrored into the Collection. For instance, if on the server I run something like...
mkfile 1k ~/test/my_files-aaaaaaaaaa-manually-created
Then I look for it in the collection, it won't be there:
files.findOne({"original.name": {$regex: ".*manually.*"}}) // returns undefined
If you just want a straightforward list of files on the server, you might consider just running an ls. From https://gentlenode.com/journal/meteor-14-execute-a-unix-command/33 you can execute any arbitrary UNIX command using Node's child_process.exec(). You can access the app root directory with process.env.PWD (from this question). So in the end if you wanted to list all the files in your public directory, for instance, you might do something like this:
exec = Npm.require('child_process').exec;
console.log("This is the root dir:");
console.log(process.env.PWD); // running from localhost returns: /Users/me/meteor_apps/test
child = exec('ls -la ' + process.env.PWD + '/public', function(error, stdout, stderr) {
// Fill in this callback with whatever you actually want to do with the information
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if(error !== null) {
console.log('exec error: ' + error);
}
});
This will have to run on the server, so if you want the information on the client, you'll have to put it in a method. This is also pretty insecure, depending on how you structure it, so you'd want to think about how to stop people from listing all the files and folders on your server, or worse -- running arbitrary execs.
Which method you choose probably depends on what you're really trying to accomplish.

Redirect user to regional language site version by knowing the ip of users Drupal 7

We are basically developing a Drupal 7 site with multiple language support.
Users should be redirected to regional translated pages basing on their IP.
I have tried using the following modules, but they didn't help to achieve what I wanted.
Internalization
IP to Locale
How can I redirect users to a specific page basing on their IP?
I have added a module for the same... just adding the code. With little modifications it can be configured for any no of languages and options.
I am using APIs from http://ipinfodb.com/.
ip2locationlite.class.php -> file can be downloaded from this link "http://ipinfodb.com/ip_location_api.php". The file consists of a very simple class, just used for calling webservice provided by http://ipinfodb.com/ and can be avoided by using your own class with file_get_contents.
I used for only chinese.
/** Author : Sunny Jhunjhunwala (sunny.jhunjhunwala#sourcen.com)
* #file - the file basically uses the php api provided by ipinfodb to get user's country
*/
/**
* Implements hook_init().
* Only for the first time checks if user is from china or not, if yes then redirect user to chinese version of the site.
*/
function dw_ip2location_init() {
if (!(array_key_exists('visited', $_COOKIE)) && empty($GLOBALS['user']->uid)) {
// Set the cookie to check if the user is new or existing.
setcookie("visited", 1, time() + (10 * 365 * 24 * 60 * 60));
include_once ('ip2locationlite.class.php');
$ipLite = new ip2location_lite;
$ipLite->setKey('a00740f71ae6ed8db250cb4c3a8ecdac672b5eae4d2a28c06284aa5461d0636d');
// #TODO : remove the below if-else while moving to production.
if (isset($_GET['ip2location'])) {
$locations = $ipLite->getCountry($_GET['ip2location']);
} else {
$locations = $ipLite->getCountry($_SERVER['REMOTE_ADDR']);
}
if (!empty($locations) && is_array($locations)) {
// Checking if the user if from china and redirecting.
if ($locations['countryCode'] == 'CN' || $locations['countryName'] == 'china') {
$path = $_GET['q'];
$translations = i18n_get_path_translations($path);
$language = i18n_language_interface();
if($language->prefix != 'cn' ) {
global $base_url;
if(!drupal_is_front_page() && array_key_exists('zh-hans', $translations)) {
drupal_goto( $base_url . '/cn/' . $translations['zh-hans']['href'], array('absolute' => true));
}
else {
drupal_goto( $base_url . '/cn/', array('absolute' => true));
}
}
}
}
}
}

Reflection with Powershell

I have a set of .NET Assemblies (all under the same directory) and some of those contain classes which implement an abstract class. I would like a Powershell script to find all the classes which implement my abstract class, and execute a method on each of them.
Does anybody have an idea on how to do this?
Thanks!
Here's a little function you might want to try.. (I haven't tested it yet, as I don't have any criteria to test this with easily..)
It can be used by supplying the paths (one or more full or relative paths separated by commas) on the command line like this
CheckForAbstractClassInheritance -Abstract System.Object -Assembly c:\assemblies\assemblytotest.dll, assemblytotest2.dll
or from the pipeline
'c:\assemblies\assemblytotest.dll','assemblytotest2.dll' | CheckForAbstractClassInheritance -Abstract System.Object
or with fileinfo objects from Get-Childitem (dir)
dir c:\assemblies *.dll | CheckForAbstractClassInheritance -Abstract System.Object
Tweak as needed..
function CheckForAbstractClassInheritance()
{
param ([string]$AbstractClassName, [string[]]$AssemblyPath = $null)
BEGIN
{
if ($AssemblyPath -ne $null)
{
$AssemblyPath | Load-AssemblyForReflection
}
}
PROCESS
{
if ($_ -ne $null)
{
if ($_ -is [FileInfo])
{
$path = $_.fullname
}
else
{
$path = (resolve-path $_).path
}
$types = ([system.reflection.assembly]::ReflectionOnlyLoadFrom($path)).GetTypes()
foreach ($type in $types)
{
if ($type.IsSubClassOf($AbstractClassName))
{
#If the type is a subclass of the requested type,
#write it to the pipeline
$type
}
}
}
}
}
The same way as you do it with c# but with PowerShell syntax.
Take a look at Assembly.GetTypes and Type.IsSubclassOf.

Resources