IT-Articles (11)

Wednesday, 04 September 2019 21:20

CentOS and BackupPC Part 3

Rate this item
(0 votes)

Installing BackupPC on CentOS

The definitive guide to installing...

or close enough

Part 3 of 3

 

This is part 3 of a 3-part article.  If you haven't seen the other parts, you can find them here:  Part 1 and Part 2

Part 3 goes through configuring Linux and Apple Hosts. For Windows PC Hosts, see BackupPC and Volume Shadow Services


There are three sections below

  • BackupPC Server SSH Configuration
  • BackupPC Server and Linux Workstations
  • Apple MacOSX

I use SSH and rsync for Linux and Apple Host because the software is standard on the OS's, it's secure, and it's easy to configure.


BackupPC Server SSH Configuration

To get started, we need to create the SSH Keys for the backuppc user

List the folder

#  ls /var/lib/BackupPC/.ssh

If it doesn't exist, run the following command as root

#  sudo -u backuppc ssh-keygen -t rsa -C "backuppc"

Press 'Enter' after each line to create keys with no password

Enter file in which to save the key (/var/lib/BackupPC/.ssh/id_rsa): <<Enter>>
Enter passphrase (empty for no passphrase):  <<Enter>>
Enter same passphrase again:  <<Enter>>
Public key is saved in: /var/lib/BackupPC/.ssh/id_rsa.pub

This creates the Public and Private key for the backuppc user


BackupPC Server and Linux Workstations

 For BackupPC to backup the Linux Server or another Linux Workstation, the backuppc user must login remotely without a password.  We can accomplish this by copying the backuppc user's public key to the root user 

First, we need to verify that the local root account has SSH configured

#  ls /root/.ssh

If this folder doesn't exist, run the following command from root to create the folder and keys

# ssh-keygen -t rsa -C "root" 


Additionally, open the SSH config file

#  vi /etc/ssh/ssh_config

Verify the following two lines are commented with '#'

# StrictHostKeyChecking no
# PasswordAuthentication no

If the SSH config file is changed, restart the service

#  systemctl restart sshd

Now, copy the backuppc users public key to the local root account

  • For the BackupPC Server, use localhost or the Server host name
    #  sudo -u backuppc ssh-copy-id root@localhost
    • Enter root password
  • For the Linux Workstation, use the computer name (ex. MyLinuxLaptop)
    #  sudo -u backuppc ssh-copy-id root@MyLinuxLaptop​
    • Enter root password

After the command above, successfully, completes, the following command should connect without password

For the BackupPC Server use localhost or the Server host name

#  sudo -u backuppc /usr/bin/ssh root@localhost

For the Linux Workstation, use the computer name (ex. MyLinuxLaptop)

#  sudo -u backuppc /usr/bin/ssh root@MyLinuxLaptop

If the following error is seen in the logs when performing a backup:  Unable to read 4 bytes?

Run the ssh-copy-id command again and verify the backuppc user can login with no password

Once you can connect without a password, go to BackupPC Configuration Page (ex. http://localhost/BackupPC)

Click 'Edit Host' and 'Add'

Enter Host:
    For the BackupPC Server, use localhost or the Server host name
        
    For the Linux Workstation, use the computer name (ex. MyLinuxLaptop)    
    
Enter User:
    This user can be the Admin or a regular user.  If this is a regular user and you want this user to access his/her own backups, then add a password using htpasswd as shown in Part 1

Click 'Save' and then click another link (ex. Host Summary) or refresh the page.  Once the page is refreshed, you will see the host name listed in the Host Drop Down list.

Select the Linux Hostname (localhost or MyLinxLaptop) and click 'Edit Config' in the Host Name Section, not the Server Section

 Click 'Xfer'

Change the XferMethod to rsync
Change the RsyncShareName to reflect folders to backup

  • Example:   /etc   and   /home

 This is all I do to connect Linux computers, but configure other settings as needed, i.e., Email, Backup Settings, and Schedule


Apple MacOSX

Backing up Apple computers is much the same thing, just have to go about it a different way.

First, we need to allow remote connections

Open System Preferences -> Sharing

Check 'Remote Login'


Check 'Only these users:' and select 'Administrators'


If only one user account is needed to be backed up, skip Enable Root User section


Enable Root User

If needing to backup multiple user accounts or folders outside a user folder, you will need to enable the Root User.

Choose Apple menu > System Preferences, then click Users & Groups (or Accounts).

Click lock icon, then enter an administrator name and password.

    Click Login Options.

    Click Join (or Edit).

Click Open Directory Utility.

Click lock icon in the Directory Utility window, then enter an administrator name and password.

From the menu bar in Directory Utility:

Choose Edit > Enable Root User, then enter the password that you want to use for the root user.

Or choose Edit > Disable Root User.



Reference: https://support.apple.com/en-us/HT204012


Copy backuppc public key to user account

  • If root user is enabled:
    #  sudo -u backuppc ssh-copy-id root@MyMacLaptop
  • If root user is not enabled (change AppleUser to reflect the user account needing to be backed up):
    #  sudo -u backuppc ssh-copy-id AppleUser@MyMacLaptop

Verify that you can login from the BackupPC server without a password:

  • If root user is enabled:
    #  sudo -u backuppc ssh root@MyMacLaptop
  • If root user is not enabled (change AppleUser to reflect the user account needing to be backed up):
    #  sudo -u backuppc ssh AppleUser@MyMacLaptop

The backuppc Server should be able to ssh into the remote computer without a password

If the following error is seen in the logs when performing a backup:  Unable to read 4 bytes?

Run the ssh-copy-id command again and verify the backuppc user can login with no password

Once you can connect to the remote computer without a password, go to BackupPC Configuration Page (ex. http://localhost/BackupPC)

Click 'Edit Host' and 'Add'

Enter Host:
    For the Apple Computer, use the computer name (ex. MyMacLaptop)    
    
Enter User:
    This user can be the Admin or a regular user.  If this is a regular user and you want this user to access his/her own backups, then add a password using htpasswd as shown in Part 1

Click 'Save' and then click another link (ex. Host Summary) or refresh the page.  Once the page is refreshed, you will see the host name listed in the Host Drop Down list.

Select the Apple Computer Hostname (MyMacLaptop) and click 'Edit Config' in the Host Name Section, not the Server Section

Click 'Xfer'

Change the XferMethod to rsync

Change the RsyncShareName to reflect folders to backup

  • If root user is enabled, backup multiple user accounts:
    • RsyncShareName = /Users
  • If root user is not enabled, backup one user account:
    • RsyncShareName = /Users/AppleUserAccount

For RsyncClientCmd and RsyncClientRestoreCmd, change the user, if root is not enable

  • If root user is enabled:
    • $sshPath -q -x -l root $host $rsyncPath $argList+
  • If root user is not enabled:
    • $sshPath -q -x -l AppleUserAccount $host $rsyncPath $argList+

 

This is all I do to connect Apple computers, but configure other settings as needed, i.e., Email, Backup Settings, and Schedule


If something needs to be corrected or doesn't make sense, leave a comment.

As always, Enjoy!

Last modified on Sunday, 08 September 2019 23:36
Monday, 02 September 2019 20:23

CentOS and BackupPC Part 2

Rate this item
(0 votes)

Installing BackupPC on CentOS

The definitive guide to installing...

or close enough.

Part 2 of 3

 

This is part 2 of a 3-part article.  If you haven't seen the other parts, you can find them here:  Part 1 and Part 3

Part 2 goes through configuring the BackupPC Server.  If something doesn't make sense, please leave a comment.


  • If you are interested in accessing BackupPC from another computer on the network, edit the Firewall with your tool of choice and allow port 80 through it
  • Additionally, you will need to edit the apache BackupPC configuration file
    • Edit: /etc/httpd/conf.d/BackupPC.conf
    • Add the two lines below containing the IP address of the local network that needs access.  Add identical lines below them, as needed, for any other network that needs web access to the server.
      	<IfModule mod_authz_core.c>
      	  # Apache 2.4
      	  <RequireAll>
      	    Require valid-user
      	    <RequireAny>
      	      Require local
                    Require ip 192.168.1  # Add this line
      	    </RequireAny>
      	  </RequireAll>
      	</IfModule>
      	<IfModule !mod_authz_core.c>
      	  # Apache 2.2
      	allow from 127.0.0.1
              allow from 192.168.1  # Add this line
      	require valid-user
      	</IfModule>
      

  • Sometimes, I have run into trouble where the temporary folder doesn't exist, gets deleted, or otherwise, disappears, so I wrote a startup script to check it and create it, if not found.  This is optional, but is something I do, just in case.
    • First, create a file.  I'll put this one in the root folder and call it backuppccheck.sh:
      #  vi /root/backuppccheck.sh
      
    • Paste the following in the file:
      #!/bin/sh
      # backuppccheck
      # description: Makes sure the backuppc Temp Folder Exist on startup
      
              if [ -d /var/run/BackupPC ]; then
                      logger "BackupPC temp folder exists"
              else
                      mkdir -p /var/run/BackupPC
                      chown backuppc:backuppc /var/run/BackupPC
                      logger "BackupPC temp folder created"
              fi
    • This will check if the folder exists and create it, if needed.  Either way, it will write a note to the logfile what it does.
    • Make the file executable:
      #  chmod u=rwx /root/backuppccheck.sh
    • Make the service file that will execute this file on startup:
      #  vi /etc/systemd/system/backuppccheck.service
    • Paste the following in the file, changing the file name and location as needed:
      [Unit]
      Description=Check if BackupPC Temp Folder Exists on startup
      After=network.target
      
      [Service]
      Type=simple
      ExecStart=/root/backuppccheck.sh
      TimeoutStartSec=0
      
      [Install]
      WantedBy=default.target
    • Start and Enable the service:
      #  systemctl start backuppccheck.service
      #  systemctl enable backuppccheck.service

To have the BackupPC server find and ping other computers, you'll need to configure the Router and/or the BackupPC Server

  • Depending on how you're network is configured, you may have to tell the router AND the backuppc server where to find computers on the network that you want to back up.  To do this, you need to assign static IP addresses in the router configuration.  For example, I want to back up the following workstations and I'm assigning the corresponding IP addresses.  Each router is different, but search the internet how to do this for your specific router, if needed.
    • MY EXAMPLE:
      • MyPCLaptop is assigned 192.168.1.50
      • MyLinuxLaptop is assigned 192.168.1.55
      • MyMacLaptop is assigned 192.168.1.60
      • MyDesktop is assigned 192.168.1.70
  • Once you have these IP addresses entered in the router, go to the BackupPC server and find the hosts file.
  • In CentOS, it is located in the following file: /etc/hosts
  • Edit the Hosts file and add the same IP addresses and Hostnames as you did in the Router
    #  vi /etc/hosts
    • Add the same hostnames and IP addresses
      127.0.0.1     localhost
      ::1           localhost
      192.168.1.50  MyPCLaptop
      192.168.1.55  MyLinuxLaptop
      192.168.1.60  MyMacLaptop
      192.168.1.70  MyDesktop
  • After adding these to the BackupPC server, you should be able to PING these computers.  For fun, you can ping as the backuppc user.
  • As root, type:
    #  sudo -u backuppc ping MyPCLaptop

  • Sending test Email
    • As root, type:
    • #  sudo -u backuppc /usr/share/BackupPC/bin/BackupPC_sendEmail -u This email address is being protected from spambots. You need JavaScript enabled to view it.
    • If the email doesn't send, you should be able to see the errors and/or troubleshoot the problem.  There are many resources on the internet to help with sendmail.

One, last, optional, thing you can do on the Server:

Encrypt the BackupPC Data

This is a little advanced and I won't go into great detail on how to encrypt a drive as there is plenty of CentOS information to be found, but once the drive is formatted and encrypted, mount the drive where you want BackupPC to store the data and configure the drive as shown in Part 1.  So, for example, if I have an encrypted drive mounted at /media/encBackup, I run through all the parts and get BackupPC working.  Since the whole point of the encryption is to keep it secure, the encrypted drive is not automatically mounted at startup so, if the computer is restarted, you will have to manually mount the drive and start the backuppc services. 

With the script below, the only thing you'll do when the computer is restarted is (1) login as root, (2) run the script, (3) type the password to unlock the drive. 

I put the script in the /root folder so when I login as root, all I have to do is run the script, but you can put it anywhere. It's really easy.  First, we need to get the encrypted drive information.

  • Unlock the Encrypted Drive and, from root, type:
    blkid
  • Locate the Encrypted Drive's:
    • Device Name (ex. /dev/sdb)
    • UUID (ex. fc3333f1-1bf3-3333-af33-333a333f33af)
    • Device Name after being unlocked (ex. /dev/mapper/fc3333f1-1bf3-3333-af33-333a333f33af)
      [root@localhost ~]# blkid
      ...
      /dev/sdb: UUID="fc3333f1-1bf3-3333-af33-333a333f33af" TYPE="crypto_LUKS" 
      ...
      /dev/mapper/fc3333f1-1bf3-3333-af33-333a333f33af: LABEL="Backups" UUID="fc8888f1-1bf8-8888-af88-888a888f88af" TYPE="ext4" 
  • Once the above information has been determined, create a file...I'll call mine: start_backuppc.sh
    #  vi /root/start_backuppc.sh
  • Paste the following information in the file and replace the Device and UUID information with your Encrypted drive information.
    #!/bin/bash
    
    # Device Name of locked drive and UUID
    cryptsetup luksOpen /dev/sdb "fc3333f1-1bf3-3333-af33-333a333f33af"
    
    # Mount encrypted drive after unlocking it
    # mount /dev/mapper/UUID  /mount/point
    mount /dev/mapper/fc3333f1-1bf3-3333-af33-333a333f33af /media/encBackup
    
    #Restart BackupPC service
    systemctl restart backuppc.service
    
  • Save the file and make it executable
    #  chmod -u=rwx /root/start_backuppc.sh
  • Now, once the computer has been restarted, login as root and type:
    #  sh start_backuppc.sh
  • Type the Encrypted Drive's Password and logout.  If there were no errors, BackupPC starts.

 

Congrats! You should have a working BackupPC server...whether it is encrypted or not.  To add different hosts, jump to Part 3

 

Last modified on Sunday, 08 September 2019 23:36
Saturday, 31 August 2019 05:08

CentOS and BackupPC Part 1

Rate this item
(0 votes)

Installing BackupPC on CentOS

The definitive guide to installing...

or close enough

Part 1 of 3

 

I, recently, was able to install BackupPC on a new installation of CentOS 7 so I was able to go through my notes and put them in a coherent form.  Below is what I consider 'coherent.' :)   I decided to break this into 3 parts because, as I was writing, it became long.  The three parts are:  1. BackupPC Installation  2. Configuration of Server 3. Adding Linux and Apple Hosts

If something doesn't make sense, please post a comment.


  • I disable selinux.  If this isn't something you want to do and you know how to configure BackupPC with selinux enabled, please post a note and I'll make an addition to this list.
    • To disable selinux, edit the file:  /etc/sysconfig/selinux
      # This file controls the state of SELinux on the system.
      # SELINUX= can take one of these three values:
      #     enforcing - SELinux security policy is enforced.
      #     permissive - SELinux prints warnings instead of enforcing.
      #     disabled - No SELinux policy is loaded.
      SELINUX=disabled
      # SELINUXTYPE= can take one of three values:
      #     targeted - Targeted processes are protected,
      #     minimum - Modification of targeted policy. Only selected processes are protected.
      #     mls - Multi Level Security protection.
      SELINUXTYPE=targeted
      
    • Change the line that reads:  SELINUX=enforcing to SELINUX=disabled
    • Restart the computer

  • Install epel-release, backuppc, and sendmail, if not already installed
    yum install epel-release
    yum install backuppc sendmail
    

  • Add a BackupPC Admin user
    • From root, type: htpasswd /etc/BackupPC/apache.users  <<admin username>>
      • Example:  # htpasswd /etc/BackupPC/apache.users bpcadmin
    • When prompted, enter a password of your choice, twice
      # htpasswd /etc/BackupPC/apache.users bpcadmin
      New password: 
      Re-type new password: 
      Adding password for user bpcadmin
    • If you already know which users that will need access to BackupPC, you can add users this same way now or come back at a later time

  • With the Backup Drive mounted, create the folders, and change the permissions to allow the backuppc user access
    # mkdir /media/backups/BackupPC
    # mkdir /media/backups/BackupPC/pc
    # mkdir /media/backups/BackupPC/cpool
    # chown -R backuppc /media/backups/BackupPC/
    

  • Edit the BackupPC config file:  /etc/BackupPC/config.pl
    • Around line 300, look for:  $Conf{TopDir} and add the path where the backups will be stored.
      $Conf{TopDir} = '/media/backups/BackupPC/';
      $Conf{ConfDir} = '/etc/BackupPC/';
      $Conf{LogDir} = '/var/log/BackupPC';
      $Conf{InstallDir} = '/usr/share/BackupPC';
      $Conf{CgiDir} = '/usr/share/BackupPC/sbin/';
      
      
    • In the same file, scroll down further, around line 2030, and look for: $Conf{CgiAdminUsers}
    • Add the Admin user created above. This gives the Admin access to make changes via the Web Gui
      $Conf{CgiAdminUserGroup} = '';
      $Conf{CgiAdminUsers} = 'bpcadmin';
      
    • Save the file

  • Give the backuppc user permission to run anywhere on server
    • Run command as root:  visudo
    • Look for "Allow root to run any commands anywhere"
    • Below the line: root   ALL=(ALL)   ALL
    • Add:  backuppc    ALL=NOPASSWD:    ALL
      ## Allow root to run any commands anywhere
      root    ALL=(ALL)       ALL
      backuppc  ALL=NOPASSWD:   ALL
      
    • Save file

  • Start the BackupPC service
    # systemctl start backuppc.service
    • Helpful tip: If the service fails, run the following as root to view the errors
      # sudo -u backuppc /usr/share/BackupPC/bin/BackupPC -d

  • If Successful, log in to website with Admin user
  • Click 'Edit Config' and check the PingPath setting
    • If blank, change it to:  /usr/bin/ping

  • Click 'Email' and check the SendmailPath setting
    • If blank, change it to /usr/sbin/sendmail

 


Jump over to Part 2 and continue...

 

 

Last modified on Monday, 09 September 2019 02:34
Rate this item
(0 votes)

BackupPC can be a very daunting task when first starting out, but as many people who have installed it multiple times will say, it's not that bad, but it does take some time to figure out.  One of my sayings (as I may have said before), "It's easy, if you know how to do it," meaning it's not easy, if you don't. :)  BackupPC is one of them, but don't fear, if you work through the issues, you'll make it. Additionally, my plan is to write my notes how I install it in a future post.

For those that get it running, the first thing they'll notice is that it doesn't copy open files.  So, for those computers where the backup begins and people are working on stuff, open files are not backed up, i.e., Outlook Files or open Office documents.  This bugged me because I was and I am a BackupPC fan.  I scoured the internet in search of an easy way (emphasis on easy) to have BackupPC copy open files on Windows Computers.  Well, in my search, I didn't find an easy one, so I went on a development spree to try and figure out a way to do it.  It took a few weeks of trial and error, but I can now say, there is an easy way to do it.

Over the years, what I did grew into a hodge podge of files in a folder and a few batch files.  These past few weeks, I decided to try and put them together into one interface.  I wanted to use AutoIt, but the compressed executable, although doesn't have viruses, is flagged by many Antivirus programs as having one just because it was compressed by AutoIt.  I didn't want to keep answering the question, "Does it contain viruses," so I opted to use Visual Basic, instead.  So, below is what has been developed.  From my experience, this solution runs on anything after Windows 7.  I've, successfully, run this solution on Windows 7/8/10 without problems.

This is the first version of the GUI, so there may be a few bugs. If you find one or more, please post it in the comments below.

Additionally, I uploaded the exe's to VirusTotal.com.  They have passed all virus checks.  I would encourage you to do the same, if you decide to use these files.  I can, personally, attest that I did not write any backdoors nor viruses in these files.  These are clean and feel free to use them, if you like.

 

 VSSBackupPC 1.1

 

VSSBackupPC is designed to be used with the BackupPC server software.  This app uses Volume Shadow Copy Services so the server can backup open files on the C:\ drive.  To accomplish this, it uses Cygwin and Rsync for the data transfer.

I tried to make this as easy as possible.  I know it's a lot of writing below, but, in reality, there are only a few settings.

This app is written in Visual Basic and the .Net Framwork version 4.6.1 is needed to run it.

The Welcome window

Select the resource zip file that is included in the download.

The contents of the resource file is below.

When the app is started, it creates a folder called: C:\rsyncd.   This is a hard coded folder and cannot be changed.

All files related to this app will be created and placed in this folder.
 

Rsyncd.secrets

Enter the rsync user name and password.  It should be the same as used on the BackupPC server in these fields: RsyncdUserName, RsyncdPassword


As you hover over the window, if a secret file is found, it will display: Secrets File Exists.  If not, it displays: No Secrets File

Click the Add button to create the file and/or add credentials to an existing one

To find more information about the secrets file, check the client setup on the BackupPC website.

 

Rsyncd.Conf

See samba.org website for more information about this file.

1.  RsyncShareName = [Module Name]

Should be the same as the one added in BackupPC. Case matters, so UserFolder and userfolder are different.

2.  Choose the Local Backup Path.

Do Not Use VSS: Checking this box will force BackupPC to use the actual folder and will not copy open files.  At this point, drives other than C: are not included in the Shadow folder.

3.  Comment:  A short comment, like "User Folder"

4.  BackupPC Server IP Address: The ‘Allowed host(s)’ to access the PC and run rsync remotely

Strict Modes, Read Only, and List: Consult the samba website above for more information

As you hover over the window, if a rsync.conf file is found, it will display: Conf File Exists.  If not, it displays: No Conf File

5.  ‘Load Defaults’ will place default values in the fields and check boxes.  Edit the RsyncShareName, Host IP Address, and/or Path.  Then, you're set.

 

 
Manually Edit Rsyncd.Conf

You can manually edit the rsyncd.conf file.  This is not necessary nor encouraged, but is built-in to help with advanced configurations.
 

Task Settings

1.  Renew VSS Folder every 'x' hours

Default = 6 hours.   Set the time (in hours) that the script looks at the Time Stamp on the Shadow folder. When the time has exceeded, the Shadow Folder is removed and recreated.

2.  Only Allow VSS Backup Tasks to Run on AC Power?

Default = Yes.   To allow the VSSBackukpPC scheduled tasks to run if the laptop is running on batteries, uncheck the box.  If checked, the Scheduled Tasks will only run while the computer is plugged in.  (Thanks to agu for finding this setting)

 

Install Services

1.  Type the Host IP Network.  Only type the first three octets of the network.  There are a few drop down examples, but you can type any IP address that is needed.1  For example:
192.168.1
172.16.0
10.0.0

2.  Select the Subnet Mask of the Network.  The default is 24 (255.255.255.0).

3. ‘Install Services.  This will open two command windows and install the services needed to run VSSBackupPC.

4.  If needed, the ‘Remove Services’ button will remove the services so the C:\rsyncd folder can be deleted.

When VSSBackupPC starts, it checks for a running process of rsync on startup.  If it finds one, it will display a message asking to remove the service if it needs to be installed again.  You do not have to remove the service if you only need to change the secrets or conf file.

1This network is added to the Private firewall profile to allow port 873 and pings through it. The script does not change the public profile in any way so make sure the computer is in the private firewall profile

 
The resource zip file contains 8 files as seen to the right.  The Cygwin files can be found on the internet as well as the vshadow,exe file.  removevss.exe and vss-backuppc.exe were written in Visual Basic to handle the logic.

All files have been uploaded and checked at VirusTotal.com.  Feel free to upload them to check yourself.  There are no Viruses or Backdoors written in the code.
 

There is one, additional, thing you have to do on the BackupPC server, but it's not difficult.

1.  Add a DumpPreUserCmd script to the BackupPC server.

Create a folder that is accessible by the backuppc user, for example, choose to create a 'scripts' subfolder where backuppc resides

In the folder, create two files:

  1. preshare.sh
  2. pass

2. preshare.sh:    Replace <Enter_Secrets_File_UserName> with the user name used above in the secrets file.

3.  pass  (used in preshare.sh):  Enter the secrets password used in the secrets file. Nothing else, no brackets, etc.

4.  In the DumpPreUserCmd field, type:

sh + the path to the preshare.sh + space + $host

Ex: sh /media/backup/scripts/preshare.sh $host

 

 

1.  preshare.sh:
---------------------
#!/bin/bash
echo "I am the dumppresharecmd for BackupPC..."
echo "======================================="
 
rsync --dry-run --password-file=/media/backup/scripts/pass rsync://<Secrets_File_UserName>@$1/cDrive

#Ex. rsync --dry-run --password-file=/media/backup/scripts/pass rsync://SUser@$1/cDrive

echo "Waiting 60 seconds.  Giving time to create shadow copy"
sleep 60
echo "all Done."
echo "======================================"

 


2.  pass
---------------------
# =======================
Secrets_File_Password
#Ex.   mysecretpass
# =======================

 

Some notes:

A VSS folder called c:\shadow is created.  This is where BackupPC is directed. 

Additionally, the script creates a logfile called: vsslog.log and is found in the C:\rsyncd folder.  When the logfile reaches 2MB, it is deleted and recreated.

I hope this makes sense and may even help someone down the road.  If there are any questions, bugs, or comments, leave them below.

As always, enjoy!

VSSBackupPC.exe and the resource.zip file can be downloaded here: VSSBackupPC.zip

 

Last modified on Saturday, 27 April 2019 00:34
Wednesday, 14 February 2018 21:09

Install Teamviewer 13 on CentOS 7

Rate this item
(3 votes)

I have been using Fedora on my main machine for a very long time and have loved it.  Over the years, I have installed CentOS on multiple machines and virtual machines, but, finally, took the plunge and installed it on my main machine.  Everything went well until I needed TeamViewer to access a friend's computer remotely.  I thought, how difficult could it be?  Download the rpm from the TeamViewer site and install it...wrong.  It needs dependencies, but doesn't let you know that unless you try and install it from the command line.  Their Linux support page lists some requirements, so take a look here, first.  If you find the requirement you need, then it's all good.  However, I needed to do more.

When I double-clicked the teamviewer rpm file, I received a graphical error message that read:  "Sorry, this did not work.  This file is not supported".  I was certain that I downloaded the correct version (32bit or 64bit), so this was a little confusing.  I searched the internet for a solution, but didn't find one.  I, eventually, found that TeamViewer was missing dependencies by executing the following command from root:

# rpm -ivh teamviewer_13.0.9865.x86_64.rpm

The error messages I received:
warning: teamviewer_13.0.9865.x86_64.rpm: Header V4 RSA/SHA1 Signature, key ID 0c1289c0: NOKEY
error: Failed dependencies:
    /usr/lib64/qt5/qml/QtGraphicalEffects/qmldir is needed by teamviewer-13.0.9865-0.x86_64
    /usr/lib64/qt5/qml/QtQuick/Controls/qmldir is needed by teamviewer-13.0.9865-0.x86_64
    libQt5Qml.so.5()(64bit) >= 5.5 is needed by teamviewer-13.0.9865-0.x86_64
    libQt5Quick.so.5()(64bit) >= 5.5 is needed by teamviewer-13.0.9865-0.x86_64
    libQt5WebKitWidgets.so.5()(64bit) >= 5.5 is needed by teamviewer-13.0.9865-0.x86_64
    libQt5X11Extras.so.5()(64bit) >= 5.5 is needed by teamviewer-13.0.9865-0.x86_64

I worked through the dependencies and thought I would post them since I didn't find a place on the internet that had the list.  Again, this is on a fresh CentOS 7 installation.

[edit August 2018] 

The problem still exists and the these dependencies are still needed, but I noticed that in order to install qt5-qtwebkit, you'll need to add the EPEL repo.  So, before installing, add the repo:
yum -y install epel-release

[============]

yum install qt5-qtdeclarative qt5-qtwebkit qt5-qtx11extras qt5-qtgraphicaleffects qt5-qtquickcontrols

After installing the above dependencies, I was still unable to double-click the file to install it.  I had to install it from the command line as root:

# rpm -ivh teamviewer_13.0.9865.x86_64.rpm 

It is now installed and happily running with CentOS 7.  The other cool thing the installation does is add a 'teamviewer.repo' file so updates will be done easily in the future. See the end of this page for more information.

I hope you don't have the same problems installing it, but if you do, try the above.

Enjoy!

Last modified on Tuesday, 14 August 2018 02:08
Wednesday, 07 February 2018 02:31

Computer Inventory with AutoIT

Rate this item
(0 votes)

I've used the following AutoIT program many times to retrieve inventory information from a PC.  It grabs a load of information and will look for installed programs or all installed programs.  It will send the information to an email address, save it to a file, or both.  It needs an INI file (below) in the same folder where the program is executed.  I used Koda to create the GUI and I used the work of a few others that I found on the internet and included them in the script.

You will need to edit the script to include the SMTP server of your choice.

Save the following in the same folder as the compiled program. Name the file: Get_Inv.ini

[admin]
email=Your_Email@Address
[search]
file0=Avast
file1=Office
[Internet]
require=1
 
[Information]
In the 'search' section, list the programs to check to see if they are installed on the computer. If the program is not found, nothing will be shown in the list.
To list all the installed programs, type 'All' in the first field, 'file0'.
List as many programs as needed.  Just add another line and increment the number.
Example:
file2=Cisco
file3=Symantec
file4=Junos
etc.
 
Internet is required (1) to send an email.  To only save a file locally, it must be '0'. If there are values other than these two, the program will not run. The local file will be saved in the same folder from where the program is run.

Below is the source code for AutoIT.  If there are any questions, leave comments below.

Enjoy!

 =============


#cs ----------------------------------------------------------------------------
 
 AutoIt Version: 3.3.10.2
 Author:         myName
 
 Script Function:
    Template AutoIt script.
 
#ce ----------------------------------------------------------------------------
 
; Script Start - Add your code below here
#include <ButtonConstants.au3>
#include <ComboConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <Constants.au3>
#include <String.au3>
#include <Array.au3>
#include <Inet.au3>
#Include<file.au3>
 
#Region ### START Koda GUI section ### Form=
$Form1_1 = GUICreate("Get Inventory...", 247, 143, 270, 600)
$Label1 = GUICtrlCreateLabel("Computer Name", 13, 16, 77, 17)
$Button1 = GUICtrlCreateButton("Send Inventory", 74, 104, 99, 25)
$Input1 = GUICtrlCreateInput(@ComputerName, 101, 16, 137, 21, BitOR($GUI_SS_DEFAULT_INPUT,$ES_READONLY))
$Checkbox1 = GUICtrlCreateCheckbox("Save Locally?", 75, 48, 97, 17, BitOR($GUI_SS_DEFAULT_CHECKBOX,$BS_RIGHTBUTTON))
GUICtrlSetTip(-1, "Save in same folder where this is running")
$Label2 = GUICtrlCreateLabel("Internet Connection Required for Email", 30, 72, 190, 17)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
 
 Global $inifile = "\Get_Inv.ini"
 
if  FileExists (@ScriptDir&$inifile) Then
    ;MsgBox(0,"T","Exists")
Else
    $createini = MsgBox(4,"Error","The Config File doesn't exist.  Shall I create one?  If Yes, you will need to edit it before running the program again.")
    if $createini = 6 Then
        SplashTextOn ("Creating...","Creating Config file.  The file needs to be edited before continuing so I'm exiting the program.", 300, 100)
        IniWrite (@ScriptDir&$inifile,"admin","email","This email address is being protected from spambots. You need JavaScript enabled to view it.")
        IniWrite (@ScriptDir&$inifile,"search","file0","Edit me")
        IniWrite (@ScriptDir&$inifile,"search","file1","Edit me")
        IniWrite (@ScriptDir&$inifile,"Internet","req","1")
        sleep (3000)
        SplashOff()
        Exit
    ElseIf $createini = 7 Then
        SplashTextOn ("Exiting...","No Config file.  I'm exiting the program.", 300, 100)
        sleep (2000)
        SplashOff()
        Exit
    Else
        Exit
    EndIf
 
EndIf
 
Global $reqinternet = IniRead(@ScriptDir&$inifile,"Internet","require","")
if $reqinternet = 1 Then
    ;MsgBox (0,"T",$reqinternet)
Elseif $reqinternet = 0 Then
        SplashTextOn ("Internet is not required...","Check the Config file.  No email will be sent and the config file saved in the App folder.", 300, 100)
        sleep (10000)
        SplashOff()
Else
    ;MsgBox(0,'T',$reqinternet)
    SplashTextOn ("Exiting...","Error in the Config file.  I'm exiting the program.", 300, 100)
    sleep (2000)
    SplashOff()
EndIf
 
if $reqinternet = 1 Then
    checkinternet()
EndIf
 
While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        case $button1
            Serial_Number()
 
EndSwitch
WEnd
 
func sendtomail($includeemail,$includebody)
    if $reqinternet = 1 Then
        checkinternet()
    EndIf
 
    ;##################################
    ; Variables
    ;##################################
 
    $SmtpServer = "emailserver.com"     ; address for the smtp-server to use - REQUIRED
    $FromName = "Inventory Script"                      ; name from who the email was sent
    $FromAddress = "This email address is being protected from spambots. You need JavaScript enabled to view it." ; address from where the mail should come
    $ToAddress = $includeemail   ; destination address of the email - REQUIRED
    $Subject = @ComputerName&" Inventory"      ; subject from the email - can be anything you want it to be
    $Body = $includebody                              ; the messagebody from the mail - can be left blank but then you get a blank mail
    $AttachFiles = ""                       ; the file(s) you want to attach seperated with a ; (Semicolon) - leave blank if not needed
    $CcAddress = ""       ; address for cc - leave blank if not needed
    $BccAddress = ""     ; address for bcc - leave blank if not needed
    $Importance = "Normal"                  ; Send message priority: "High", "Normal", "Low"
    $Username = "This email address is being protected from spambots. You need JavaScript enabled to view it."                    ; username for the account used from where the mail gets sent - REQUIRED
    $Password = "emailpassword"                  ; password for the account used from where the mail gets sent - REQUIRED
    $IPPort = 465                            ; port used for sending the mail
    $ssl = 1                                ; enables/disables secure socket layer sending - put to 1 if using httpS
    ;$IPPort=465                          ; GMAIL port used for sending the mail
    ;~ $ssl=1                               ; GMAILenables/disables secure socket layer sending - put to 1 if using httpS
 
    ;##################################
    ; Script
    ;##################################
    Global $oMyRet[2]
    Global $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc")
    $rc = _INetSmtpMailCom($SmtpServer, $FromName, $FromAddress, $ToAddress, $Subject, $Body, $AttachFiles, $CcAddress, $BccAddress, $Importance, $Username, $Password, $IPPort, $ssl)
    SplashOff()
    If @error Then
        MsgBox(0, "Error sending message", "Error code:" & @error & "  Description:" & $rc)
    Else
        MsgBox(0,"Successful","Message Sent")
    EndIf
 
EndFunc
 
Func Serial_Number()
 
    $txtpath = @TempDir
    $txtfile = "\serial.txt"
    $sendfile = "\"&@ComputerName&".txt"
 
    RunWait(@ComSpec & ' /c ' & 'wmic bios get serialnumber /VALUE >> '&$txtpath&$txtfile,"", @SW_HIDE)
    RunWait(@ComSpec & ' /c ' & 'wmic computersystem get model /VALUE >> '&$txtpath&$txtfile,"", @SW_HIDE)
    RunWait(@ComSpec & ' /c ' & 'wmic computersystem get manufacturer /VALUE >> '&$txtpath&$txtfile,"", @SW_HIDE)
    addproductid($txtpath&$txtfile)
    RunWait(@ComSpec & ' /c ' & 'wmic computersystem get name /VALUE >> '&$txtpath&$txtfile,"", @SW_HIDE)
    RunWait(@ComSpec & ' /c ' & 'wmic cpu get name /VALUE >> '&$txtpath&$txtfile,"", @SW_HIDE)
    calcgb($txtpath&$txtfile,1)
 
    $file=($txtpath&$txtfile)
    $filewr=($txtpath&$sendfile)
    $fileread= FileRead($file)
    $filechange1 = StringReplace($fileread,@CRLF,",")
    $filechange2 = StringReplace ($filechange1,",,,,,",@crlf)
    $filechange3 = StringReplace ($filechange2,",,","")
    $filechange = StringReplace ($filechange3,",",@CRLF,1)
 
    SplashTextOn ("Processing...","Please wait...",200,70)
    RunWait(@ComSpec & ' /c ' & 'wmic product list brief /format:list > '&$txtpath&"\plist.txt","", @SW_HIDE)
    SplashOff()
    SplashTextOn ("Working...","Please wait...",200,70)
 
    $fopn = FileOpen($filewr,$FO_APPEND)
    FileWrite ($fopn,$filechange)
 
    FileWriteLine($fopn, @OSVersion&" "&@OSArch)
    FileWriteLine($fopn, "OS Build:"&@OSBuild)
    FileWriteLine($fopn, "Service Pack:"&@OSServicePack)
    FileWriteLine($fopn,"Date and Time: "&@MON&"/"&@MDAY&"/"&@YEAR&"  "&@HOUR&":"&@MIN&":"&@SEC&@CRLF&"**************************")
 
    $fopnav = FileOpen($txtpath&"\plist.txt",$FO_APPEND)
    ;Look for installed apps in registry
    $subkey = "None"
    $i=1
    While $subkey <> ""
        $subkey = RegEnumKey("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall",$i)
        ;MsgBox (0,"Subkey # " &$i&" Under uninstall",$subkey)
        $removejunklines = StringInStr($subkey,"{")
        if $removejunklines = 0 Then
            FileWriteLine ($fopnav,"REG:"&$subkey&@CRLF)
        EndIf
        $i+= 1
    WEnd
 
    $searchnum = 0
    $searchname = "file"
    FileSetPos($fopnav,0,$FILE_BEGIN)
    while $searchname <> ""
        $searchname = IniRead(@ScriptDir&$inifile,"search","file"&$searchnum,"")
        ;MsgBox(0,"TTT",$searchname&"--file"&$searchnum)
        if $searchname = "" then ExitLoop
        ; find line with search string
        $iLine = 0
        $sLine = ''
        $iValid = 0
        $x = 0
        while $x < 1
            $iLine += 1
            $sLine = FileReadLine ($fopnav)
            if @error = -1 then
                if $searchname = "All" Then
                    ExitLoop 2
                EndIf
                ;MsgBox (0,"TITLE",@error)
                ;FileWriteLine ($fopn,$searchname&" Not Found: "&@CRLF)
                ;FileWriteLine ($fopn,"======================")
                FileSetPos($fopnav,0,$FILE_BEGIN)
                ExitLoop
            EndIf
            if $searchname <> "All" Then
                ;test line for $search string until the flag iValid is set
                if StringInStr ($sLine, $searchname) And Not $iValid Then
                    $iValid = 1
                    ;ContinueLoop
                EndIf
            Else
                $iValid = 1
            EndIf
 
            if $iValid Then
                $iValid += 1
                $appwrite = $sLine
                $removeREG = StringInStr($appwrite,"REG:")
                if $removeREG <> 0 Then
                    if $searchname = "All" then
                        FileWriteLine ($fopn,"Found: "&$appwrite)
                    Else
                        FileWriteLine ($fopn,$searchname&" Found: "&$appwrite)
                    EndIf
                    FileWriteLine ($fopn,"======================")
                    $iValid= 0
                    ContinueLoop
                EndIf
 
                $removestr = StringInStr($appwrite,"Identifying")
                $removeven = StringInStr($appwrite,"Vendor")
                if $removestr = 0 AND $removeven = 0 Then
                    if $searchname = "All" then
                        FileWriteLine ($fopn,"Found: "&$appwrite)
                    else
                        FileWriteLine ($fopn,$searchname&" Found: "&$appwrite)
                    EndIf
                EndIf
                if $iValid > 4 then
                    ;Reset valid count
                    FileWriteLine ($fopn,"======================")
                    $iValid = 0
                    ;ExitLoop
                EndIf
 
            EndIf
 
        WEnd
        $searchnum = $searchnum+1
    WEnd
 
    ;send email (email address, body)
    $emailname = IniRead(@ScriptDir&$inifile,"admin","email","")
    FileSetPos($fopn,0, $FILE_BEGIN)
    $emailbody = FileRead($fopn)
    if $reqinternet = 1 Then
        checkinternet()
        SplashTextOn ("Working...","Trying to send email...",200,70)
        sendtomail($emailname,$emailbody)
    EndIf
    SplashOff()
    FileClose($fopn)
    FileClose($fopnav)
    $savefile = GUICtrlRead($Checkbox1)
    if $savefile = 1 OR $reqinternet = 0 Then
        FileCopy(@TempDir&$sendfile,@ScriptDir&$sendfile, $FC_OVERWRITE)
        FileDelete($filewr) ; Inventory File
    Else
        FileDelete($filewr) ; Inventory File
    EndIf
    FileDelete ($file) ; Generated File
    FileDelete ($txtpath&"\plist.txt") ; Generated File
    ; -------------------
    ; PROGRAM ENDS
    ; -------------------
 
EndFunc
 
func checkinternet()
    $x = 0
    While $x = 0
        ;--------------------------------------------------------------------------------------------
        ;check $ret[0] for trueness, and $ret[1] for type of connection according to variables provided...
        ;--------------------------------------------------------------------------------------------
        $INTERNET_CONNECTION_MODEM          = 0x1
        $INTERNET_CONNECTION_LAN            = 0x2
        $INTERNET_CONNECTION_PROXY          = 0x4
        $INTERNET_CONNECTION_MODEM_BUSY     = 0x8
        $INTERNET_RAS_INSTALLED             = 0x10
        $INTERNET_CONNECTION_OFFLINE        = 0x20
        $INTERNET_CONNECTION_CONFIGURED     = 0x40
 
        $ret = DllCall("WinInet.dll","int","InternetGetConnectedState","int_ptr",0,"int",0)
 
        If $ret[0] then
            ;check type of connection
            $sX = "Connected !" & @LF & "------------------" & @LF
            If BitAND($ret[1], $INTERNET_CONNECTION_MODEM)      Then $sX = $sX & "MODEM" & @LF
            If BitAND($ret[1], $INTERNET_CONNECTION_LAN)        Then $sX = $sX & "LAN" & @LF
            If BitAND($ret[1], $INTERNET_CONNECTION_PROXY)      Then $sX = $sX & "PROXY" & @LF
            If BitAND($ret[1], $INTERNET_CONNECTION_MODEM_BUSY) Then $sX = $sX & "MODEM_BUSY" & @LF
            If BitAND($ret[1], $INTERNET_RAS_INSTALLED)         Then $sX = $sX & "RAS_INSTALLED" & @LF
            If BitAND($ret[1], $INTERNET_CONNECTION_OFFLINE)    Then $sX = $sX & "OFFLINE" & @LF
            If BitAND($ret[1], $INTERNET_CONNECTION_CONFIGURED) Then $sX = $sX & "CONFIGURED" & @LF
        Else
            $x = 0
            MsgBox(0,"Not Connected","Please connect to the internet before continuing.")
            ;$sX = "Not Connected"
            ContinueLoop
 
        Endif
 
        ;SplashTextOn("Connected...","Connection Detected",200,100)
        ;sleep (1000)
        ;SplashOff()
        $x=1
        ;MsgBox(4096,$ret[0] & ":" & $ret[1],$sX)
 
     WEnd
 
EndFunc
 
func calcgb($pathtxt,$str2src)
    if $str2src = 1 Then
        $str2srcname = "TotalPhysicalMemory="
        $str2len = 20
        $str2dec = 3
    Else
        $str2srcname = "Size="
        $str2len = 5
        $str2dec = 0
    EndIf
 
    $filepk=($pathtxt)
    $fopnpk = FileOpen($filepk,$FO_APPEND)
    ; ---------MAYBE------------
    ; Check the drive type for C:\
    $sInfo = DriveGetType("C:\")
    if $sInfo <> "" Then
        ;MsgBox($MB_SYSTEMMODAL, "", "Drive Type: " & $sInfo)
        ;write a line
        FileWrite ($fopnpk,@CRLF&@CRLF&"Drive Type="&$sInfo&@CRLF&@CRLF&@CRLF)
    EndIf
    ; Check the SSD status for C:\
    $sInfo = DriveGetType("C:\", $DT_SSDSTATUS)
    if $sInfo <> "" Then
        ;MsgBox($MB_SYSTEMMODAL, "", "Drive SSD: " & $sInfo)
        ;write a line
        FileWrite ($fopnpk,@CRLF&@CRLF&"Drive Type (SSD)="&$sInfo&@CRLF&@CRLF&@CRLF)
    EndIf
    ; Check the SSD status for disk 0
    $sInfo = DriveGetType(0, $DT_SSDSTATUS)
    if $sInfo <> "" Then
        ;MsgBox($MB_SYSTEMMODAL, "", "Drive SSD: " & $sInfo)
        ;write a line
        FileWrite ($fopnpk,@CRLF&@CRLF&"Drive Status (SSD)="&$sInfo&@CRLF&@CRLF&@CRLF)
    EndIf
    ; Check the bus type status for disk 0
    $sInfo = DriveGetType(0, $DT_BUSTYPE)
    if $sInfo <> "" Then
        ;MsgBox($MB_SYSTEMMODAL, "", "Drive Bus: " & $sInfo)
        ;write a line
        FileWrite ($fopnpk,@CRLF&@CRLF&"Drive Bus="&$sInfo&@CRLF&@CRLF&@CRLF)
    EndIf
 
    Local $iTotalSpace = DriveSpaceTotal(@HomeDrive & "\") ; Find the total disk space of the home drive, generally this is the C:\ drive.
    $TotalSpace = round($iTotalSpace/1000,$str2dec)
    ; MsgBox(0, "", "Total Space: " & $TotalSpace &"GB")
    FileWrite ($fopnpk,@CRLF&@CRLF&"Total Disk Space="&$TotalSpace&" GB"&@CRLF&@CRLF&@CRLF)
 
    Local $RAMARR = MemGetStats()
    $TotalRAM = round($RAMARR[1]/1000000,$str2dec)
    ;MsgBox(0, "", "Total physical RAM (GB): " & $TotalRAM)
    FileWrite ($fopnpk,@CRLF&@CRLF&"Total RAM="&$TotalRAM&" GB"&@CRLF&@CRLF&@CRLF)
 
    FileClose($fopnpk)
 
EndFunc
 
func addproductid($pathtxt)
    $productkey = RegRead("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\BIOS\","SystemSKU")
    ;MsgBox (0,"TTT",$productkey)
    if $productkey = "" Then
        $productkey = "Not Found"
    EndIf
    $filepk=($pathtxt)
    $fopnpk = FileOpen($filepk,$FO_APPEND)
    FileWrite ($fopnpk,@CRLF&@CRLF&"Product Key="&$productkey&@CRLF&@CRLF&@CRLF)
    FileClose($fopnpk)
EndFunc
 
; The UDF
Func _INetSmtpMailCom($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject = "", $as_Body = "", $s_AttachFiles = "", $s_CcAddress = "", $s_BccAddress = "", $s_Importance="Normal", $s_Username = "", $s_Password = "", $IPPort = 25, $ssl = 0)
    Local $objEmail = ObjCreate("CDO.Message")
    $objEmail.From = '"' & $s_FromName & '" <' & $s_FromAddress & '>'
    $objEmail.To = $s_ToAddress
    Local $i_Error = 0
    Local $i_Error_desciption = ""
    If $s_CcAddress <> "" Then $objEmail.Cc = $s_CcAddress
    If $s_BccAddress <> "" Then $objEmail.Bcc = $s_BccAddress
    $objEmail.Subject = $s_Subject
    If StringInStr($as_Body, "<") And StringInStr($as_Body, ">") Then
        $objEmail.HTMLBody = $as_Body
    Else
        $objEmail.Textbody = $as_Body & @CRLF
    EndIf
    If $s_AttachFiles <> "" Then
        Local $S_Files2Attach = StringSplit($s_AttachFiles, ";")
        For $x = 1 To $S_Files2Attach[0]
            $S_Files2Attach[$x] = _PathFull($S_Files2Attach[$x])
;~          ConsoleWrite('@@ Debug : $S_Files2Attach[$x] = ' & $S_Files2Attach[$x] & @LF & '>Error code: ' & @error & @LF) ;### Debug Console
            If FileExists($S_Files2Attach[$x]) Then
                ConsoleWrite('+> File attachment added: ' & $S_Files2Attach[$x] & @LF)
                $objEmail.AddAttachment($S_Files2Attach[$x])
            Else
                ConsoleWrite('!> File not found to attach: ' & $S_Files2Attach[$x] & @LF)
                SetError(1)
                Return 0
            EndIf
        Next
    EndIf
    $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = $s_SmtpServer
    If Number($IPPort) = 0 then $IPPort = 25
    $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = $IPPort
    ;Authenticated SMTP
    If $s_Username <> "" Then
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = $s_Username
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = $s_Password
    EndIf
    If $ssl Then
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
    EndIf
    ;Update settings
    $objEmail.Configuration.Fields.Update
    ; Set Email Importance
    Switch $s_Importance
        Case "High"
            $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "High"
        Case "Normal"
            $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "Normal"
        Case "Low"
            $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "Low"
    EndSwitch
    $objEmail.Fields.Update
    ; Sent the Message
    $objEmail.Send
    If @error Then
        SetError(2)
        Return $oMyRet[1]
    EndIf
    $objEmail=""
EndFunc   ;==>_INetSmtpMailCom
;
;
; Com Error Handler
Func MyErrFunc()
    $HexNumber = Hex($oMyError.number, 8)
    $oMyRet[0] = $HexNumber
    $oMyRet[1] = StringStripWS($oMyError.description, 3)
    ConsoleWrite("### COM Error !  Number: " & $HexNumber & "   ScriptLine: " & $oMyError.scriptline & "   Description:" & $oMyRet[1] & @LF)
    SetError(1); something to check for when this function returns
    Return
EndFunc   ;==>MyErrFunc

 

 

Last modified on Friday, 25 May 2018 01:55
Sunday, 22 October 2017 21:00

Fix Corrupted Windows Profile

Rate this item
(0 votes)

 

Over the years, I've had various people that have had trouble logging into their Windows computer.  Windows would login to a Temporary profile.  It is an easy fix, but not so easy from a distance since it involves editing the registry.  I don't like sending regedit commands to users since so many things could go wrong.  In response to the many requests I received, I wrote the script below in AutoIT.  It's simple and easy for the user to double-click the executable file after restarting into Safe Mode.  It fixes the Corrupted Profile.  The code isn't pretty, but leave a comment if you find anything that doesn't work.

If you want to learn more about the Windows Temporary Profile, search for:  windows temporary profile fix

I hope this helps someone.

Thanks!


#NoTrayIcon #RequireAdmin #include Opt("TrayMenuMode",3) ;$settingsitem = TrayCreateItem("Settings") ;TrayCreateItem ("") $exititem = TrayCreateItem("Exit") TraySetIcon("Shell32.dll",14) TraySetToolTip("Running Fix Profile") TraySetState() Func CheckMenuItem() $msg = TrayGetMsg() Select Case $msg = $exititem Exit EndSelect EndFunc For $i = 1 To 50 Local $var = RegEnumKey("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList", $i) CheckMenuItem() If @error <> 0 Then ExitLoop if stringright ($var,4) = ".bak" Then $slen = StringLen ($var) $new = stringleft ($var,$slen - 4) $copykey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" & $new $destkey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" & $new & ".old" _RegMoveKey($copykey, $destkey) $movesourcekey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" & $var $movedestkey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" & $new _RegMoveKey ($movesourcekey, $movedestkey) ; Parameters.....: $s_key - Source key ; $s_val - Source value ;RefCount set to 0 RegWrite ($movedestkey,"RefCount","REG_DWORD",0) CheckMenuItem() ; Write Log file Local $file = FileOpen("fixlog.txt", 1) If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Get current system time $tCur = _Date_Time_GetSystemTime() FileWrite($file, _Date_Time_SystemTimeToDateTimeStr($tCur) & @CRLF) FileWrite($file, "Move From: " & $copykey & @CRLF) FileWrite($file, "Move To: " & $destkey & @CRLF) FileWrite($file, "Move From: " & $movesourcekey & @CRLF) FileWrite($file, "Move To: " & $movedestkey & @CRLF) FileWrite($file, "Changed RefCount Value to 0" & @CRLF) FileClose($file) MsgBox (0,"Completed","Press OK to Exit. Restart computer and login like normal.") Exit Else MsgBox (0,"Completed","Press OK to Exit. A bad profile was not found. Please contact the Help Desk for more troubleshooting ideas.") Exit EndIf Next

Last modified on Sunday, 22 October 2017 21:38
Thursday, 12 October 2017 01:03

OpenWrt, OpenVPN, Two Signals, One Router

Rate this item
(1 Vote)

While living outside the U.S., I, often, found myself needing a VPN connection to do stuff that made me look like I was in the U.S. I chose an OpenVPN service because it was simple to set up, but ran into trouble when I needed it for multiple devices. I installed the OpenVPN software on my computer, my children's computer, and my wife's computer, but found I couldn't connect any Streaming Device to it because I couldn't install the software on it. With the VPN service I had, I could only connect 2 devices at a time so this, quickly, became troublesome. I began thinking about what to do. I could purchase (or use) another router and configure it for an OpenVPN connection, but I would have two wifi routers and a modem sitting around. I, really, didn't want the extra cables and wires collecting dust.

Thinking through this,I had another idea. Instead of having two wifi routers, what if I could configure the OpenWRT to router to broadcast two wifi signals with one connecting to an OpenVPN server and the other one connecting locally? This way, I would only have one router and one modem sitting around. With this in mind, I went on a tech hunt and, finally, figured it out. After I configured mine, I configured many others as people learned about what I did. These routers were quite popular at one time with folks around me. For your, geeky, reading pleasure, the steps that I do to make one are below.

Enjoy!

Warning:  There is a lot I don't explain in this walkthrough as these are my notes.  If you are unfamiliar with what you see below, please ask in the comments or ask a trusted friend to help.


The idea: Using an OpenWRT flashed router, broadcast two wireless signals. One connecting to an OpenVPN server (ex. Witopia, StrongVPN, etc.) and the other connecting locally

The Purpose: To secure a connection for online banking, online purchasing, watching Netflix, Hulu, etc., on media devices and to have local internet access, when needed. Depending on which wireless SSID that is connected, you can either be running over a VPN or locally. For example, you can connect your media devices to the VPN SSID and run Netflix, Hulu, or to just have a secure connection all the time and/or connect to the other SSID when the VPN connection goes down or to have a faster speed

Before attempting this, I looked around on the internet and didn't find a walk through, so if there is one, please let me know. However, I did find lots of help that I picked up from different places. Some of them include:

http://wiki.openwrt.org/doc/howto/vpn.client.pptp

https://forum.openwrt.org/viewtopic.php?id=39223

There were a few more, but can't remember which ones now.

The instructions below are written for Attitude Adjustment 12.09 RC2, but they will work on any later version


Here is what I do:

Purchase OpenVPN service from a reputable company (ex. Witopia, StrongVPN, etc.)

Install OpenVPN and ip on the OpenWRT router:

  • opkg update

  • opkg install openvpn-openssl ip

Add a new Wireless controller as normal (Network->Wifi).

  • SSID: <your 'secure' name>

  • Mode: Access Point

  • Attach the network to the LAN network for now.

  • We'll test it to make sure it works and that you have internet access in a few moments...

  • Add Wireless Security and any other wireless setting you desire

  • Save and Apply

  • Click 'Enable'

Add a new interface (Network->Interfaces->Add new interface)

  • Choose Name (ex. Slan) -If you change this name (Slan), make sure to change the other references to it below

  • Select 'Static Address.'

  • Create bridge = unchecked

  • Cover the following interfaces = Choose newly created wireless Network

  • Submit

Choose IP address in another subnet, for example:

  • IPv4 address = 192.168.20.1

  • IPv4 netmask = 255.255.255.0

  • Leave Gateway blank

  • Custom DNS server = 192.168.20.1

  • Save and Apply

Firewall Settings

  • Create new Zone = <your 'secure' lan name> (needs to be different than wlan above. I choose the name of the lan. ex. slan)

  • Click 'Setup DHCP server' and use default settings unless you need something special.

  • Save and Apply

From LuCI, go to the Firewall section: Network->Firewall Section

  • Edit the LAN settings and add the newly created interface (slan) to the covered networks. There should be two now. LAN and SLAN. Wan should be checked under the Allow forward to destination zone.

  • Save and Apply.

Back to Network->Wifi section

  • Edit the newly created wireless interface and uncheck the 'lan' network. Only 'slan' or whatever you called it should be checked.

  • Save and Apply

Test the wireless connection. If you followed the above steps, you should have internet access and have an ip address in the 192.168.20.0 subnet.

 

 Once the test is good, go to Network->Firewall and edit each setting so it matches the table below: 

Name

Input

Output

Forward

Masquerade & MSS clamping

Covered Networks

Allow Forward To

Allow Forward From

Lan

Accept

Accept

Reject

Both Blank

Lan

wan

 

Wan

Reject

Accept

Reject

Both Checked

Wan

 

lan

Slan

Accept

Accept

Reject

Both Blank

Slan

Ovpn 1

 

Ovpn 1

Accept

Accept

Reject

Check Masquerade

MSS Blank

Ovpn 1

 

Slan

1 See below for more information about ovpn firewall zone. Just edit Lan and Wan at this point. We'll finish this below.

 

The rest of the setup process will be on the command line so login to the router via SSH (see Command-Line Interface(CLI))

  • Configure the network – edit file: /etc/config/network

    • Add ovpn interface

config 'interface' 'ovpn'

option 'ifname' 'tun0'

option 'defaultroute' '0'

option 'peerdns' '0'

option 'proto' 'none'

 

Configure the firewall – edit file: /etc/config/firewall

  • Configure Forward Zone for ovpn

config 'forwarding'

option 'dest' 'ovpn'

option 'src' 'slan'

 

  • Configure OpenVPN Firewall zone

config zone

option name 'ovpn'

option input 'ACCEPT'

option forward 'REJECT'

option output 'ACCEPT'

option network 'ovpn'

 

Add new table to routing table – edit file: /etc/iproute2/rt_tables

  • install ip from software repo, if the iproute2 folder doesn't exist

  • Add the one highlighted line below

# reserved values

#

255 local

254 main

253 default

10 vpn

0 unspec

#

# local

#

#1 inr.ruhep

 

Create route-up.sh and tunneldown.sh files in root folder with favorite editor (ex. vi).  These files do not exist so they need to be created and edit the IP address as shown below

  • FileName: /root/tunneldown.sh

#!/bin/sh

ip rule del from <ip address of slan>/24 table vpn

ip route flush table vpn

#example: ip rule del from 192.168.20.1/24 table vpn

  • FileName: /root/route-up.sh

#!/bin/sh

ip route add $ifconfig_remote dev $dev proto kernel scope link src $ifconfig_local

ip route add $route_network_1 via $ifconfig_remote dev $dev metric 1 table vpn

ip route add 0.0.0.0/1 via $ifconfig_remote dev $dev table vpn

ip route add 128.0.0.0/1 via $ifconfig_remote dev $dev table vpn

# Add route back to local network

ip route add <ip subnet from slan>/24 via <slan Gateway> table vpn

#example : ip route add 192.168.20.0/24 via 192.168.20.1 table vpn

# Add rule from local network to VPN Gateway

ip rule add from <ip address from slan>/24 table vpn

#example: ip rule add from 192.168.20.1/24 table vpn


Create and edit the OpenVPN Config below and save it on your computer as .ovpn (ex. vpn.dallas.ovpn). Place it in the same folder where the .key, .crt, and ca.crt files are located that you received from the OpenVPN service

  • Edit and/or add the yellow highlighted lines

#####################################

# OpenVPN configuration file

#####################################

client

route-up /root/route-up.sh

route-noexec

down /root/tunneldown.sh

script-security 3 system

dev tun

proto udp

remote <vpn.server.name> 1194

resolv-retry infinite

nobind

persist-key

persist-tun

ns-cert-type server

cipher bf-cbc

comp-lzo

verb 3

mute 20

ca /root/ca.crt

mssfix 1300

key /root/<openvpn>.key

cert /root/<openvpn>.crt

#tls-auth ta.key 1

 

Copy Files to router (using favorite File transfer program)

  • In linux, use Terminal and type the following from the folder where the four files are located.

    • scp ca.crt <openvpn>.ovpn <openvpn>.crt <openvpn>.key This email address is being protected from spambots. You need JavaScript enabled to view it..x.x:/root

  • SSH back into the router

 

Make the files, route-up.sh and tunneldown.sh, executable

  • From the router, run:

    • chmod u=rwx /root/route-up.sh /root/tunneldown.sh

 

Make the .key and .crt non-accessible to others or OpenVPN will fuss at you

  • chmod u=rw,go= <openvpn>.key <openvpn>.crt

 

Now comes the fun...

  • Test the connection and get the DNS number you'll use in the next section
  •  Still in SSH terminal, Type: openvpn –config vpn.<whateveryoucalledit>.ovpn

  •  Watch the messages scroll up the screen. If all is successful, you'll see 'Initialization Sequence Completed' on the last line.

  •  If successful, scroll up and look at the lines until you see the one that reads DNS:

  •  PUSH: Received control message: 'PUSH_REPLY,redirect-gateway def1,dhcp-option DNS 10.x.x.x,route 10.x.x.x,topology net30,ping 10,ping-restart 60,ifconfig 10.x.x.x 10.x.x.x'

  •  Also watch for “RNETLINK answers: File exists.” This means the route-up file was successful.

  •  Once you have the DNS address, we can modify the settings

  •  Configure dnsmasq settings – edit file: /etc/dnsmasq.conf

 Add the highlighted lines to the file

# Change the following lines if you want dnsmasq to serve SRV

# records.

# You may add multiple srv-host lines.

# The fields are <name>,<target>,<port>,<priority>,<weight>

# Added for OpenVPN DNS

dhcp-option=<name of network interface>, 6, <IP Address from OpenVPN Connection>

# example: dhcp-option=slan,6,10.x.x.x

# A SRV record sending LDAP for the example.com domain to

# ldapserver.example.com port 289

#srv-host=_ldap._tcp.example.com,ldapserver.example.com,389

 

Create and name a startup file and place it in /etc/init.d/ so it can be enabled and disabled from OpenWrt GUI

  • Create file with your favorite text editor (ex. vi /etc/init.d/openvpn-client)

#!/bin/sh /etc/rc.common

# Copyright (C) 2007 OpenWrt.org

START=90

start()

{

logger -t "openvpn" "starting openvpn-client"

openvpn --daemon --config /root/vpn.<whateveryoucalledit>.ovpn

}

stop()

{

logger -t "openvpn" "stopping openvpn-client"

killall openvpn

sleep 3

}

  • Make it executable: chmod u=rwx /etc/init.d/openvpn-client

  • Exit the SSH Shell!

 

  • From Web GUI, go to System -> Startup

    • The 'openvpn-client' and 'openvpn' show in 'Initsscripts' as disabled

    • Enable openvpn and refresh to make sure it is running

    • If it stays in the Enabled state, finish the firewall settings:

Name

Input

Output

Forward

Masquerade & MSS clamping

Covered Networks

Allow Forward To

Allow Forward From

Lan

Accept

Accept

Reject

Both Blank

Lan

wan

 

Wan

Reject

Accept

Reject

Check Masquerade

MSS Blank

Wan

 

lan

Slan

Accept

Accept

Reject

Both Blank

Slan

Ovpn 1

 

Ovpn 1

Accept

Accept

Reject

Check Masquerade

MSS Blank

Ovpn 1

 

Slan


Restart the router

If everything works, when you connect to the secure wireless network, your ip address will be in the location of the vpn server.

All DONE!


Troubleshooting

  • If, after enabling the openvpn-client, it comes back disabled, there is something wrong in the configuration. The best way to debug or troubleshoot the connection is to SSH into the router and start the openvpn connection by typing:

  • openvpn --config <openvpn>.ovpn

  • Watch toward the end to see if there are any errors in the route-up.sh script

  • Press 'Ctrl C' and watch what happens to the tunneldown.sh script

  • If you forgot to make the files executable, the connection will fail.



 

Last modified on Saturday, 14 October 2017 03:36
Monday, 09 October 2017 02:18

K2 Comment Notification

Rate this item
(1 Vote)

Today, I was messing around with the K2 Joomla Plugin. I got it working and everything was great. The only problem I found is if someone leaves a comment on an article, no one will know unless the page is visited again. I searched around and found a plugin that cost some moolah, but I didn't want to go that route. Another one I found was not available for downloading. So, away I went on a development hunt to figure out what I could do.

I ended up writing my own PHP script.  It creates a new column in K2's comment table.  When the script runs, it looks for 0's in the new column and sends an email with the information it finds in the record.  It's not a perfect solution, but it works for me.  I set it to run once a day so I'll receive all the comments, in separate emails, daily.

It's not a Joomla plugin, but it is still really easy to install. I have two .php files. One for authenticating and the other is the script. I did it this way in case someone wants to put the script in the 'public_html' folder. However, I recommend creating a folder within the Home folder so it's not accessible from the Internet and run it as a cron job.

For my example below, I'll use the folder 'K2Send'.  Let's begin:

Create a folder to hold two .php files.

/home/<<user name>>/K2Send

Create two files within this folder (ex. K2Send.php and K2SendAuth.php)

Copy the following into the K2SendAuth.php file and then edit it to reflect your server and database information:


<php
// Information for K2 Send Comments
$dbserver = 'localhost';
$dbuser= 'Database User';
$dbpass = 'Database Password';
$db = 'Database';
$dbtable = "K2 comments Table";

// This is the name of the column that will be added to the K2 Comment Table.
// It can be labeled anything
$dbcolumn = "Notify";

// fromEmail = What email address it is sent from
$fromEmail = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

// toEmail = What email address it is sent to
$toEmail = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

// Server domain where K2 is running
$fromdomain = "mywebdomain.com";

// textEmail =0 (email is formatted HTML)
// textEmail = 1 (email is formatted Text)
$textEmail = "0";
?>


 Now that you have the auth file done, open up the K2Send.php file and paste the following in it and edit the 'require_once' line to reflect the path:


<?php
/*
To Do....
1. Check if the notification column is in the K2 comments table
2. If not, create it
3. Check if column contains a 0
4. If so, send email
5. Replace the 0 with a 1
*/

//Require Authenication File
require_once "/home/---UserNAME---/K2Send/K2SendAuth.php";

$servername = $dbserver;
$username = $dbuser;
$password = $dbpass;
$dbname = $db;
$columnexist = 0;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->;connect_error) {
    die("Connection failed: " . $conn->;connect_error);
}

// 1. Check if the notification column is in the K2 comments table
$sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_NAME`='{$dbtable}'";
$result = $conn->;query($sql);

if ($result->num_rows > 0)
{
    // output data of each row
    while($row = $result->fetch_assoc())
    {
        if ($row["COLUMN_NAME"]==$dbcolumn)
        {
            echo "This column- ".$dbcolumn." - Exists!\n\n";
            $columnexist=1;
        }
    }
    
    if ($columnexist==0)         
        {
// 2. If not, create it
            $add = "ALTER TABLE ".$dbtable." ADD ".$dbcolumn." INT( 11 ) NOT NULL";
            $result = $conn->query($add) or die(mysqli_error($conn));
        }
}
else
{
    echo "0 results";
}

// 3. Check if column contains a 0
$sql = "SELECT * FROM ".$dbtable;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

        /* echo "-". $row["id"]."-".$row["userName"]."-".$row["commentDate"].  
        "-" . $row["commentText"]. "-" . $row["commentEmail"].  "-" . $row["commentURL"].  "-" .
        $row["published"]. "-" . $row[$dbcolumn]."\n\n";
        */
        echo "Searching Comments Table.\n\n";
        
        if ($row[$dbcolumn]==0)
        {
// 4. If so, send email in text or HTML
// $textEmail = 0 (HTML)
            echo "Found a new comment.\n\n";
            if ($textEmail == 0)
            {
                $message = "
                <html>
                <head>
                <title>K2 Commment</title>
                </head>
                <body>
                <p>New K2 Comment</p>
                <table>
                <tr>
                <th>id</th>
                <th>Item</th>
                <th>User</th>
                <th>User Name</th>
                <th>Date</th>
                <th>Comment</th>
                <th>User Email</th>
                <th>User URL</th>
                </tr>
                <th>id</th>
                <th>Item</th>
                <th>User</th>
                <th>User Name</th>
                <th>Date</th>
                <th>Comment</th>
                <th>User Email</th>
                <th>User URL</th>
                </tr>
                <tr>
                <td>".$row["id"]."</td>
                <td>".$row["itemID"]."</td>
                <td>".$row["userID"]."</td>
                <td>".$row["userName"]."</td>
                <td>".$row["commentDate"]."</td>
                <td>".$row["commentText"]."</td>
                <td>".$row["commentEmail"]."</td>
                <td>".$row["commentURL"]."</td>
                </tr>
                </table>
                </body>
                </html>
                ";

                // Always set content-type when sending HTML email
                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            }
            else
            {
              //Send Text Email
              $message = "New K2 Comment\nID = ".$row["id"]."\n ItemID = ".$row["itemID"].
              "\n UserID = ".$row["userID"]."\n User Name=  ".$row["userName"]."\n Date = ".
              $row["commentDate"]."\n Comment = ".$row["commentText"]."\n User Email = ".
              $row["commentEmail"]."\n User URL = ".$row["commentURL"]."\n";
            }

            $to = $toEmail;
            $subject = "K2 Comments from ".$fromdomain;
            // More headers
            $headers .= 'From: '.$fromEmail . "\r\n";
            // $headers .= 'Cc: <<Put another EMAIL Address>>' . "\r\n";
            
            mail($to,$subject,$message,$headers);

// 5. Replace the 0 with a 1
            $sql = "UPDATE {$dbtable} SET {$dbcolumn}=1 WHERE id={$row["id"]}";
            if ($conn-&gt;query($sql) === TRUE) {
                echo "Record updated successfully\n\n";
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
   

        }
            echo "No new comment found.\n\n";
    }
} else {
    echo "0 results";
}

$conn->close();
echo "Exiting...\n\n";
?>

 


Add a cron job to run the K2Send.php file as often as you like.

Post a comment if you see any errors.

Enjoy!

Last modified on Sunday, 05 May 2019 18:26
Friday, 06 October 2017 13:53

Joomla LDAP Plugin - Update email address

Rate this item
(0 votes)

I spent a little while searching for a way to update the Joomla user Email Address when the email address changes in Windows Active Directory. Of course, I'm using the LDAP plugin included in Joomla 3.x. The plugin can be found here. As you see, there isn't much documentation on it.

Since I couldn't find anything, I decided to edit the php file and make it work. Below is what I did.

Hope this helps someone.


1. Found the file in my Joomla site and opened it up for editing (ldap.php)

2. Went to line 150 or right after:

if (isset($userdetails[0][$ldap_email][0]))
{
$response->email = $userdetails[0][$ldap_email][0];

3. I Inserted the code:

// Grab email address, currently, in the Joomla User table
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('email')
->from('<<INSERT JOOMLA USER TABLE>>_users')
->where('username=' . "'{$credentials['username']}'");
$db->setQuery($query);
$result = $db->loadResult();

// Update Email address if it's different
$newemail = $userdetails[0][$ldap_email][0];
if ( $result == $newemail)
{
// echo "Same";
}
else
{
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->update('<<INSERT JOOMLA USER TABLE>>_users')
->set("email = '{$newemail}'")
->where('username=' . "'{$credentials['username']}'");
$db->setQuery($query);
$found = (int) $db->execute();

}

4. Done. Now, when the user logs in, it checks the email address to see if it's different. If it is, it updates it. If it's not, nothing happens.

Last modified on Friday, 06 October 2017 14:05