Magento 2 – Area code not set when running script via command line CLI

I have created module for exporting my product data to script outside of Magento2.

This is my Data.php

<?php namespace Oktarin\Nabavanet\Helper;  class Data extends \Magento\Framework\App\Helper\AbstractHelper {    protected $  markup=1.03;   protected $  markup_extra=1.02;   protected $  price_limit=1500.00;   protected $  pricefile;   protected $  prices;   protected $  pdv=0.25;   protected $  base_url="https://domain.com/index.php/catalog/product/view/id/";   protected $  base_image_url="https://domain.com/pub/media/catalog/product";   protected $  shipping_cost=35.00;   protected $  cats;   protected $  appState; /*   public function __construct(\Magento\Framework\App\Helper\Context $  context,\Magento\Framework\App\State $  state) {     $  this->appState = $  state;      parent::__construct($  context);   }      public function execute() {     $  originalArea = $  this->state->getAreaCode();     $  this->appState->setAreaCode('frontend');     //reset original code     $  this->appState->setAreaCode($  originalArea);   } */    public function getProductCollection()     {         $  collection = $  this->_productCollectionFactory->create();         return $  collection;     } // end of function getProductCollection     public function makeXml(){ /* */   //  $  originalArea = $  this->state->getAreaCode();       $  objectManager = \Magento\Framework\App\ObjectManager::getInstance();     $  this->appState= $  objectManager->create('Magento\Framework\App\State');     $  this->appState->setAreaCode('frontend');     $  productCollection = $  objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');     $  collection = $  productCollection->create()                 ->addAttributeToSelect('*')                // ->addAttributeToFilter('sku', array('like' => '%702638%'))                 ->load();  $  product=array();     foreach ($  collection as $  product_data){       if(!empty($  product_data->getEntity_id())){           //Load the product categories         $  categories1 = $  product_data->getCategoryIds();         //Select the last category in the list         $  categoryId = end($  categories1);         $  categoryObject=\Magento\Framework\App\ObjectManager::getInstance();         $  category=$  categoryObject->create('Oktarin\Nabavanet\Helper\CategoryTree');         $  categoryTreepath=$  category->getTreeByCategoryId($  categoryId);          if(!empty($  product_data->getspecial_price())){             $  price=$  product_data->getspecial_price();             $  regular_price=$  product_data->getprice();          }         else{           $  price=$  product_data->getprice();           $  regular_price=false;         }          // Dostupnost proizvoda           switch($  product_data->getproduct_availability()){               case "3929":                 // Po narudžbi                 $  availability="Po narudžbi";                 break;               case "3930":                 // Na stanju                 $  availability="Raspoloživo";                 break;               case "3931":                 // Zalihe pri kraju                 $  availability="Raspoloživost potrebno provjeriti";                 break;                   }            $  product[]=array(             "internal_product_id" => $  product_data->getEntity_id(),             "sku" => $  product_data->getsku(),             "ean" => $  product_data->getean(),             "name" => $  product_data->getName(),             "url" => $  this->base_url.$  product_data->getEntity_id()."/s/".$  product_data->geturl_key()."/",             "availability" => $  availability,             "category" => $  categoryTreepath,             "image_url" => $  this->base_image_url.$  product_data->getimage(),             "additional_image_url" => $  this->base_image_url.$  product_data->getsmall_image(),             "description" => $  product_data->getshort_description(),             "shipping_cost" => $  this->shipping_cost,             "regular_price" => $  regular_price,             "brand" => $  product_data->getbrand(),             "part_number" => $  product_data->getpart_number(),             "warranty" => $  product_data->getgarancija_proizvoda(),             "price" => $  price,             "specialPrice" => $  product_data->getspecial_price(),             "tehnickaSpecifikacija" => $  product_data->getdescription()           );         } // end of of entity_id isnt empty       } // end of foreach          //reset original code     $  this->appState->setAreaCode($  originalArea);         return $  product;   } // end of function makeXml  } // end class 

Method makeXml() I am calling from another script in file nabavanet-export.php that is designed to be run from cron/CLI/command line:

#!/usr/bin/php <?php (PHP_SAPI !== 'cli' || isset($  _SERVER['HTTP_USER_AGENT'])) && die('cli only'); require_once __DIR__ . "/include.php";  $  nabavanet=new Xml();    /* MAGENTO start */   // calling on Magento Helpers   use Magento\Framework\App\Bootstrap;   require '../app/bootstrap.php';   $  params = $  _SERVER;   $  bootstrap = Bootstrap::create(BP, $  params);   $  obj = $  bootstrap->getObjectManager();   $  nabava = $  obj->get('\Oktarin\Nabavanet\Helper\Data');   // end of Magento Helpers   /* END Magento */  try{   $  filename="nabavaexport";   $  xml=$  nabavanet->createNabavanetXMLfile($  nabava->createXml(),$  filename); if($  xml==1){     echo "XML ".$  filename.".xml generated!\n";   copy($  filename.".xml", "../nabavanet/".$  filename.".xml"); } else{     echo "XML ".$  filename.".xml not generated\n"; }   } catch (PDOException $  e) {     // detaljan ispis grešaka slanjem     // PDOException objekta preko varijable $  e     // PDO objekta preko varijable $  db     // PDOStatement objekta preko varijable $  stmt     showPDOErrors($  e, $  db_read, $  stmt_read);     showPDOErrors($  e, $  db_write, $  stmt_write); }             ?> 

Script nabavanet-export.php was working fine when run through browser, however when I run it through command line I get this:

Fatal error: Uncaught Magento\Framework\Exception\LocalizedException: Area code is not set in /usr/www/users/shopyb/vendor/magento/framework/App/State.php:152 Stack trace: #0 /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php(173): Magento\Framework\App\State->getAreaCode() #1 /usr/www/users/shopyb/generated/code/Magento/Framework/Session/Generic/Interceptor.php(50): Magento\Framework\Session\SessionManager->start() #2 /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php(130): Magento\Framework\Session\Generic\Interceptor->start() #3 /usr/www/users/shopyb/generated/code/Magento/Framework/Session/Generic/Interceptor.php(14): Magento\Framework\Session\SessionManager->__construct(Object(Magento\Framework\App\Request\Http), Object(Magento\Framework\Session\SidResolver\Proxy), Object(Magento\Framework\Session\Config), Object(Magento\Framework\Session\SaveHandler), Object(Magento\Framework\Session\Validator), Object(Magento\Framework\Session\Storage), Object(Magento\Framework\Stdlib\C in /usr/www/users/shopyb/vendor/magento/framework/Session/SessionManager.php on line 175 

As you can see I have tried implementing fix as said many times:

  public function __construct(\Magento\Framework\App\State $  state, $  name=null) {     $  this->appState = $  state;      parent::__construct($  name);   } 

But this also generated error

So I have tried modifing it like this but without success:

  public function __construct(\Magento\Framework\App\Helper\Context $  context,\Magento\Framework\App\State $  state) {     $  this->appState = $  state;      parent::__construct($  context);   } 

I hope someone can give me pointers how to make file nabavanet-export.php run as command line. I need that outside script because it is depending on other methods required for generating xml.

tshark filtering out same vlan traffic from command line

I am looking for help on how I can filter out same VLAN traffic(i.e. src IPs 10.1.1.0/24 and dst IPs 10.1.1.0/24) out of a capture file and output all other traffic to a txt file.

I am using a batch file to process all the captures using tshark in a directory and want to use a display filter to remove this “same VLAN” traffic to reduce the size of the output.

Here is the batch file I am using:

@echo off  set cDate=captureday set cap_files="*.pcapng" set cap_folder="D:\caps\%cDate%" set outfile-udp=D:\conversations\cap-UDP-%cDate%.txt set outfile-tcp=D:\conversations\cap-TCP-%cDate%.txt set tshark_cmd="c:\Program Files\Wireshark\tshark" set tshark_udp=-Y "!(ipv6)" -q -z conv,udp set tshark_tcp=-Y "!(ip.src in {10.1.1.0/24} && ip.dst in {10.1.1.0/24})" -q -z conv,tcp  echo. > %outfile-udp% echo. > %outfile-tcp%  for /r %cap_folder% %%f in (%cap_files%) do (     echo Processing File: %%f      REM echo == File:  %%f >> %outfile%     %tshark_cmd%  -r %%f %tshark_udp% >> %outfile-udp%     %tshark_cmd%  -r %%f %tshark_tcp% >> %outfile-tcp% )  echo. echo Results in: %outfile-udp%  echo Results in: %outfile-tcp% 

This doesn’t seem to work however so I was wondering if someone out there has done this before and can tell me what I am doing incorrectly here. Basically I am still getting this 10.1.1.0/24 <-> 10.1.1.0/24 traffic.

This is for already existing captures. I have already got a capture filter running this ignores this traffic.

This is an example of the output of the text file:


================================================================================ TCP Conversations Filter:<No Filter>                                                            |       <-      | |       ->      | |     Total     |    Relative    |   Duration   |                                                            | Frames  Bytes | | Frames  Bytes | | Frames  Bytes |      Start     |              | 10.1.1.154:51087        <-> 10.1.1.202:5482           20016   1417372   13477  20140238   33493  21557610     4.393919000       124.2292 10.1.1.154:51088        <-> 10.1.1.201:5482           17479   1170181   11871  17779866   29350  18950047    10.602867000       118.3747 10.1.1.154:52765        <-> 10.1.1.194:2021            7346    584098    4201    338242   11547    922340     0.187889000       128.7159 10.1.1.154:57613        <-> 10.1.1.193:2021            7197    572273    4111    331079   11308    903352     0.182195000       128.7268 10.1.1.154:52120        <-> 10.1.1.192:2021            7180    570921    4104    330495   11284    901416     0.136573000       128.7624 10.1.1.154:61285        <-> 10.1.1.190:2021            7126    566585    4066    327231   11192    893816     0.182070000       128.7277 10.1.1.154:52738        <-> 10.1.1.191:2021            6301    500987    3602    289742    9903    790729    18.821383000       110.0925 

Alternatively if there is a way just to delete out the lines the the source and destination IP’s using SED or findstr I would be happy to do this as well 😉

Many thanks in advance

Cheers

How to make updates to data and return list of updates without breaking Command query separation or DRY?

I have a use case to make updates to a slightly complex JSON object and then return the list of changes made (not the updated data). The process of finding the list of changes is extremely similar to the process of making the changes and it would bring in some redundancy if I chose to separate the two methods. So I’m wondering if there is a way to do this without choosing DRY over CQS and SRP.

Detect network traffic and execute command [on hold]

using kind of a dial-up connection, I was wondering if there is any option using Linux (Raspberry Pi as router) to detect incoming traffic on interface wlan0 (and maybe a specific device) so that a command can be executed:

I have two network interfaces on my Pi. One is used for the local WiFi network to be accessed by all my devices, while the traffic is routed to the second interface to the external gateway. That works fine. The issue is that it requires a login from time to time, which is an issue for Alexa devices and bothers me in general. Therefore, I need to execute a script, when a client (of wlan0) wants to use the internet. Any suggestions?

handle space in filename for imagemagic command

I am trying to resize image based on file name and size :

import subprocess import os  os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hiren.settings')  from hiren.settings import BASE_DIR   def resize(image_file, size):     os.chdir(BASE_DIR + '/convert/')     file_name = os.path.splitext(os.path.basename(image_file))[0]     file_ext = os.path.splitext(os.path.basename(image_file))[1]      for i in size:         cmd = ['convert', image_file, '-resize', i, file_name + i + file_ext]         # subprocess.check_call(f'convert {image_file} -resize {i} {file_name + i + file_ext}', shell=True)         subprocess.check_call(cmd, shell=True)   resize(BASE_DIR + '/convert/x/images 2.jpeg', ['308x412', '400x400']) 

then here is errors :

Traceback (most recent call last):   File "/home/../image.py", line 26, in <module>     resize(BASE_DIR + '/convert/x/images_2.jpeg', ['308x412', '400x400'])   File "/home/.../image.py", line 23, in resize     subprocess.check_call(cmd, shell=True)   File "/usr/lib/python3.6/subprocess.py", line 311, in check_call     raise CalledProcessError(retcode, cmd) Version: ImageMagick 6.9.7-4 Q16 x86_64 20170114 http://www.imagemagick.org subprocess.CalledProcessError: Command '['convert', '/home/../convert/x/images_2.jpeg', '-resize', '308x412', 'images_2308x412.jpeg']' returned non-zero exit status 1. Copyright: © 1999-2017 ImageMagick Studio LLC License: http://www.imagemagick.org/script/license.php Features: Cipher DPC Modules OpenMP  Delegates (built-in): bzlib djvu fftw fontconfig freetype jbig jng jpeg lcms lqr ltdl lzma openexr pangocairo png tiff wmf x xml zlib Usage: convert-im6.q16 [options ...] file [ [options ...] file ...] [options ...] file 

I am using python 3.6. Now how can I handle empty space or space less file name ?