Linux on Windows: WSL with Desktop Environment via RDP

Linux on Windows: WSL with Desktop Environment via RDP

WSL (Windows Subsystem for Linux) is very common these days especially with the new that Windows will ship a Linux kernel with WSL 2.0!

Installing a Linux distro as WSL is easy via the Microsoft App Store and there are plenty of tutorials out there for it.

Most of the resources cover the access via Shell, Terminal, Hyperterminal or other console based tools to the WSL.
Running GUI software is possible and there are resources describing how to archieve this via VcXsrv (see chapter in this post of mine).

But what if you:

Want to have/access a Desktop environment on WSL?

You can use any Desktop Environment you want, I will be using Xfce in this example because it is lightweight.

Here is the quick rundown of all commands and steps, explained in the sections below. One is for Kali Linux, the other is for the Debian based distros (Debian, Ubuntu, …).

For Kali:

sudo apt update && sudo apt -y upgrade
sudo apt -y install kali-desktop-xfce
sudo apt-get install xrdp
sudo cp /etc/xrdp/xrdp.ini /etc/xrdp/xrdp.ini.bak
sudo sed -i 's/3389/3390/g' /etc/xrdp/xrdp.ini
sudo sed -i 's/max_bpp=32/#max_bpp=32\nmax_bpp=128/g' /etc/xrdp/xrdp.ini
sudo sed -i 's/xserverbpp=24/#xserverbpp=24\nxserverbpp=128/g' /etc/xrdp/xrdp.ini
sudo /etc/init.d/xrdp start

For other debian based distros:

sudo apt update && sudo apt -y upgrade
sudo apt -y install xfce4
sudo apt-get install xrdp
sudo cp /etc/xrdp/xrdp.ini /etc/xrdp/xrdp.ini.bak
sudo sed -i 's/3389/3390/g' /etc/xrdp/xrdp.ini
sudo sed -i 's/max_bpp=32/#max_bpp=32\nmax_bpp=128/g' /etc/xrdp/xrdp.ini
sudo sed -i 's/xserverbpp=24/#xserverbpp=24\nxserverbpp=128/g' /etc/xrdp/xrdp.ini
sudo /etc/init.d/xrdp start

And then connect via RDP localhost:3390 to your desktop.

Connect to WSL DE via Xrdp

Login to WSL DE

Detailed steps

Updating the system and installing Xfce4

sudo apt update && sudo apt -y upgrade
sudo apt -y install kali-desktop-xfce
sudo apt -y install xfce4

The first command updates the source list and the packages. Always important, I will not explain this.
The sudo apt -y install kali-desktop-xfce installs a Kali Linux specific version of Xfce4 and sudo apt -y install xfce4 will install the Xfce4 package for debian based distros.

Installing Xrdp

sudo apt-get install xrdp

Xrdp is an open source remote desktop solution and also very lightweight and easy to configure. This command will install the package and setup the default configuration with port 3389.

Configuring Xrdp

sudo cp /etc/xrdp/xrdp.ini /etc/xrdp/xrdp.ini.bak
sudo sed -i 's/3389/3390/g' /etc/xrdp/xrdp.ini
sudo sed -i 's/max_bpp=32/#max_bpp=32\nmax_bpp=128/g' /etc/xrdp/xrdp.ini
sudo sed -i 's/xserverbpp=24/#xserverbpp=24\nxserverbpp=128/g' /etc/xrdp/xrdp.ini
sudo /etc/init.d/xrdp start

Copy the config file as backup before the changes, change the port from 3389 to 3390 and for quality reasons increase the bpp from 24 to 128. You can play with those settings but since this is a local connection, the speed should not be worse with those settings.
And finally restarting the xrdp service to apply the changes.

Now you can connect via localhost:3390 and the credentials of your WSL account via RDP! ?

Desktop of WSL via xrdp

Why the port change from 3389 to 3390?

Two reasons: security and sometimes port 3389 is used by a process on wsl and you get the message

Your computer could not connect to another console session on the remote computer because you already have a console session in progress.

Benefits of RDP here

Even though you can run GUI software via XServer in a window, sometimes it is more convenient to have the full desktop environment accessible.
Also you can restore a previously disconnected session easily and do not have to close the console (let processes running for example).

Source : Linux on Windows: WSL with Desktop Environment via RDP – DEV Community ?‍??‍?

Install and Configure pfBlockerNg for DNS Black Listing in pfSense Firewall

Install and Configure pfBlockerNg for DNS Black Listing in pfSense Firewall

In an earlier article the installation of a powerful FreeBSD based firewall solution known as pfSense was discussed. pfSense, as mentioned in the earlier article, is a very powerful and flexible firewall solution that can make use of an old computer that may be laying around not doing much.

This article is going to talk about a wonderful add-on package for pfsense called pfBlockerNG.

pfBlockerNG is a package that can be installed in pfSense to provide the firewall administrator with the ability to extend the firewall’s capabilities beyond the traditional stateful L2/L3/L4 firewall.

As the capabilities of attackers and cyber criminals continues to advance, so must the defenses that are put in place to thwart their efforts. As with anything in the computing world, there isn’t a one solution fixes all product out there.

pfBlockerNG provides pfSense with the ability for the firewall to make allow/deny decisions based items such as the geolocation of an IP address, the domain name of a resource, or the Alexa ratings of particular websites.

The ability to restrict on items such as domain names is very advantageous as it allows administrators to thwart attempts of internal machines attempting to connect out to known bad domains ( in other words, domains that may be known to have malware, illegal content, or other insidious pieces of data).

This guide will walk through configuring a pfSense firewall device to use the pfBlockerNG package as well as some basic examples of domain block lists that can be added/configured into the pfBlockerNG tool.

Requirements

This article will make a couple of assumptions and will build off of the prior installation article about pfSense. The assumptions will be as follows:

  • pfSense is already installed and has no rules currently configured (clean slate).
  • The firewall only has a WAN and a LAN port (2 ports).
  • The IP scheme being used on the LAN side is 192.168.0.0/24.

It should be noted that pfBlockerNG can be configured on an already running/configured pfSense firewall. The reason for these assumptions here is simply for sanity’s sake and many of the tasks that will be completed, can still be done on a non-clean slate pfSense box.

Lab Diagram

The image below is the lab diagram for the pfSense environment that will be used in this article.

pfSense Network Diagram

pfSense Network Diagram

Install pfBlockerNG for pfSense

With the lab ready to go, it is time to begin! The first step is to connect to the web interface for the pfSense firewall. Again this lab environment is using the 192.168.0.0/24 network with the firewall acting as the gateway with an address of 192.168.0.1. Using a web browser and navigating to ‘https://192.168.0.1’ will display the pfSense login page.

Some browsers may complain about the SSL certificate, this is normal since the certificate is self signed by the pfSense firewall. You can safely accept the warning message and if desired, a valid certificate signed by a legitimate CA can be installed but is beyond the scope of this article.

pfSense SSL Warning

pfSense SSL Warning

After successfully clicking ‘Advanced’ and then ‘Add Exception…’, click to confirm the security exception. The pfSense login page will then display and allow for the administrator to log in to the firewall appliance.

pfSense Login Window

pfSense Login Window

Once logged in to the main pfSense page, click on the ‘System’ drop down and then select ‘Package Manager’.

pfSense Package Manager

pfSense Package Manager

Clicking this link will change to the package manager window. The first page to load will be all the currently installed packages and will be blank (again this guide is assuming a clean pfSense install). Click on the text ‘Available Packages’ to be provided a list of installable packages for pfSense.

pfSense Available Packages

pfSense Available Packages

Once the ‘Available Packages’ page loads, type ‘pfblocker’ into the ‘Search term’ box and click the ‘Search’. The first item that is returned should be pfBlockerNG. Locate the ‘Install’ button to the right of the pfBlockerNG description and click the ‘+’ to install the package.

The page will reload and request the administrator confirm the installation by clicking ‘Confirm’.

Install pfBlockerNG for pfSense

Install pfBlockerNG for pfSense

Once confirmed, pfSense will begin to install pfBlockerNG. Do not navigate away from the installer page! Wait until the page displays successful installation.

pfBlockerNG Installation

pfBlockerNG Installation

Once the installation has been completed, the pfBlockerNG configuration can begin. The first task that needs to be completed though is some explanations on what is going to happen once pfBlockerNG is configured properly.

Once pfBlockerNG is configured, DNS requests for websites should be intercepted by the pfSense firewall running the pfBlockerNG software. pfBlockerNG will then have updated lists of known bad domains that are mapped to a bad IP address.

The pfSense firewall needs to intercept DNS requests in order to be able to filter out bad domains and will use a local DNS resolver known as UnBound. This means clients on the LAN interface need to use the pfSense firewall as the DNS resolver.

If the client requests a domain that is on pfBlockerNG’s block lists, then pfBlockerNG will return a false ip address for the domain. Let’s begin the process!

pfBlockerNG Configuration for pfSense

The first step is to enable the UnBound DNS resolver on the pfSense firewall. To do this, click on the ‘Services’ drop down menu and then select ‘DNS Resolver’.

pfSense DNS Resolver

pfSense DNS Resolver

When the page reloads, the DNS resolver general settings will be configurable. This first option that needs to be configured is the checkbox for ‘Enable DNS Resolver’.

The next settings are to set the DNS listening port (normally port 53), setting the network interfaces that the DNS resolver should listen on (in this configuration, it should be the LAN port and Localhost), and then setting the egress port (should be WAN in this configuration).

pfSense Enable DNS Resolver

pfSense Enable DNS Resolver

Once the selections have been made, be sure to click ‘Save’ at the bottom of the page and then click the ‘Apply Changes’ button that will appear at the top of the page.

The next step is the first step in configuration of pfBlockerNG specifically. Navigate to the pfBlockerNG configuration page under the ‘Firewall’ menu and then click on ‘pfBlockerNG’.

pfBlockerNG Configuration

pfBlockerNG Configuration

Once pfBlockerNG has loaded, click on the ‘DNSBL’ tab first to begin setting up the DNS lists before activating pfBlockerNG.

Setup DNS Lists

Setup DNS Lists

When the ‘DNSBL’ page loads, there will be a new set of menus beneath the pfBlockerNG menus (highlighted in green below). The first item that needs to be addressed is the ‘Enable DNSBL’ check box (highlighted in green below).

This check box will require the UnBound DNS resolver be used on the pfSense box in order to inspect dns requests from LAN clients. Don’t worry UnBound was configured earlier but this box will need to be checked! The other item that needs to be filled in on this screen is the ‘DNSBL Virtual IP’.

This IP needs to be in the private network range and not a valid IP on the network in which pfSense is being used. For example, a LAN network on 192.168.0.0/24 could use an IP of 10.0.0.1 as it is a private IP and isn’t part of the LAN network.

This IP will be used to gather statistics as well as monitor domains that are being rejected by pfBlockerNG.

Enable DNSBL for pfSense

Enable DNSBL for pfSense

Scrolling down the page, there are a few more settings worth mentioning. The first is the ’DNSBL Listening Interface’. For this setup, and most setups, this setting should be set to ‘LAN’.

The other setting is ‘List Action’ under ‘DNSBL IP Firewall Settings’. This setting determines what should happen when a DNSBL feed provides IP addresses.

The pfBlockerNG rules can be setup to do any number of actions but most likely ‘Deny Both’ will be the desired option. This will prevent inbound and outbound connections to the IP/domain on the DNSBL feed.

Configure DNSBL for pfSense

Configure DNSBL for pfSense

Once the items have been selected, scroll to the bottom of the page and click the ‘Save’ button. Once the page reloads, it is time to configure the DNS Block Lists that should be used.

pfBlockerNG provides the administrator with two options that can be configured independently or together depending on the administrator’s preference. The two options are manual feeds from other web pages or EasyLists.

To read more about the different EasyLists, please visit the project’s homepage: https://easylist.to/

Configure pfBlockerNG EasyList

Let’s discuss and configure the EasyLists first. Most home user’s will find these lists to be sufficient as well as the least administratively burdensome.

The two EasyLists available in pfBlockerNG are ‘EasyList w/o Element Hiding’ and ‘EasyPrivacy’. To use one of these lists, first click on the ‘DNSBL EasyList’ at the top of the page.

Configure DNSBL EasyList

Configure DNSBL EasyList

Once the page reloads, the EasyList configuration section will be made available. The following settings will need to be configured:

  • DNS Group Name – User’s choice but no special characters
  • Description – User’s choice, special characters allowed
  • EasyList Feeds State – Whether the configured list is used
  • EasyList Feed – Which list to use (EasyList or EasyPrivacy) both can be added
  • Header/Label – User choice but no special characters
EasyList Configuration for pfSense

EasyList Configuration for pfSense

The next section is used to determine which parts of the lists will be blocked. Again these are all user preference and multiple can be selected if desired. The important settings in the ‘DNSBL – EasyList Settings’ are as follows:

  • Categories – User preference and multiple can be selected
  • List Action – Needs to be set to ‘Unbound’ in order to inspect DNS requests
  • Update Frequency – How often pfSense will update the list of bad sites
DNSBL EasyList Settings

DNSBL EasyList Settings

When the EasyList settings are configured to the user’s preferences, be sure to scroll to the bottom of the page and click the ‘Save’ button. Once the page reloads, scroll to the top of the page and click on the ‘Update’ tab.

Once on the update tab, check the radio button for ‘Reload’ and then check the radio button for ‘All’. This will run through a series of web downloads to obtain the block lists selected on the EasyList configuration page earlier.

This must be done manually otherwise lists won’t be downloaded until the scheduled cron task. Anytime changes are made (lists added or removed) be sure to run this step.

Update EasyList Settings

Update EasyList Settings

Watch the log window below for any errors. If everything went to plan, client machines on the LAN side of the firewall should be able to query the pfSense firewall for known bad sites and receive bad ip addresses in return. Again the client machines must be set to use the pfsense box as their DNS resolver though!

Check Nslookup for Errors

Check Nslookup for Errors

Notice in the nslookup above that the url returns the false IP configured earlier in the pfBlockerNG configurations. This is the desired outcome. This would result in any request to the URL ‘100pour.com’ being directed to the false IP address of 10.0.0.1.

Configure DNSBL Feeds for pfSense

In contrast to the AdBlock EasyLists, there is also the ability to use other DNS Black Lists within pfBlockerNG. There are hundreds of lists that are used to track malware command and control, spyware, adware, tor nodes, and all sorts of other useful lists.

These lists can often be pulled into pfBlockerNG and also used as further DNS Black Lists. There are quite a few resources that provide useful lists:

  • https://forum.pfsense.org/index.php?topic=114499.0
  • https://forum.pfsense.org/index.php?topic=102470.0
  • https://forum.pfsense.org/index.php?topic=86212.0

The links above provide threads on pfSense’s forum where members have posted a large collection of the list’s they use. Some of the author’s favorite lists include the following:

  • http://adaway.org/hosts.txt
  • http://www.malwaredomainlist.com/hostslist/hosts.txt
  • http://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&mimetype=plaintext
  • https://zeustracker.abuse.ch/blocklist.php?download=domainblocklist
  • https://gist.githubusercontent.com/BBcan177/4a8bf37c131be4803cb2/raw

Again there are tons of other lists and the author strongly encourages that individuals seek out more/other lists. Let’s continue with the configuration tasks though.

The first step is to go into pfBlockerNG’s configuration menu again through ‘Firewall->pfBlockerNG->DSNBL’.

Once on the DNSBL configuration page again, click on the ‘DNSBL Feeds’ text and then click on the ‘Add’ button once the page refreshes.

Configure DNSBL Feeds for pfSense

Configure DNSBL Feeds for pfSense

The add button will allow the administrator to add more lists of bad IP addresses or DNS names to the pfBlockerNG software (the two items already in the list are the author’s from testing). The add button brings the administrator to a page where DNSBL lists can be added to the firewall.

DNS BadList Configuration

DNS BadList Configuration

The important settings in this output are the following:

  • DNS Group Name – User chosen
  • Description – Useful for keeping groups organized
  • DNSBL Settings – These are the actual lists
    • State – Whether that source is used or not and how it is obtained
    • Source – The link/source of the DNS Black List
    • Header/Label – User choice; no special characters
  • List Action – Set to Unbound
  • Update Frequency – How often the list should be updated

Once these settings have been set, click the save button down at the bottom of the page. As with any changes to pfBlockerNG, the changes will take effect on the next scheduled cron interval or the administrator can manually force a reload by navigating to the ‘Update’ tab, click the ‘Reload’ radio button, and then click the ‘All’ radio button. Once those are selected, click the ‘Run’ button.

DNSBL Feeds Update Settings

DNSBL Feeds Update Settings

Watch the log window below for any errors. If everything went to plan, test that the lists are working by simply attempting to do an nslookup from a client on the lan side to one of the domains listed in one of the text files used in the DNSBL configuration.

Watch DNS Lookup

Watch DNS Lookup

As can be seen in the output above, the pfSense device is returning the virtual IP address that was configured in pfBlockerNG as the bad IP for the black list domains.

At this point the administrator could continue tuning the lists by adding more lists or creating custom domain/IP lists. pfBlockerNG will continue to redirect these restricted domains to a fake IP address.

Source : Install and Configure pfBlockerNg for DNS Black Listing in pfSense Firewall

How to set up a VPN server on Windows 10

How to set up a VPN server on Windows 10

Do you need to create a VPN server? Here are the steps to set up a VPN server using the built-in Incoming Connection feature on Windows 10.

Setup VPN server on Windows 10

A virtual private network (VPN) is one of the most popular methods to access files and resources, such as apps, intranet websites, and printers using an encrypted connection from a remote location and through the internet.

Often companies use VPN to extend their private network to allow employees access resources through a public network as if they were directly connected into the company’s network.

Windows 10 like other versions of the OS has a feature called “Incoming Connection” that enables you to set up a VPN server to connect remotely to your home network to access your computer’s files and peripherals, and even other computers in the network.

In this guide, you’ll learn how to set up a VPN server on your Windows 10 computer without the need of extra software on the Home or Pro version of the OS.

How to find your IP address information

Before diving into the instructions, the first thing you need to know is your public IP address that has been assigned to you by your Internet Service Provider (ISP). You will need this information in order to contact your VPN server remotely.

To know your current public IP address, open your web browser, and using any search engine, do a search for “What’s my IP”, and your information should be listed in the first result.

If you’re setting up Incoming Connection in your home computer, you probably have a dynamic public IP address, which can change at any time. If this is the case, you’ll need to configure DDNS (Dynamic Domain Name System) in your router to avoid having to configure the VPN setup every time your public IP address changes.

Here are the instructions that will help you set up DDNS on your router. Remember that you can visit your router’s manufacturer website for more assistance to configure DDNS.

How to set up port forwarding on your router

To be able to connect through a public network, such as the internet, to your home VPN server, you’ll need to forward port 1723 (Point to Point Tunneling Protocol (PPTP)) to allow VPN connections.

Here are the instructions that will help you set up port forwarding on your router. Remember that you can visit your router’s manufacturer website for more assistance to configure Port Forwarding.

How to set up a VPN server on Windows 10

Once you have set up DDNS to use a domain name instead of a complicated IP address, and you forwarded port 1723, now you are ready to set up a VPN server on your device:

Use these steps to create a VPN server on Windows 10:

    1. Open Control Panel.
    2. Click on Network and Sharing Center.
    3. Using the left pane, click the Change adapter settings link.
      Network and Sharing Center
      Network and Sharing Center
    4. On “Network Connections,” open the File menu pressing the Alt key, and select the New Incoming Connection option.

      New Incoming Connection option on Windows 10

    5. Check the users you want to VPN access to your computer, and click the Next button.

      VPN user setup on Windows 10

      Alternatively, you can click the Add someone button to create a new VPN user:

      Create new VPN user on Windows 10

    6. Check the Through the Internet option.
    7. Click the Next button.

      Through the Internet

    8. In the networking software page, select Internet Protocol Version 4 (TCP/IPv4) option.
    9. Click the Properties button.

      Set up VPN on Windows 10 TCP/IP properties

    10. Check the Allow callers to access my local area network option.
    11. Under “IP address assignment,” click Specify IP addresses, and specify the number of clients allowed to access using a VPN connection. (You will do this by specifying an IP address range, and it’s recommended that you use high-order range of IP addresses to help avoid conflicts in the network with the IPs distributed by your router.)

      Incoming IP Properties for VPN access

      Quick Tip: To find out the range of IP addresses you can use, navigate to your router’s settings page, and look for the DHCP settings.
    12. Click the OK button.
    13. Click the Allow access button.
  1. Click the Close button to complete setting up the VPN server on Windows 10.

    VPN setup completed on Windows 10

How to allow VPN connections through the firewall

While configuring the Incoming Connection feature on Windows 10 should automatically open the necessary Windows Firewall ports, you want to make sure the firewall is properly configured.

Use these steps to allow VPN connections through the firewall on Windows 10:

  1. Open Start.
  2. Search for Allow an app through Windows Firewall, and click the top result to open the experience.
  3. Click the Change settings button.
  4. Scroll down and make sure Routing and Remote Access is allowed on Private and Public.

    VPN server firewall configuration on Windows 10

  5. click the OK button.

How to set up a VPN connection on Windows 10

After completing setting up the Windows 10 as a VPN server, you’ll need to configure the devices that will be accessing your local network remotely. You can set up any device, including your desktop, laptop, tablet, and even phone (e.g., Android and iPhone).

Here are the instructions to set up a VPN connection on Windows 10.

Once you set up a VPN connection on your computer, you’ll need to adjust the settings with these steps:

  1. Open Control Panel.
  2. Click on Network & Internet.
  3. Click on Network and Sharing Center.
  4. On the left pane, click the Change adapter settings link.
  5. Right-click the VPN adapter and select Properties.

    VPN Connection properties

  6. In the General tab, make sure you’re using the correct domain you created while configuring DDNS — or at least you’re using the correct public IP address.

    VPN Connection address properties

  7. Click on the Security tab.
  8. Under “Type of VPN,” select the Point to Point Tunneling Protocol (PPTP) option.
  9. Under “Data encryption,” select the Maximum strength encryption (disconnect if server declines) option.

    VPN Connection Security options on Windows 10

  10. Click the OK button.
  11. Click on the Networking tab.
  12. Uncheck the Internet Protocol Version 6 (TCP/IPv6) option.
  13. Check the Internet Protocol Version 4 (TCP/IPv4) option.
  14. Select the Internet Protocol Version 4 (TCP/IPv4) option.
  15. Click the Properties button.

    VPN Connection Networking options on Windows 10

  16. Click the Advanced button.

    VPN Connection TCP/IP properties on Windows 10

  17. Clear the Use default gateway on remote network option.

    Stop internet traffic through VPN connection

    Important: We’re disabling this option to prevent your web traffic to go through the remote connection, which can dramatically slow down your internet connection. However, if you’re looking to access the internet through a VPN connection, then don’t change this last setting.
  18. Click the OK button.
  19. Click the OK button again.
  20. Click the OK button once more.
  21. Open Settings.
  22. Click on Network & Internet.
  23. Click on VPN.
  24. Select the VPN connection option and click the Connect button.
    Windows 10 remote connection using VPN
    Windows 10 remote connection using VPN

While there are many solutions to allow users to connect remotely to a private network using a VPN connection, you can set up your own server with the tools built within Windows 10 without the need of extra software.

In addition, one of the best benefits of setting up a VPN server on your Windows 10 PC is that it’s not only secure and reliable, but it’s a great alternative for users who are still skeptical about cloud services to store their data. Even more, through a virtual private network, you can even access your device using remote desktop.

Source : How to set up a VPN server on Windows 10 • Pureinfotech

How to Restart or Shutdown a Remote Computer

How to Restart or Shutdown a Remote Computer

There will be times as a Windows Administrator that you will need to reboot or shutdown a remote computer or server.

In this tutorial, I’ll show you two easy methods for rebooting and shutting down remote computers.

The first method uses a built in Windows command and the second method uses PowerShell.

Check it out.

Windows Shutdown Command

Windows systems has a built in shutdown command that can be used to restart or shutdown local and remote computers.

The command is shutdown.

To use this command just open the windows command prompt and type shutdown.

To view the full list of command options type shutdown /? in the CMD window.

There are several command line switches, below I list the most useful options.

/s – Shutdown the computer

/r – restart computer

/m \\computer – Specify the remote computer

/l – Log off

/t xxx – Set the time out period before shutdown to xxx seconds

/c “comment” – Message to display on the screen before restart or shutdown

Now lets move onto some examples

Restart or Shutdown Examples with Command Line

In these examples, I’ll be on PC1 and will initiate a remote restart or shutdown on PC2.

I’ll be using the /r switch in these examples, you can change them to /s to shutdown instead of restart.

Example 1: Restart Remote Computer

By default, this will prompt the remote computer and give it about a minute before it restarts.

shutdown /r /m \\pc2

The pop up below is what a Windows 10 system will display.

Example 2: Restart With a Custom Message

You may want to display a custom message to the logged on users, to do that just use the /c command.

shutdown /m \\pc2  /c "The IT department has initiated a remote restart on your computer"

Below is the pop up on the remote computer with the custom message.

Example 3: Immediate Restart no Countdown

If you want to immediately restart with no countdown or message use this command.

shutdown /r /m \\pc2 /t 0

If you want a longer countdown just specify the seconds /t 60

Example 4: Log user off remote computer

If you just want to log a user off the remote computer use this command.

shutdown /l /m\\pc2

Restart or Shutdown with Powershell

Here are a few examples of how you can restart or shutdown computers with PowerShell.

The downside to PowerShell is it doesn’t have as many options as the shutdown command. There is no option to prompt users with a custom message or provide a countdown.

Example 1: Use Powershell to restart a computer

This command will immediately restart a remote computer. The -Force option will force a restart even if a user is logged on.

Restart-Computer -ComputerName REMOTE_COMPUTER_NAME -Force

Example 2: Use PowerShell to shutdown a computer

This command will shutdown a remote computer. Use the -Force to force a shutdown even if a user is logged on.

Stop-Computer -ComputerName REMOTE_COMPUTER_NAME -Force

Example 3: Use PowerShell to restart a list of computers

This is handy if you have several computers to restart. Just list all the computers you want in a text file and add that to the PowerShell command.

restart-computer (get-content c:\work\computers.txt)

Example 4: Use PowerShell to shutdown down two computers

Stop-Computer -ComputerName "Server01", "Server02"

Have fun!

See also:

How to View Open Files On Windows Server
How To Check Windows Server Uptime

Recommended Tool: SolarWinds Server & Application Monitor (SAM)

This utility was designed to Monitor Active Directory and other critical applications. It will quickly spot domain controller issues, prevent replication failures, track failed logon attempts and much more.

What I like best about SAM is it’s easy to use dashboard and alerting features. It also has the ability to monitor virtual machines and storage.

Download Your Free Trial of SolarWinds Server & Application Monitor. 

Source : How to Restart or Shutdown a Remote Computer

How to migrate from Microsoft Exchange 2010 to Exchange 2016 – TechGenix

Microsoft Exchange 2016 is exciting as it comes with a host of cool features such as cloud deployments, improved reliability, and a new architecture that is much more conducive for today’s business environment.

If you haven’t done it already, it’s probably time to consider migrating your mail server from Exchange 2010 to 2016 because it is more convenient and lays the foundation for future progress.

So, what’s new in Exchange 2016 that makes it so exciting for system administrators world over?

Let’s briefly look at some of the key changes in 2016 that were not available in the 2010 version. Also, if you don’t want to miss my future Exchange configuration guides and best practices articles, sign up for updates here!

Architecture

Exchange 2010 had separate components such as Mailbox,  Hub Transport, Unified Messaging, and Client Access for performing separate roles in the server. In 2016, all of these components have been combined into a single component called Mailbox, and this component performs the combined role of other components.

Exchange Admin Center

Exchange Admin Center (EAC) has been greatly enhanced to help you connect from anywhere using a web browser. It acts as a single point of control for all operations and is optimized for on-premise, online, and hybrid Exchange deployments. Due to this enhanced EAC, Exchange Management Console (EMC) of 2010 has taken a back seat. Microsoft observed delayed updates in EMC, and this is why it decided to limit its scope in 2016.

Hybrid Configuration Wizard (HCW)

Exchange 2016 has a cloud-based application called Hybrid Configuration Wizard (HCW) that helps to connect with other Microsoft tools like Office 365 in real-time. Improved diagnostics and troubleshooting make it ideal for hybrid deployments.

MAPI over HTTP

MAPI over HTTP is the default protocol in Exchange 2016, as it is more reliable and stable than the RPC over HTTP protocol of Exchange 2010. Also, this protocol allows Outlook to pause a connection, change networks, and resume hibernation, things that were difficult to implement in Exchange 2010.

Certificate Management

In 2010, you had to install certificate for every server through EMC, while in 2016, you can install certificates across multiple servers at the same time through EAC. You can also see the expiry details in EAC.


Now that you know why Exchange 2016 is better, let’s see how to migrate from version 2010 to 2016.

Update the existing environment

If you unsure of the version you’re using, open the Exchange Management Shell and run this command:

Get-ExchangeServer : Format-List Name, Edition, AdminDisplayVersion

Like what you’re reading? Get the latest updates and tech guides in your inbox.

This should bring up the current version you’re using. Make sure it says Exchange 2010.

The first step is to update the existing environment to make the 2010 version suitable for upgrading to 2016.  To do that, install Exchange 2010 Service Pack 3 and Exchange 2010 SP3 Update Rollup 11. These are the minimum supported patch level updates for 2010, and the installation process is fairly self-explanatory.

exchange-server-2010-sp3-upgrade

installing-update-rollup

The next step is to consider updating the Directory Service Requirement and Outlook Client. For Exchange 2016, the minimum Directory Service Requirement is AD Functional Level 2008, and for Outlook Client, it is Exchange 2016 Support Outlook 2010 and above on Windows and Mac Outlook 2011 and above on Mac. You should update clients to this minimum supported version before implementing Exchange 2016.

Prepare the System for Exchange Server 2016

Do you have the system requirements needed to support Exchange 2016? Let’s double check the below requirements again, as Exchange Server 2016 supports only the following:

  • Windows Server 2012 / 2012 R2
  • Minimum memory requirement for Mailbox server role is 8GB plus an additional minimum requirement of 4GB for edge transport
  • Paging file size should be set to physical RAM, and an additional 10MB to 32788MB, depending on the size of the RAM. If you’re using 32GB of RAM, then go for the maximum of 32788MB
  • Disk space of at least 30GB on the drive on which you plan to install Exchange. Also, an additional 500MB is needed for every Unified Messaging (UM) language pack that you want to install. Additionally, you need 200MB of available disk space on the system drive, and a hard disk of a minimum of 500MB of free space for message queue database
  • A screen resolution of 1024 X 768 pixels.
  • Disk partitions that are formatted on the NTFS file system
  • .NET framework and UCS API should be installed before installing Exchange 2016. You can download both from Microsoft website and install it in your system.

Make sure your system meets all these prerequisites before installing Exchange 2016.

Next, you have to prepare the schema update. This step is irreversible, so make sure you have a full backup of Active Directory before proceeding.

A good part about this migration is you don’t have to worry much about changing HTTPS names for OWA as both the versions support the same set of naming services and active sync directories.

Install Active Directory for Exchange 2016

Next, run the Exchange 2016 setup. Choose a specific directory to extract all the files of this setup. Once the extraction is complete, run the following commands, one after the other. Open the command prompt and go to the directory where you have extracted the files.

The first command is to prepare the schema, which is, setup.exe /PrepareSchema /IAcceptExchangeServerLicenseTerms

prepare-active-directory-schema

Now your schema is prepared, so move on to the next command, which is, setup.exe /PrepareAD /IAcceptExchangeServerLicenseTerms. Once that’s done, prepare your domain with the command setup.exe /PrepareDomain /IAcceptExchangeServerLicenseTerms. With this, we have completed the Active Directory installation for Exchange 2016.

Install Exchange 2016

Now that you have the environment set up, it’s time to do what you’ve come for, which is installing Exchange 2016. Fortunately, this is also the easiest step in the migration process as the configuration wizard takes care of most things for you!

Browse through the setup directory, and run the file called Setup.exe.

initializing-setup

During the installation, you’ll be prompted to choose the server role selection. Choose « Mailbox role, » and the other options will automatically be deactivated because Mailbox and Edge Transport cannot coexist in the same machine.

server-role-selection

Installation will complete within the next few minutes.

server-progress-exchange-setup

Once the installation is complete, click on the Finish button. This will load the Exchange Admin Center on the browser.

exchange-admin-center

Exchange management console in 2010 is replaced with a web-based Exchange Admin Center in 2016. This is the place where you can have greater control over all operations.

exchange-admin-center-interface

Other Configurations

After installing Exchange 2016 successfully, update the Service Connection Point for AutoDiscover. To do this, use the Set-ClientAccess command from Exchange Management Shell.

Go to the Exchange Management Shell, and type this command:

Set-ClientAccessService -Identity E2016 -AutoDiscoverServiceInternalURI https://autodiscover.yourURL.com/Autodiscover/Autodiscover.xml

Next, update the settings of Outlook Anywhere. To do this, go to EAC, and click on servers on the left hand side. This will open up the list of servers. Click the Edit icon and a pop-up will open. Choose the Outlook Anywhere option, and update the DNS lookup and IMAP4 settings with the name of your new server.

outlook-anywhere-interface

Once you’ve configured the settings, run IIS RESET. To do this, go to your command prompt and run the command iisreset. This will stop and restart IIS services.

The next step is to configure your Receive Connector to relay email applications. To configure this, go to the mail flow option in your EAC, click on a connector, and edit it.

receive-connector

Next up is your Mail Database installation. When you install 2016, a default database is created. You can rename this database and move it from C Drive to another drive. Open the EMC shell and run these commands to rename and move your database.

Get-MailboxDatabase -Server E2016 : Set-MailboxDatabase -Name DBExchange2016

Move-DatabasePath -Identity DB01 -EdbFilePath E:\Database\DB01\DBExchange2016.EDB. -LogFolderPath E:\Database\DBExchange2016_Log

Once that’s done, update the OWA directory. Exchange 2016 supports acting-as-a-proxy for 2010, so both the versions can coexist using the same URLs. Now, change the OWA and autodiscover URL to Exchange 2016, to ensure all URLs go through Exchange 2016. You can use the below script to do that.

$Server  = « E2010 »
$HTTPS_FQDN = your_URL
Get -OWAVirtualDirectory -Server $Server | Set -OWAVirtualDirectory -ExternalURL $null
Get -ECPVirtualDirectory -Server $Server | Set -ECPVirtualDirectory -ExternalURL $null
Get -OABVirtualDirectory -Server $Server | Set -OABVirtualDirectory -ExternalURL $null
Get -ActiveSyncVirtualDirectory -Server $Server | Set -ActiveSyncVirtualDirectory -ExternalURL $null
Get -WebServicesVirtualDirectory -Server $Server | Set -WebServicesVirtualDirectory -ExternalURL $null
Enable -OutlookAnywhere -Server $Server -ClientAuthenticationMethod Basic -SSLOffloading $False -ExternalHostName $HTTPS_FQDN

Lastly, update the DNS, so it points to autodiscover and OWA. To do that, open your Accu Directory Domain Controller Machine. Open the DNS Manager, and change the record to ensure that it points to the new server.

Whew! With this, you’re almost done with the migration.

Test your configuration

Finally, it’s time to test if your configurations work. It’s best to create a new user to login and test the account functionality. To create a new user, open EAC and click on Recipients. From here, add a new user and check if everything is working fine.

If all is good, migrate all users from the Exchange 2010 to the Exchange 2016 database.

And that’s a wrap!

In short, much has changed between Exchange 2010 and Exchange 2016, so it’s best you migrate to the latest version to make the most of the new functionalities. Migrating to 2016 is not so difficult when you follow the aforementioned steps.

Do the migration right away to enjoy the new functionalities of Exchange 2016, not to mention the reduced workload of mundane tasks. With all Exchange has to offer, you best prepare to upgrade to appreciate the benefits. (Remember, an upgrade is usually one-time only!)

Learn why Exchange 2016 is better than Exchange 2010–and how to take the plunge to migrate your Microsoft server to the latest version.

Source : How to migrate from Microsoft Exchange 2010 to Exchange 2016 – TechGenix

Python: Check if a File or Directory Exists

Python: Check if a File or Directory Exists

There are quite a few ways to solve a problem in programming, and this holds true especially in Python. Many times you’ll find that multiple built-in or standard modules serve essentially the same purpose, but with slightly varying functionality. Checking if a file or directory exists using Python is definitely one of those cases.

Here are a few ways to check for existing files/directories and their nuances. Throughout these examples we’ll assume our current working directory has these files and directories in it:

drwxr-xr-x  3 scott  staff  102 Jan 12 10:01 dir  
-rw-r--r--  1 scott  staff    5 Jan 12 09:56 file.txt
lrwxr-xr-x  1 scott  staff    8 Jan 12 09:56 link.txt -> file.txt  
lrwxr-xr-x  1 scott  staff    3 Jan 12 10:00 sym -> dir  

Notice that we have one directory (dir), one file (file.txt), one file symlink (link.txt), and one directory symlink (sym).

Checking if a File Exists

This is arguably the easiest way to check if both a file exists and if it is a file.

import os  
os.path.isfile('./file.txt')    # True  
os.path.isfile('./link.txt')    # True  
os.path.isfile('./fake.txt')    # False  
os.path.isfile('./dir')    # False  
os.path.isfile('./sym')    # False  
os.path.isfile('./foo')    # False  

Note that os.path.isfile does follow symlinks, so we get True when checking link.txt.

isfile is actually just a helper method that internally uses os.stat and stat.S_ISREG(mode) underneath, which we’ll touch on later.

Checking if a Directory Exists

Like the isfile method, os.path.isdir is the easiest way to check if a directory exists, or if the path given is a directory.

import os  
os.path.isdir('./file.txt')    # False  
os.path.isdir('./link.txt')    # False  
os.path.isdir('./fake.txt')    # False  
os.path.isdir('./dir')    # True  
os.path.isdir('./sym')    # True  
os.path.isdir('./foo')    # False  

Again, just like isfile, os.path.isdir does follow symlinks. It is also just a simple wrapper around os.stat and stat.S_ISDIR(mode), so you’re not getting much more than convenience from it.

Checking if Either Exist

Another way to check if a path exists (as long as you don’t care if the path points to a file or directory) is to use os.path.exists.

import os  
os.path.exists('./file.txt')    # True  
os.path.exists('./link.txt')    # True  
os.path.exists('./fake.txt')    # False  
os.path.exists('./dir')    # True  
os.path.exists('./sym')    # True  
os.path.exists('./foo')    # False  

As you can see, it doesn’t care if the path points to a file, directory, or symlink, so it’s almost like you’re using isfile(path) or isdir(path). But actually, internally it is just trying to call os.stat(path), and if an error is thrown then it returns False.

Advanced

Throughout the article I’ve been mentioning how all of the above methods utilize the os.stat method, so I figured it would be useful to take a look at it. This is a lower-level method that will provide you with detailed information about files, directories, sockets, buffers, and more.

Like all the other methods we’v already covered, os.stat follows symlinks, so if you want to get the stat info on a link, try using os.lstat() instead.

Since every operating system is different, the data provided by os.stat varies greatly. Here is just some of the data that each OS has in common:

  • st_mode: protection bits
  • st_uid: owner’s user id
  • st_gid: owner’s group id
  • st_size: size of file in bytes
  • st_atime: time of last access
  • st_mtime: time of last modification
  • st_ctime: time of last metadata change on Unix, or time of creation on Windows

You can then use this data with the stat module to get interesting information, like whether a path points to a socket (stat.S_ISSOCK(mode)), or if a file is actually a named pipe (stat.S_ISFIFO(mode)).

If you need some more advanced functionality, then this is where you should go. But for 90% of the time you’re dealing with directories and files, the os or os.path modules should have you covered.

Although, one valid use-case might be when you’re doing multiple tests on the same file and want to avoid the overhead of the stat system call for each test. So if you have quite a few tests to do then this will help you do it more efficiently.

Source: http://stackabuse.com/python-check-if-a-file-or-directory-exists/

How to Copy a File in Python with shutil | Python Central

So you want to know how to copy a file in Python? Good! It’s very useful to learn and most complex applications that you may design will need at least some form of copying files.

Copying a Single File in Python

Alright, let’s get started. This first section will describe how to copy a single file (not a directory) to another location on the hard disk.

Python has a special module called shutil for simple, high level file operations that is useful when copying single files.

Here’s an example of a function that will copy a single file to a destination file or folder (with error handling/reporting):

And that’s it! We just call that method, and the file is copied. If the source or destination file doesn’t exist, we print an error notifying the user that the operation has failed. If the source and destination files are the same, we don’t copy them and notify the user of the failed operation.

Python shutil’s Different Copy Methods

The module shutil has several methods for copying files other than the simple copy method that we have seen above.

I’ll go over them in some detail here, explaining the differences between them and situations where we might need them.

shutil.copyfileobj(fsrc, fdst[, buffer_length])

This function allows copying of files with the actual file objects themselves. If you’ve already opened a file to read from and a file to write to using the built-in open function, then you would use shutil.copyfileobj. It is also of interest to use this function when it is necessary to specify the buffer length of the copy operation. It may help, when copying large files, to increase the buffer length from its default value of 16 KB in order to speed up the copy operation.

All of the other copy functions mentioned below call this function at some point. It is the « base » copy method.

Let’s look at a benchmark for copying files using a 50 KB, 100 KB, 500 KB, 1 MB, 10 MB, and 100 MB buffer size vs a normal copy operation. We will test an archived file in iso format of 3.2 GB.

We’ll be using this function to specify the buffer size:

And Ubuntu’s built in time bash command to time the operation.

Here are the results:

50 KB: 29.539s
100 KB: 27.423s
500 KB: 25.245s
1 MB: 26.261s
10 MB: 25.521s
100 MB: 24.886s

As you can see, there is quite a big difference between the buffer sizes. Almost a 16% decrease in the amount of time it took using a 50 KB buffer size to using a 100 MB buffer size.

The optimal buffer size ultimately depends on the amount of RAM you have available as well as the file size.

shutil.copyfile(src, dst)

This method copies a file from the source, src, to the destination, dst. This differs from copy in that you must ensure that the destination path exists and also contains the file name. For example, '/home/' would be invalid because it’s the name of a directory. '/home/test.txt' would be valid because it contains a file name.

shutil.copy(src, dst)

The copy that we used above detects if the destination path contains a file name or not. If the path doesn’t contain a file name, copy uses the original file name in the copy operation. It also copies the permission bits to the destination file.

You would use this function if you are uncertain of the destination path format or if you’d like to copy the permission bits of the source file.

shutil.copy2(src, dst)

This is the same as the copy function we used except it copies the file metadata with the file. The metadata includes the permission bits, last access time, last modification time, and flags.

You would use this function over copy if you want an almost exact duplicate of the file.

Comparison of Python File Copying Functions

Below we can see a comparison of shutil‘s file copying functions, and how they differ.

Function Copies Metadata Copies Permissions Can Specify Buffer
shutil.copy No Yes No
shutil.copyfile No No No
shutil.copy2 Yes Yes No
shutil.copyfileobj No No Yes

That’s pretty much the end of copying files. I hope you benefited from this article, and I hope it was worth your time to learn a little bit of file operations in Python.

 

Source : How to Copy a File in Python with shutil | Python Central

Python loggin lib  – log to a file

6.28.8.1 Basic example – log to a file

Here’s a simple logging example that just logs to a file. In order, it creates a Logger instance, then a FileHandler and a Formatter. It attaches the Formatter to the FileHandler, then the FileHandler to the Logger. Finally, it sets a debug level for the logger.

import logging
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('/var/tmp/myapp.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.WARNING)

We can use this logger object now to write entries to the log file:

logger.error('We have a problem')
logger.info('While this is just chatty')

If we look in the file that was created, we’ll see something like this:

2003-07-08 16:49:45,896 ERROR We have a problem

The info message was not written to the file – we called the setLevel method to say we only wanted WARNING or worse, so the info message is discarded.

The timestamp is of the form « year-month-day hour:minutes:seconds,milliseconds. » Note that despite the three digits of precision in the milliseconds field, not all systems provide time with this much precision.

Source : 6.28.8.1 Basic example – log to a file

16.6. logging — Logging facility for Python — Python 3.6.4 documentation

This module defines functions and classes which implement a flexible event logging system for applications and libraries.

The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules.

The module provides a lot of functionality and flexibility. If you are unfamiliar with logging, the best way to get to grips with it is to see the tutorials (see the links on the right).

The basic classes defined by the module, together with their functions, are listed below.

  • Loggers expose the interface that application code directly uses.
  • Handlers send the log records (created by loggers) to the appropriate destination.
  • Filters provide a finer grained facility for determining which log records to output.
  • Formatters specify the layout of log records in the final output.

For tutorial information and discussion of more advanced topics, see

Source : 16.6. logging — Logging facility for Python — Python 3.6.4 documentation

Backup with rsync

Everyone needs to make backups. Some people copy their most important files to an external hard disk or DVD, others use automated software to do the job for them. Many Mac OSX users use Time Machine, Apple’s backup application. I think i don’t have enough control when i use it. So i started looking for a program that did what i wanted it to do, make incremental backups from folders that i chose, and have the option to exclude files or folders from the backup.

rsync, a command line (cli) program that’s installed by default on almost all UNIX based operating systems (so also Mac OSX and a whole lot of GNU/Linux distro’s), does the job quite good for me.

Example bash commande bellow:

rsync -avzru /Volumes/LACIE/ /Volumes/LaCie\ 1 --exclude "/Applications/**" --exclude ".*" --exclude ".*/" --exclude ".*/**"

This can be perfectioned by passing it to tar command etc.

Notes:

  • rsync is the program.
  • -avzru means ‘archive’, ‘verbose’ (more output to the command line), ‘compress’ (use compression to decrease traffic if you use rsync over a network), ‘recursive’ (go into all folders), ‘update’ (don’t overwrite newer files)
  • /Volumes/LACIE/ this is the source external hard disk (notice the “/” at the end!)
  • /Volumes/LaCie\ 1 this is the destination external hard disk. It’s called ‘LaCie 1’, and the backslash is there to see the space as part of the path. (notice that there is no “/” at the end)
  • –exclude “/Applications/**” here i exclude the folder ‘Applications’ from the backup
  • –exclude “.*” –exclude “.*/” –exclude “.*/**” also exclude all hidden files and folders

that’s it ?